OXYGENHUB
# 4b9d06778581 oxygen / crates / oxy-core / src / repo / mod.rs
89.1 KiB · Rust · last changed Fetch checks the host's transparency log (spec §14.8) 20 days ago source blame history raw
1
//! A repository on disk: the `.oxy` directory, one workspace, the operation
2
//! log, and the working-copy change (spec §12, §13.1).
3
//!
4
//! Not yet implemented from the spec: packs, checkpoints, multiple
5
//! workspaces, multi-signer policy updates, and the `objects`/`checkpoint`
6
//! endpoints. A repository without a policy is unverified and accepts
7
//! unsigned pushes; with one, everything received is checked (spec §14.5). Changes are signed individually when `core.sign` is
8
//! `change`; the default `seal` leaves them unsigned until push exists.
9
10
use crate::attest::{Attest, AttestBody};
11
use crate::diff::{ranges, split_lines, text_edits};
12
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
13
use crate::identity::{
14
    verify as verify_signature, Delegate, Domain, Identity, Scope, SecretKey, Signature,
15
};
16
use crate::ids::{ChangeId, NodeId, WorkspaceId};
17
use crate::objects::{
18
    Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp,
19
};
20
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
21
use crate::protocol::{
22
    open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef,
23
    SignedAttest, SignedPolicy,
24
};
25
use crate::state::{FileContent, Snapshot, State};
26
use crate::store::{Store, StoreError};
27
#[allow(unused_imports)]
28
use crate::subrepo::Pin;
29
use crate::tree::OpKey;
30
use rand::RngCore;
31
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
32
use std::fs;
33
use std::io::Write;
34
use std::path::{Path, PathBuf};
35
36
pub const OXY_DIR: &str = ".oxy";
37
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
38
const FORMAT1_LINE: &str = "oxy repository format 1\n";
39
const BINARY_SNIFF: usize = 8 * 1024;
40
/// Loose objects tolerated before a commit packs them (spec §13.4).
41
pub const AUTOPACK_THRESHOLD: usize = 4096;
42
43
#[derive(Debug, thiserror::Error)]
44
pub enum RepoError {
45
    #[error("io: {0}")]
46
    Io(#[from] std::io::Error),
47
    #[error(transparent)]
48
    Store(#[from] StoreError),
49
    #[error(transparent)]
50
    Object(#[from] crate::objects::ObjectError),
51
    #[error(transparent)]
52
    State(#[from] crate::state::StateError),
53
    #[error("{0}")]
54
    Msg(String),
55
    /// The operation would leave a conflict where none may be (a rebased
56
    /// change cannot hold one); the caller may offer another way.
57
    #[error("{0}")]
58
    Conflicted(String),
59
}
60
61
pub type Result<T> = std::result::Result<T, RepoError>;
62
63
/// The operation head's reference record on a store that is not this
64
/// disk's directory (oxygen#68).
65
pub const HEAD_RECORD: &str = "ops/head";
66
67
/// How often recording an operation reads the head again when other
68
/// processes keep moving it.
69
const HEAD_TRIES: usize = 8;
70
71
/// The object store of the repository directory `oxy`: `.oxy/objects`,
72
/// or the store `storage.url` names behind a cache of `storage.cache`
73
/// bytes in `.oxy/cache` (oxygen#68). `.oxy/objects` is then only
74
/// scratch space: packs being written, and derived caches.
75
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
76
    let Some(url) = &config.storage_url else {
77
        return Ok(Store::open(oxy.join("objects"))?);
78
    };
79
    let options = crate::protocol::RemoteOptions {
80
        cache_dir: Some(oxy.join("cache")),
81
        ..Default::default()
82
    };
83
    let remote = crate::protocol::open_store(url, &options)
84
        .ok_or_else(|| {
85
            RepoError::Msg(format!(
86
                "storage.url {url}: this oxy cannot open that kind of store (dir://, or s3://, gs:// and az:// in builds with cloud stores)"
87
            ))
88
        })?
89
        .map_err(|e| RepoError::Msg(format!("open the repository's store {url}: {e}")))?;
90
    let cached = crate::strata::CachingStore::open(
91
        std::sync::Arc::from(remote),
92
        oxy.join("cache"),
93
        config.storage_cache,
94
    )
95
    .map_err(|e| RepoError::Msg(format!("open the cache for {url}: {e}")))?;
96
    Ok(Store::open_on(
97
        std::sync::Arc::new(cached),
98
        oxy.join("objects"),
99
    )?)
100
}
101
102
fn fail<T>(s: impl Into<String>) -> Result<T> {
103
    Err(RepoError::Msg(s.into()))
104
}
105
106
mod bookmarks;
107
mod checkout;
108
mod checkpoint;
109
mod config;
110
mod doctor;
111
mod fsck;
112
mod gc;
113
mod git;
114
mod history;
115
mod hooks;
116
mod hosted;
117
mod identity;
118
mod inspect;
119
mod ops;
120
mod policy;
121
mod prompt;
122
mod receipts;
123
mod revset;
124
mod snapshot;
125
pub mod strata;
126
mod subrepos;
127
mod sync;
128
mod tags;
129
#[cfg(test)]
130
mod tests;
131
mod touched;
132
mod transparency;
133
mod walk;
134
mod workspace;
135
136
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
137
pub use checkout::CheckoutReport;
138
pub use config::{parse_size, read_config_file, Config};
139
pub use doctor::{Check, DoctorReport, Health};
140
pub use fsck::{FsckReport, Problem, Severity};
141
pub use gc::GcReport;
142
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
143
pub use hooks::{json_array, json_str, HookOutcome};
144
pub use hosted::FileEdit;
145
pub use identity::{Rotation, SignatureStatus};
146
pub use inspect::{BisectStep, BlameLine, Description};
147
pub use ops::{RestoreReport, RevertReport, ViewChange};
148
pub use policy::PolicyUpdate;
149
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
150
pub use receipts::ReceiptInfo;
151
pub use revset::{Revset, REVSET_BUDGET};
152
pub use snapshot::{
153
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
154
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
155
    Selection, SnapshotResult,
156
};
157
pub use subrepos::{SubrepoInfo, SubrepoSync};
158
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated};
159
pub use tags::TagInfo;
160
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
161
162
/// The file name under which per-bookmark or per-tag data is kept: `/`
163
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
164
/// than a directory that would clash with it.
165
pub(crate) fn name_file(name: &str) -> String {
166
    name.replace('%', "%25").replace('/', "%2F")
167
}
168
169
/// The name a [`name_file`] file name stands for.
170
pub(crate) fn file_name_to_name(file: &str) -> String {
171
    file.replace("%2F", "/").replace("%25", "%")
172
}
173
174
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
175
    Ok(crate::durable::write_atomic(path, data)?)
176
}
177
178
/// Replace a cache file: whole or not at all, but without waiting for the
179
/// disk. A cache checks its own bytes when read, so one a crash leaves
180
/// short or stale is rebuilt rather than trusted.
181
/// How many changes a state index may fall behind its working copy before
182
/// it is written again; until then each load replays them.
183
const INDEX_REPLAY_LIMIT: usize = 16;
184
/// The changes whose encodings are kept for building graphs: a batch of
185
/// files often takes inline text from a few changes in turn.
186
const CHANGE_CACHE_COUNT: usize = 4;
187
const CHANGE_CACHE_BYTES: usize = 512 << 20;
188
/// How many state indexes a workspace keeps.
189
const STATE_INDEXES_KEPT: usize = 2;
190
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
191
192
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
193
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
194
    fs::write(&tmp, data)?;
195
    fs::rename(&tmp, path)?;
196
    Ok(())
197
}
198
199
pub struct LogEntry {
200
    pub hash: ChangeHash,
201
    /// Metadata from the state; the full change may be absent in a shallow repository.
202
    pub change: crate::state::ChangeMeta,
203
    pub is_working_copy: bool,
204
    pub is_head: bool,
205
}
206
207
/// A text file's base graph key, by path, as a walk asks for it.
208
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
209
210
/// A file as found on disk or in an imported tree.
211
#[derive(Clone)]
212
pub(crate) struct FsEntry {
213
    pub kind: NodeKind,
214
    pub exec: bool,
215
    /// File content, or a symlink's target. Empty when `blob` is set.
216
    /// Shared, so a new file's insert holds it without a copy.
217
    pub content: std::sync::Arc<Vec<u8>>,
218
    /// The stored blob of an opaque file whose size and mtime are unchanged
219
    /// since the last manifest (spec §12.3 stat cache); the content was not
220
    /// read.
221
    pub blob: Option<ObjectRef>,
222
    /// BLAKE3 of the content, carried over from the manifest when the stat
223
    /// is unchanged, so the manifest can be rewritten without rehashing.
224
    pub content_hash: Option<[u8; 32]>,
225
    /// A text file known equal to the base's rendering without reading it:
226
    /// its stat matches the manifest and the manifest recorded it equal to
227
    /// a base file graph with the same key (spec §12.3). `content` is empty.
228
    pub unchanged: bool,
229
    /// The base graph key this file equals, for the next manifest.
230
    pub graph_key: Option<[u8; 32]>,
231
    /// Size and mtime already known to be current (a checkout leaving the
232
    /// file as it was), so the manifest need not stat it again.
233
    pub stat: Option<(u64, u128)>,
234
}
235
236
impl FsEntry {
237
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
238
        FsEntry {
239
            kind,
240
            exec,
241
            content: std::sync::Arc::new(content),
242
            blob: None,
243
            content_hash: None,
244
            unchanged: false,
245
            graph_key: None,
246
            stat: None,
247
        }
248
    }
249
}
250
251
pub struct Repo {
252
    /// The key a host accepts certified updates with (spec §14.7): when
253
    /// set, accepting a reference update signed by a short-lived key also
254
    /// records the host's acceptance and its time.
255
    pub(crate) acceptor: Option<std::sync::Arc<(Identity, crate::identity::SecretKey)>>,
256
    /// Oxygen-pinned subrepos skipped by the running Git export.
257
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
258
    /// The manifest as last read, with the file identity it was read from,
259
    /// so one command parses it once (see `read_manifest`).
260
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
261
    /// A listing of the working copy left by a failed clean check, for the
262
    /// snapshot that follows it to reuse; taken by the next walk and
263
    /// dropped whenever the manifest is written.
264
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
265
    /// The nested repositories the last walk left out, being neither
266
    /// registered nor tracked subrepos (oxygen#43).
267
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
268
    root: PathBuf,
269
    oxy: PathBuf,
270
    store: Store,
271
    workspace: WorkspaceId,
272
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
273
    bare: bool,
274
    keys_dir: PathBuf,
275
    user_config: PathBuf,
276
    pub config: Config,
277
    /// What the working copy's file system can represent (spec §7.7).
278
    platform: crate::portable::Platform,
279
    /// The encodings of the changes last read for their inline inserts,
280
    /// oldest first.
281
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
282
    /// `--at-op`: read the repository as it was after this operation;
283
    /// recording an operation is refused.
284
    at_op: Option<ObjectRef>,
285
    /// The directories (with their times) and nested repositories of the
286
    /// last walk, for the manifest written from it.
287
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
288
    /// The directories a manifest check listed, for its restamp only.
289
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
290
}
291
292
/// A walk's directories with their times, and its nested repositories.
293
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
294
295
/// Marker file of a bare repository, inside `.oxy/`.
296
const BARE_MARKER: &str = "bare";
297
/// Marker of a hosted repository that has no id yet: the first push binds
298
/// it to the pusher's id (spec §16.1).
299
const UNBOUND_MARKER: &str = "unbound";
300
301
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
302
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
303
pub fn default_home() -> PathBuf {
304
    if let Ok(h) = std::env::var("OXY_HOME") {
305
        return PathBuf::from(h);
306
    }
307
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
308
        return PathBuf::from(x).join("oxy");
309
    }
310
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
311
    PathBuf::from(home).join(".config").join("oxy")
312
}
313
314
pub fn default_keys_dir() -> PathBuf {
315
    default_home().join("keys")
316
}
317
318
pub fn default_user_config() -> PathBuf {
319
    default_home().join("config.toml")
320
}
321
322
/// Where `create_identity` records the author.
323
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
324
pub enum IdentityScope {
325
    /// The user file: every repository of this user signs with it.
326
    User,
327
    /// This repository only.
328
    Repo,
329
}
330
331
impl Repo {
332
    // ------------------------------------------------------------ lifecycle
333
334
    pub fn init(root: &Path) -> Result<Repo> {
335
        let mut id = [0u8; 16];
336
        rand::rngs::OsRng.fill_bytes(&mut id);
337
        Self::init_with_id(root, id)
338
    }
339
340
    /// Initialize a repository with a given repository ID (clones share the
341
    /// ID of their origin, spec §14.4).
342
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
343
        Self::init_on(root, id, None)
344
    }
345
346
    /// A new repository with a fresh id, bare or not, on `storage` or in
347
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
348
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
349
        let mut id = [0u8; 16];
350
        rand::rngs::OsRng.fill_bytes(&mut id);
351
        if bare {
352
            Self::init_bare_on(root, id, storage)
353
        } else {
354
            Self::init_on(root, id, storage)
355
        }
356
    }
357
358
    /// Initialize a repository whose objects and operation head are kept
359
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
360
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
361
        fs::create_dir_all(root)?;
362
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
363
        let oxy = root.join(OXY_DIR);
364
        if oxy.exists() {
365
            return fail(format!("{} is already an oxy repository", root.display()));
366
        }
367
        fs::create_dir_all(oxy.join("ops"))?;
368
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
369
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
370
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
371
        if let Some(url) = storage {
372
            config.set("storage.url", url)?;
373
        }
374
        config.save(&oxy.join("config"))?;
375
        let workspace = WorkspaceId::random();
376
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
377
        let store = open_objects(&oxy, &config)?;
378
        let repo = Repo {
379
            acceptor: None,
380
            last_change: Default::default(),
381
            at_op: None,
382
            walked_dirs: Default::default(),
383
            listed_dirs: Default::default(),
384
            git_export_skipped: Default::default(),
385
            manifest_cache: Default::default(),
386
            listing_cache: Default::default(),
387
            untracked_nested: Default::default(),
388
            root,
389
            oxy,
390
            store,
391
            workspace,
392
            bare: false,
393
            keys_dir: default_keys_dir(),
394
            platform: crate::portable::Platform::current(),
395
            user_config: default_user_config(),
396
            config,
397
        };
398
        repo.register_workspace(&workspace, &repo.root)?;
399
400
        let wc = repo.new_working_copy(vec![], "");
401
        let wc_hash = repo.store.put_change(&wc)?;
402
        let mut view = View::default();
403
        view.bookmarks.insert(
404
            repo.config.bookmark.clone(),
405
            repo.store.put_state(&StateObject::new(vec![]))?,
406
        );
407
        view.workspaces.insert(workspace, wc_hash);
408
        repo.record_op(&[], "oxy init", view)?;
409
        Ok(repo)
410
    }
411
412
    /// Create a bare repository: an object store, operation log and
413
    /// references with no workspace and no working copy, for hosting
414
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
415
    pub fn init_bare(root: &Path) -> Result<Repo> {
416
        let mut id = [0u8; 16];
417
        rand::rngs::OsRng.fill_bytes(&mut id);
418
        Self::init_bare_with_id(root, id)
419
    }
420
421
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
422
        Self::init_bare_on(root, id, None)
423
    }
424
425
    /// [`Repo::init_on`] for a bare repository.
426
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
427
        fs::create_dir_all(root)?;
428
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
429
        let oxy = root.join(OXY_DIR);
430
        if oxy.exists() {
431
            return fail(format!("{} is already an oxy repository", root.display()));
432
        }
433
        fs::create_dir_all(oxy.join("ops"))?;
434
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
435
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
436
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
437
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
438
        if let Some(url) = storage {
439
            config.set("storage.url", url)?;
440
        }
441
        config.save(&oxy.join("config"))?;
442
        let store = open_objects(&oxy, &config)?;
443
        let repo = Repo {
444
            acceptor: None,
445
            last_change: Default::default(),
446
            at_op: None,
447
            walked_dirs: Default::default(),
448
            listed_dirs: Default::default(),
449
            git_export_skipped: Default::default(),
450
            manifest_cache: Default::default(),
451
            listing_cache: Default::default(),
452
            untracked_nested: Default::default(),
453
            root,
454
            oxy,
455
            store,
456
            workspace: WorkspaceId::ZERO,
457
            bare: true,
458
            keys_dir: default_keys_dir(),
459
            platform: crate::portable::Platform::current(),
460
            user_config: default_user_config(),
461
            config,
462
        };
463
        let mut view = View::default();
464
        view.bookmarks.insert(
465
            repo.config.bookmark.clone(),
466
            repo.store.put_state(&StateObject::new(vec![]))?,
467
        );
468
        repo.record_op(&[], "oxy init --bare", view)?;
469
        Ok(repo)
470
    }
471
472
    /// A bare repository with no id yet. Its `id()` is all zero until the
473
    /// first push binds it (`bind_id`), so an existing repository can be
474
    /// pushed to a freshly created hosted one and keep its identity.
475
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
476
        let repo = Self::init_bare_with_id(root, [0; 16])?;
477
        fs::remove_file(repo.oxy.join("id"))?;
478
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
479
        Ok(repo)
480
    }
481
482
    pub fn is_unbound(&self) -> bool {
483
        self.oxy.join(UNBOUND_MARKER).is_file()
484
    }
485
486
    /// Give an unbound repository its id.
487
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
488
        if !self.is_unbound() {
489
            return fail("this repository already has an id");
490
        }
491
        if id == [0; 16] {
492
            return fail("a repository id cannot be all zero");
493
        }
494
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
495
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
496
        Ok(())
497
    }
498
499
    /// Whether this repository has no working copy (`init_bare`).
500
    pub fn is_bare(&self) -> bool {
501
        self.bare
502
    }
503
504
    /// Open the repository containing `start` (searching upwards).
505
    pub fn open(start: &Path) -> Result<Repo> {
506
        let start = start.canonicalize()?;
507
        let mut dir: Option<&Path> = Some(&start);
508
        while let Some(d) = dir {
509
            let oxy = d.join(OXY_DIR);
510
            if oxy.is_file() {
511
                // A secondary workspace (spec §12.2): the file points at the repository.
512
                let text = fs::read_to_string(&oxy)?;
513
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
514
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
515
                };
516
                let format = fs::read_to_string(shared.join("format"))?;
517
                if format != FORMAT_LINE {
518
                    return fail(format!("unsupported repository format: {}", format.trim()));
519
                }
520
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
521
                let store = open_objects(&shared, &config)?;
522
                let mut repo = Repo {
523
                    acceptor: None,
524
                    last_change: Default::default(),
525
                    at_op: None,
526
                    walked_dirs: Default::default(),
527
                    listed_dirs: Default::default(),
528
                    git_export_skipped: Default::default(),
529
                    manifest_cache: Default::default(),
530
                    listing_cache: Default::default(),
531
                    untracked_nested: Default::default(),
532
                    root: d.to_path_buf(),
533
                    oxy: shared,
534
                    store,
535
                    workspace,
536
                    bare: false,
537
                    keys_dir: default_keys_dir(),
538
                    platform: crate::portable::Platform::current(),
539
                    user_config: default_user_config(),
540
                    config,
541
                };
542
                repo.apply_workspace_bookmark();
543
                return Ok(repo);
544
            }
545
            if oxy.is_dir() {
546
                let format = fs::read_to_string(oxy.join("format"))?;
547
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
548
                let bare = oxy.join(BARE_MARKER).is_file();
549
                let workspace = if bare {
550
                    WorkspaceId::ZERO
551
                } else {
552
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
553
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
554
                };
555
                let store = open_objects(&oxy, &config)?;
556
                let mut repo = Repo {
557
                    acceptor: None,
558
                    last_change: Default::default(),
559
                    at_op: None,
560
                    walked_dirs: Default::default(),
561
                    listed_dirs: Default::default(),
562
                    git_export_skipped: Default::default(),
563
                    manifest_cache: Default::default(),
564
                    listing_cache: Default::default(),
565
                    untracked_nested: Default::default(),
566
                    root: d.to_path_buf(),
567
                    oxy,
568
                    store,
569
                    workspace,
570
                    bare,
571
                    keys_dir: default_keys_dir(),
572
                    platform: crate::portable::Platform::current(),
573
                    user_config: default_user_config(),
574
                    config,
575
                };
576
                if !bare {
577
                    repo.apply_workspace_bookmark();
578
                }
579
                if format == FORMAT1_LINE {
580
                    repo.migrate_format1()?;
581
                } else if format != FORMAT_LINE {
582
                    return fail(format!("unsupported repository format: {}", format.trim()));
583
                }
584
                return Ok(repo);
585
            }
586
            dir = d.parent();
587
        }
588
        fail(format!(
589
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
590
            start.display()
591
        ))
592
    }
593
594
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
595
    /// into format 2, where each bookmark names a `state` object.
596
    fn migrate_format1(&self) -> Result<()> {
597
        let (head, version) = self.read_head()?;
598
        // Collect the chain root-first.
599
        let mut chain: Vec<Format1Op> = Vec::new();
600
        let mut cur = Some(head);
601
        while let Some(r) = cur {
602
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
603
            cur = op.parents.first().copied();
604
            chain.push(op);
605
        }
606
        chain.reverse();
607
        let mut new_parent: Option<ObjectRef> = None;
608
        for old in chain {
609
            let mut view = View::default();
610
            for (name, heads) in &old.view.bookmarks {
611
                view.bookmarks.insert(
612
                    name.clone(),
613
                    self.store.put_state(&StateObject::new(heads.clone()))?,
614
                );
615
            }
616
            view.workspaces = old.view.workspaces.clone();
617
            let op = Op {
618
                parents: new_parent.into_iter().collect(),
619
                hlc: old.hlc,
620
                command: old.command,
621
                view,
622
            };
623
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
624
        }
625
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
626
            return fail("the operation log changed while it was rewritten; run the command again");
627
        }
628
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
629
        Ok(())
630
    }
631
632
    /// Pack automatically once many loose objects have accumulated.
633
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
634
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
635
            self.store.pack_loose()?;
636
            self.store.merge_packs()?;
637
        }
638
        Ok(())
639
    }
640
641
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
642
    pub fn id(&self) -> Result<[u8; 16]> {
643
        if self.is_unbound() {
644
            return Ok([0; 16]);
645
        }
646
        let path = self.oxy.join("id");
647
        match fs::read_to_string(&path) {
648
            Ok(h) => hex::decode(h.trim())
649
                .ok()
650
                .and_then(|v| v.try_into().ok())
651
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
652
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
653
                let mut id = [0u8; 16];
654
                rand::rngs::OsRng.fill_bytes(&mut id);
655
                write_atomic(&path, hex::encode(id).as_bytes())?;
656
                Ok(id)
657
            }
658
            Err(e) => Err(e.into()),
659
        }
660
    }
661
662
    pub fn root(&self) -> &Path {
663
        &self.root
664
    }
665
    pub fn store(&self) -> &Store {
666
        &self.store
667
    }
668
    pub fn workspace(&self) -> WorkspaceId {
669
        self.workspace
670
    }
671
672
    /// Use a different user directory for keys and the user config file
673
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
674
    /// Act as if the working copy were on another platform's file system
675
    /// (tests of Windows and macOS behaviour on any host).
676
    /// Accept certified updates as `identity` (a host's key), recording when
677
    /// (spec §14.7).
678
    pub fn with_acceptor(mut self, identity: Identity, sk: crate::identity::SecretKey) -> Repo {
679
        self.acceptor = Some(std::sync::Arc::new((identity, sk)));
680
        self
681
    }
682
683
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
684
        self.platform = platform;
685
        self
686
    }
687
688
    pub fn platform(&self) -> crate::portable::Platform {
689
        self.platform
690
    }
691
692
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
693
        let dir = dir.into();
694
        self.keys_dir = dir.join("keys");
695
        self.user_config = dir.join("config.toml");
696
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
697
            self.config = c;
698
        }
699
        self.apply_workspace_bookmark();
700
        self
701
    }
702
703
    /// The workspace's current bookmark (spec §10.1) overrides the
704
    /// configured default when `oxy bookmark switch` has recorded one.
705
    fn apply_workspace_bookmark(&mut self) {
706
        if let Ok(b) = fs::read_to_string(
707
            self.oxy
708
                .join("workspaces")
709
                .join(self.workspace.to_hex())
710
                .join("bookmark"),
711
        ) {
712
            let b = b.trim();
713
            if !b.is_empty() {
714
                self.config.bookmark = b.to_string();
715
            }
716
        }
717
    }
718
719
    pub fn user_config_path(&self) -> &Path {
720
        &self.user_config
721
    }
722
723
    /// Set a key in the user file and refresh the effective configuration.
724
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
725
        Config::set_user(&self.user_config, key, value)?;
726
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
727
        Ok(())
728
    }
729
730
    pub fn save_config(&self) -> Result<()> {
731
        self.config.save(&self.oxy.join("config"))
732
    }
733
734
    fn author(&self) -> KeyId {
735
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
736
    }
737
}
738
739
impl Repo {
740
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
741
        let mut c = Change {
742
            version: crate::objects::CHANGE_VERSION,
743
            change_id: ChangeId::random(),
744
            deps,
745
            author: self.author(),
746
            hlc: Hlc::now(),
747
            message: message.into(),
748
            tree_ops: vec![],
749
            edits: vec![],
750
            kind: ChangeKind::WorkingCopy,
751
        };
752
        c.normalize();
753
        c
754
    }
755
756
    // ------------------------------------------------------------ operation log
757
758
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
759
        if let Some(r) = self.at_op {
760
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
761
        }
762
        let r = self.head_ref()?;
763
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
764
        Ok((r, op))
765
    }
766
767
    pub fn view(&self) -> Result<View> {
768
        Ok(self.head_op()?.1.view)
769
    }
770
771
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
772
        if self.at_op.is_some() {
773
            return fail(
774
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
775
            );
776
        }
777
        let op = Op {
778
            parents: parents.to_vec(),
779
            hlc: Hlc::now(),
780
            command: command.into(),
781
            view,
782
        };
783
        let r = self.store.put(ObjectType::Op, &op.encode())?;
784
        // The head is the commit point: everything it names must be on disk first.
785
        let flushing = crate::timing::phase("op: flush the store");
786
        self.store.flush()?;
787
        drop(flushing);
788
        // Compare and swap (spec §12.1): when another process recorded an
789
        // operation since this one read the head, the two are merged
790
        // instead of one overwriting the other. On this disk the head moves
791
        // under a short lock; on any other store by its record's version,
792
        // and a record that moved meanwhile is read again and merged again.
793
        let _lock = if self.store.is_local() {
794
            Some(self.lock_ops()?)
795
        } else {
796
            None
797
        };
798
        let Some(parent) = parents.first() else {
799
            // The first operation (init): there is no head yet.
800
            if !self.swap_head(&r, None)? {
801
                return fail(format!(
802
                    "{} already holds a repository's operation log",
803
                    self.store.backend().describe()
804
                ));
805
            }
806
            return Ok(r);
807
        };
808
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
809
        for _ in 0..HEAD_TRIES {
810
            let (current, version) = self.read_head()?;
811
            let to = if current == *parent {
812
                r
813
            } else {
814
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
815
                let merged = Op {
816
                    parents: vec![current, r],
817
                    hlc: Hlc::now(),
818
                    command: format!("{command} (merged with a concurrent operation)"),
819
                    view: self.merge_views(&base, &op.view, &theirs)?,
820
                };
821
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
822
                self.store.flush()?;
823
                m
824
            };
825
            if self.swap_head(&to, version.as_ref())? {
826
                return Ok(to);
827
            }
828
        }
829
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
830
    }
831
832
    /// The operation head's lock, held only while the head pointer moves.
833
    fn lock_ops(&self) -> Result<FileLock> {
834
        fs::create_dir_all(self.oxy.join("ops"))?;
835
        FileLock::acquire(
836
            self.oxy.join("ops").join("lock"),
837
            "another oxy process holds the operation log",
838
        )
839
    }
840
841
    fn head_ref(&self) -> Result<ObjectRef> {
842
        Ok(self.read_head()?.0)
843
    }
844
845
    /// The operation head, and on a store its record's version for
846
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
847
    /// any other store (a bucket, or memory in tests) it is the store's
848
    /// [`HEAD_RECORD`] reference record (oxygen#68).
849
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
850
        if self.store.is_local() {
851
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
852
            let r = ObjectRef::from_hex(hex.trim())
853
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
854
            return Ok((r, None));
855
        }
856
        let backend = self.store.backend();
857
        match backend.read_ref(HEAD_RECORD) {
858
            Ok(Some((bytes, version))) => {
859
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
860
                    || {
861
                        RepoError::Msg(format!(
862
                            "the operation head in {} is corrupt",
863
                            backend.describe()
864
                        ))
865
                    },
866
                )?;
867
                Ok((r, Some(version)))
868
            }
869
            Ok(None) => fail(format!(
870
                "{} holds no operation log (no {HEAD_RECORD} record)",
871
                backend.describe()
872
            )),
873
            Err(e) => fail(format!("read the operation head: {e}")),
874
        }
875
    }
876
877
    /// Move the operation head to `to` from the `expected` version
878
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
879
    /// disk the caller holds the operations lock and the head always
880
    /// moves; on a store it moves only if the record is unchanged, and
881
    /// `false` says another process moved it first.
882
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
883
        if self.store.is_local() {
884
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
885
            return Ok(true);
886
        }
887
        match self
888
            .store
889
            .backend()
890
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
891
        {
892
            Ok(_) => Ok(true),
893
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
894
            Err(e) => fail(format!("move the operation head: {e}")),
895
        }
896
    }
897
898
    /// Three-way merge of two views that both started from `base` (spec
899
    /// §12.1). A reference only one side changed takes that side's value.
900
    /// When both changed it differently: a bookmark keeps both sides'
901
    /// heads (it may then have several), a change beats a deletion, a
902
    /// workspace changed by both is an error (only one of them matches the
903
    /// files on disk), and otherwise this process's value wins for remote
904
    /// references and the policy, the first value for a tag (tags never
905
    /// move).
906
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
907
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
908
            b: &BTreeMap<K, V>,
909
            o: &BTreeMap<K, V>,
910
            t: &BTreeMap<K, V>,
911
            mut both: impl FnMut(&V, &V) -> Result<V>,
912
        ) -> Result<BTreeMap<K, V>> {
913
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
914
            let mut out = BTreeMap::new();
915
            for k in keys {
916
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
917
                let v = if ov == tv || tv == bv {
918
                    ov.cloned()
919
                } else if ov == bv {
920
                    tv.cloned()
921
                } else {
922
                    match (ov, tv) {
923
                        (Some(x), Some(y)) => Some(both(x, y)?),
924
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
925
                        (None, None) => None,
926
                    }
927
                };
928
                if let Some(v) = v {
929
                    out.insert(k.clone(), v);
930
                }
931
            }
932
            Ok(out)
933
        }
934
        let bookmarks = pick(
935
            &base.bookmarks,
936
            &ours.bookmarks,
937
            &theirs.bookmarks,
938
            |x, y| {
939
                let mut heads = self.store.get_state(x)?.heads;
940
                heads.extend(self.store.get_state(y)?.heads);
941
                let heads = self.load_state(&heads)?.maximal(&heads);
942
                Ok(self.store.put_state(&StateObject::new(heads))?)
943
            },
944
        )?;
945
        // Two operations that both replaced one workspace's working copy
946
        // cannot both be right: the files on disk match only one of them.
947
        // The working-copy lock keeps this from happening; should it happen
948
        // anyway, this operation is not recorded.
949
        let workspaces = pick(
950
            &base.workspaces,
951
            &ours.workspaces,
952
            &theirs.workspaces,
953
            |_, _| {
954
                fail(
955
                    "another oxy process changed this working copy at the same time; \
956
                     this command was not recorded: check `oxy status` and run it again",
957
                )
958
            },
959
        )?;
960
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
961
        let empty = BTreeMap::new();
962
        let names: BTreeSet<&String> = base
963
            .remotes
964
            .keys()
965
            .chain(ours.remotes.keys())
966
            .chain(theirs.remotes.keys())
967
            .collect();
968
        let mut remotes = BTreeMap::new();
969
        for n in names {
970
            let m = pick(
971
                base.remotes.get(n).unwrap_or(&empty),
972
                ours.remotes.get(n).unwrap_or(&empty),
973
                theirs.remotes.get(n).unwrap_or(&empty),
974
                |x, _| Ok(*x),
975
            )?;
976
            if !m.is_empty() {
977
                remotes.insert(n.clone(), m);
978
            }
979
        }
980
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
981
            ours.policy
982
        } else if ours.policy == base.policy {
983
            theirs.policy
984
        } else {
985
            ours.policy.or(theirs.policy)
986
        };
987
        self.store.flush()?;
988
        Ok(View {
989
            bookmarks,
990
            workspaces,
991
            remotes,
992
            policy,
993
            tags,
994
        })
995
    }
996
997
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
998
        let mut out = Vec::new();
999
        let (mut r, mut op) = self.head_op()?;
1000
        loop {
1001
            let next = op.parents.first().copied();
1002
            out.push((r, op));
1003
            match next {
1004
                Some(p) => {
1005
                    r = p;
1006
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1007
                }
1008
                None => break,
1009
            }
1010
        }
1011
        Ok(out)
1012
    }
1013
1014
    /// Undo the last user command (spec §12.1). Operations that only recorded
1015
    /// a working-copy snapshot are skipped, since the files are still on disk
1016
    /// and the next snapshot recreates them, and a command's own checkout
1017
    /// (`… (checkout)`) goes with the command. When the working copy is
1018
    /// clean and was clean after the operation undone to, its files follow
1019
    /// too, since nothing on disk can be lost; otherwise they stay as they
1020
    /// are (an undone commit's edits come back as uncommitted work).
1021
    pub fn undo(&self) -> Result<Op> {
1022
        let _wc = self.lock_working_copy()?;
1023
        let clean_now =
1024
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
1025
        let (read_head, mut op) = self.head_op()?;
1026
        let wc_now = op.view.workspaces.get(&self.workspace).copied();
1027
        let up = |op: Op| -> Result<Option<Op>> {
1028
            match op.parents.first() {
1029
                Some(p) => Ok(Some(Op::decode(&self.store.get_typed(p, ObjectType::Op)?)?)),
1030
                None => Ok(None),
1031
            }
1032
        };
1033
        loop {
1034
            while op.is_snapshot() {
1035
                match up(op.clone())? {
1036
                    Some(p) => op = p,
1037
                    None => break,
1038
                }
1039
            }
1040
            if !op.command.ends_with(" (checkout)") {
1041
                break;
1042
            }
1043
            match up(op.clone())? {
1044
                Some(p) => op = p,
1045
                None => break,
1046
            }
1047
        }
1048
        let Some(parent) = op.parents.first() else {
1049
            return fail("nothing to undo");
1050
        };
1051
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1052
        {
1053
            let _lock = if self.store.is_local() {
1054
                Some(self.lock_ops()?)
1055
            } else {
1056
                None
1057
            };
1058
            let (now, version) = self.read_head()?;
1059
            if now != read_head || !self.swap_head(parent, version.as_ref())? {
1060
                return fail("another oxy command ran while undoing; run undo again");
1061
            }
1062
        }
1063
        self.drop_manifest();
1064
        if let Some(then) = parent_op.view.workspaces.get(&self.workspace) {
1065
            if clean_now && Some(*then) != wc_now {
1066
                let wc = self.store.get_change(then)?;
1067
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
1068
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1069
                    // The files differ from the restored working copy by
1070
                    // exactly what the undone command did: nothing else is
1071
                    // on disk, as the working copy was clean.
1072
                    self.checkout(&base, true, "oxy undo (checkout)")?;
1073
                }
1074
            }
1075
        }
1076
        Ok(parent_op)
1077
    }
1078
1079
    /// The last operation that was not a snapshot.
1080
    pub fn last_command(&self) -> Result<Op> {
1081
        let (_, mut op) = self.head_op()?;
1082
        while op.is_snapshot() {
1083
            let Some(parent) = op.parents.first() else {
1084
                break;
1085
            };
1086
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1087
        }
1088
        Ok(op)
1089
    }
1090
1091
    // ------------------------------------------------------------ states
1092
1093
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1094
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1095
        if let Some(st) = self.load_state_checkpointed(heads)? {
1096
            return Ok(st);
1097
        }
1098
        self.load_state_full(heads)
1099
    }
1100
1101
    /// The state of `heads` for its history (changes, tree, metadata) with
1102
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1103
    /// and friends. Build the graphs a command needs with
1104
    /// [`Repo::load_graphs_of`].
1105
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
1106
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
1107
            return Ok(st);
1108
        }
1109
        self.load_state_replayed(heads, State::new_history_only())
1110
    }
1111
1112
    /// Build these file graphs in a history-only state.
1113
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
1114
        Ok(state.load_graphs(
1115
            nodes,
1116
            |refs| {
1117
                self.read_blobs(refs).map_err(|e| {
1118
                    crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
1119
                })
1120
            },
1121
            |h| self.change_bytes(h),
1122
        )?)
1123
    }
1124
1125
    /// The graphs of `nodes` of a history-only state, built beside it (see
1126
    /// [`State::build_graphs_detached`]).
1127
    pub fn build_graphs_detached(
1128
        &self,
1129
        state: &State,
1130
        nodes: &[crate::ids::NodeId],
1131
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
1132
        Ok(state
1133
            .build_graphs_detached(
1134
                nodes,
1135
                |refs| {
1136
                    self.read_blobs(refs).map_err(|e| {
1137
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
1138
                    })
1139
                },
1140
                |h| self.change_bytes(h),
1141
            )?
1142
            .into_iter()
1143
            .collect())
1144
    }
1145
1146
    /// Build every graph a history-only state still lacks, making it full.
1147
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
1148
        Ok(state.load_all_graphs(
1149
            |refs| {
1150
                self.read_blobs(refs).map_err(|e| {
1151
                    crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
1152
                })
1153
            },
1154
            |h| self.change_bytes(h),
1155
        )?)
1156
    }
1157
1158
    /// A change's encoding, for building graphs of its inline inserts. The
1159
    /// last few read are kept: a checkout building graphs a batch at a
1160
    /// time reads the same large changes for every batch, often in turn.
1161
    fn change_bytes(
1162
        &self,
1163
        h: &ChangeHash,
1164
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
1165
        let mut cache = self.last_change.borrow_mut();
1166
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
1167
            let hit = cache.remove(i);
1168
            let b = hit.1.clone();
1169
            cache.push(hit);
1170
            return Ok(b);
1171
        }
1172
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
1173
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
1174
        })?);
1175
        cache.push((*h, b.clone()));
1176
        // The last few, within a memory budget; the newest always stays.
1177
        while cache.len() > CHANGE_CACHE_COUNT
1178
            || (cache.len() > 1
1179
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
1180
        {
1181
            cache.remove(0);
1182
        }
1183
        Ok(b)
1184
    }
1185
1186
    /// Load the dependency closure of `heads` change by change.
1187
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1188
        self.load_state_replayed(heads, State::new())
1189
    }
1190
1191
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
1192
        let history = state.is_history_only();
1193
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1194
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1195
        {
1196
            let _t = crate::timing::phase("load: read and add changes");
1197
            let (mut read, mut add, mut fetch) = (
1198
                std::time::Duration::ZERO,
1199
                std::time::Duration::ZERO,
1200
                std::time::Duration::ZERO,
1201
            );
1202
            while let Some(h) = stack.pop() {
1203
                // A change the state holds brings its history with it.
1204
                if !seen.insert(h) || state.contains(&h) {
1205
                    continue;
1206
                }
1207
                let t0 = std::time::Instant::now();
1208
                // A history-only state reads text only for the graphs it
1209
                // builds; either way the hash is the one asked for.
1210
                let (c, texts) = if history {
1211
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
1212
                    fetch += t0.elapsed();
1213
                    Change::decode_skeleton(&bytes, h)
1214
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1215
                } else {
1216
                    (self.store.get_change(&h)?, Vec::new())
1217
                };
1218
                read += t0.elapsed();
1219
                stack.extend(c.deps.iter().copied());
1220
                let t1 = std::time::Instant::now();
1221
                state.add_known(h, c, texts);
1222
                add += t1.elapsed();
1223
            }
1224
            crate::timing::record("load:   of which reading", read);
1225
            crate::timing::record("load:     of which fetching", fetch);
1226
            crate::timing::record("load:   of which applying", add);
1227
        }
1228
        let _t = crate::timing::phase("load: validate");
1229
        state.validate()?;
1230
        Ok(state)
1231
    }
1232
1233
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
1234
        if self.bare {
1235
            return fail("this is a bare repository: it has no working copy");
1236
        }
1237
        let view = self.view()?;
1238
        let h = *view
1239
            .workspaces
1240
            .get(&self.workspace)
1241
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
1242
        Ok((h, self.store.get_change(&h)?))
1243
    }
1244
1245
    /// Heads of a bookmark's state (spec §10.1).
1246
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
1247
        match view.bookmarks.get(bookmark) {
1248
            Some(st) => Ok(self.store.get_state(st)?.heads),
1249
            None => Ok(vec![]),
1250
        }
1251
    }
1252
1253
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1254
        self.heads_of(&self.view()?, &self.config.bookmark)
1255
    }
1256
1257
    // ------------------------------------------------------------ blobs
1258
1259
    fn blob_for(content: &[u8]) -> Blob {
1260
        Blob::of(content)
1261
    }
1262
1263
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1264
        Self::blob_for(content).hash()
1265
    }
1266
1267
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1268
        for c in crate::chunk::chunks(content) {
1269
            self.store.put_chunk(c)?;
1270
        }
1271
        Ok(self
1272
            .store
1273
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1274
    }
1275
1276
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1277
    /// all their chunks, are read in parallel; a blob the store lacks goes
1278
    /// through [`Repo::read_blob`], which may fetch it lazily.
1279
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1280
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1281
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
1282
            blobs.push(match got {
1283
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
1284
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
1285
                Err(crate::store::StoreError::NotFound(_)) => None,
1286
                Err(e) => return Err(e.into()),
1287
            });
1288
        }
1289
        let chunk_refs: Vec<ObjectRef> = blobs
1290
            .iter()
1291
            .flatten()
1292
            .flat_map(|b| b.chunks.iter().copied())
1293
            .collect();
1294
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1295
        let mut out = Vec::with_capacity(refs.len());
1296
        for (r, blob) in refs.iter().zip(blobs) {
1297
            match blob {
1298
                None => out.push(self.read_blob(r)?),
1299
                Some(b) => {
1300
                    let mut content = Vec::with_capacity(b.length as usize);
1301
                    for c in &b.chunks {
1302
                        match chunks.next() {
1303
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
1304
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
1305
                            Some(Err(e)) => return Err(e.into()),
1306
                            None => return fail("chunk list ended early"),
1307
                        }
1308
                    }
1309
                    out.push(content);
1310
                }
1311
            }
1312
        }
1313
        Ok(out)
1314
    }
1315
1316
    /// Read a blob's content, fetching it from the remote that withheld it
1317
    /// when it is lazily absent (spec §13.5).
1318
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1319
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
1320
            self.fetch_lazy_blob(r)?;
1321
        }
1322
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1323
        let mut out = Vec::with_capacity(blob.length as usize);
1324
        for c in &blob.chunks {
1325
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1326
        }
1327
        Ok(out)
1328
    }
1329
1330
    // ------------------------------------------------------------ working copy
1331
1332
    /// Attributes from the `.oxyattributes` files in the working directory.
1333
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1334
        // Nested repositories and ignored paths are left out, as in a walk.
1335
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
1336
        let files: Vec<(String, Vec<u8>)> = listing
1337
            .files
1338
            .into_iter()
1339
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
1340
            .collect();
1341
        crate::attributes::Attributes::from_files(
1342
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1343
        )
1344
    }
1345
1346
    /// Folders holding a repository of their own that the last look at the
1347
    /// working copy left out, not being subrepos (oxygen#43).
1348
    pub fn untracked_nested(&self) -> Vec<String> {
1349
        self.untracked_nested.borrow().clone()
1350
    }
1351
1352
    /// Attributes from a materialized state's `.oxyattributes` files.
1353
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
1354
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
1355
            match &f.content {
1356
                FileContent::Text { bytes, .. }
1357
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1358
                {
1359
                    Some((p.as_str(), bytes.as_slice()))
1360
                }
1361
                _ => None,
1362
            }
1363
        }))
1364
    }
1365
1366
    /// Store a blob, raw when the path is `nocompress`.
1367
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1368
        if !nocompress {
1369
            return self.store_blob(content);
1370
        }
1371
        for c in crate::chunk::chunks(content) {
1372
            self.store.put_chunk_nocompress(c)?;
1373
        }
1374
        Ok(self
1375
            .store
1376
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1377
    }
1378
1379
    /// This workspace's state index (oxygen#41): its working copy's base,
1380
    /// saved so a snapshot reads it rather than replaying history.
1381
    /// The state index of the state with these heads: this workspace keeps
1382
    /// the last few it used, named by their heads, so moving between two
1383
    /// states finds both.
1384
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
1385
        let mut heads = heads.to_vec();
1386
        heads.sort();
1387
        let mut h = blake3::Hasher::new();
1388
        for c in &heads {
1389
            h.update(&c.0);
1390
        }
1391
        self.oxy.join("index").join(format!(
1392
            "{}{}",
1393
            self.state_index_prefix(),
1394
            &h.finalize().to_hex()[..16]
1395
        ))
1396
    }
1397
1398
    fn state_index_prefix(&self) -> String {
1399
        format!("state-{}-", self.workspace.to_hex())
1400
    }
1401
1402
    /// This workspace's state indexes, newest first.
1403
    fn state_indexes(&self) -> Vec<PathBuf> {
1404
        let prefix = self.state_index_prefix();
1405
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
1406
            .into_iter()
1407
            .flatten()
1408
            .flatten()
1409
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
1410
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
1411
            .collect();
1412
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
1413
        found.into_iter().map(|(_, p)| p).collect()
1414
    }
1415
1416
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1417
    /// from this workspace's state index when it holds that history: every
1418
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1419
    /// is loaded from history and indexed for next time.
1420
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
1421
        if let Some((st, heads)) = self.read_state_index(deps) {
1422
            let mut have = st.maximal(deps);
1423
            have.sort();
1424
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1425
                #[cfg(test)]
1426
                assert_eq!(
1427
                    st.write_index(),
1428
                    self.load_state_history(deps)?.write_index(),
1429
                    "a state index holds the state history gives"
1430
                );
1431
                return Ok(st);
1432
            }
1433
            // An index a few changes behind (a commit, a pull since): add
1434
            // what it lacks, as long as all it holds is history of `deps`.
1435
            // Anything amiss (a change beyond a shallow boundary) takes the
1436
            // long way instead.
1437
            let (indexed, started) = (st.len(), std::time::Instant::now());
1438
            if let Ok(st) = self.load_state_replayed(deps, st) {
1439
                let mut all = deps.to_vec();
1440
                all.extend(heads.iter().copied());
1441
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
1442
                within.sort();
1443
                want.sort();
1444
                if within == want {
1445
                    #[cfg(test)]
1446
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1447
                    // Writing the index costs far more than replaying a
1448
                    // few small changes: it is rewritten once it falls
1449
                    // behind, or when replaying took long (large changes).
1450
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
1451
                        || started.elapsed() > INDEX_REPLAY_TIME
1452
                    {
1453
                        self.write_state_index(deps, &st);
1454
                    }
1455
                    return Ok(st);
1456
                }
1457
            }
1458
        }
1459
        let st = self.load_state_history(deps)?;
1460
        self.write_state_index(deps, &st);
1461
        Ok(st)
1462
    }
1463
1464
    /// Two history-only states hold the same changes and render the same
1465
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1466
    /// the checkpoint's graphs as the bases of its files' histories.
1467
    #[cfg(test)]
1468
    fn assert_same_state(&self, a: &State, b: &State) {
1469
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1470
        assert_eq!(ids(a), ids(b), "the same changes");
1471
        let files = |s: &State| {
1472
            let mut s = s.clone();
1473
            self.load_all_graphs(&mut s).unwrap();
1474
            s.materialize().files
1475
        };
1476
        assert_eq!(files(a), files(b), "the same files");
1477
    }
1478
1479
    /// The state index file: its heads, a hash of its changes block and one
1480
    /// of the rest, then the body [`State::write_index`] gives, whose first
1481
    /// block is the changes. Hashed in two parts so the log can read and
1482
    /// check the changes alone.
1483
    /// The index of `deps` if there is one, else the newest, which the
1484
    /// caller may bring up to date.
1485
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1486
        let _t = crate::timing::phase("load: state index");
1487
        let exact = self.state_index_path(deps);
1488
        let bytes = match fs::read(&exact) {
1489
            Ok(b) => {
1490
                // Used now: the newest, so the last to be dropped.
1491
                let _ = fs::File::options()
1492
                    .write(true)
1493
                    .open(&exact)
1494
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1495
                b
1496
            }
1497
            Err(_) => fs::read(self.state_indexes().first()?).ok()?,
1498
        };
1499
        let mut r = crate::flat::Reader::new(&bytes);
1500
        let mut heads = Vec::new();
1501
        for _ in 0..r.count().ok()? {
1502
            heads.push(r.object().ok()?);
1503
        }
1504
        let (changes_sum, rest_sum) = (r.object().ok()?, r.object().ok()?);
1505
        let body = &bytes[4 + 32 * heads.len() + 64..];
1506
        let split = 4 + r.count().ok()?;
1507
        // Checked whole, so a part decoded later (the tree's maps, a
1508
        // file's history) can trust its bytes.
1509
        let (changes, rest) = (body.get(..split)?, body.get(split..)?);
1510
        let mut h = blake3::Hasher::new();
1511
        h.update_rayon(rest);
1512
        if *blake3::hash(changes).as_bytes() != changes_sum.0
1513
            || *h.finalize().as_bytes() != rest_sum.0
1514
        {
1515
            return None;
1516
        }
1517
        Some((State::read_index(body).ok()?, heads))
1518
    }
1519
1520
    /// The changes of this workspace's state index (the closure of its
1521
    /// heads), read without the rest of the index.
1522
    pub(crate) fn read_state_index_changes(
1523
        &self,
1524
    ) -> Option<std::collections::HashMap<ChangeHash, std::sync::Arc<crate::state::ChangeMeta>>>
1525
    {
1526
        use std::io::Read;
1527
        let _t = crate::timing::phase("load: state index changes");
1528
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1529
        let mut word = [0u8; 4];
1530
        f.read_exact(&mut word).ok()?;
1531
        let n = u32::from_le_bytes(word) as usize;
1532
        let mut head = vec![0u8; 32 * n + 64 + 4];
1533
        f.read_exact(&mut head).ok()?;
1534
        let sum = &head[32 * n..32 * n + 32];
1535
        let len = u32::from_le_bytes(head[32 * n + 64..].try_into().unwrap()) as usize;
1536
        let mut changes = vec![0u8; 4 + len];
1537
        changes[..4].copy_from_slice(&head[32 * n + 64..]);
1538
        f.read_exact(&mut changes[4..]).ok()?;
1539
        if blake3::hash(&changes).as_bytes() != sum {
1540
            return None;
1541
        }
1542
        State::read_index_changes(&changes[4..]).ok()
1543
    }
1544
1545
    /// Save `st`, the history-only state of `deps`, as this workspace's
1546
    /// state index; quietly nothing when it cannot be (it is only a cache).
1547
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1548
        let _t = crate::timing::phase("write: state index");
1549
        let encoding = crate::timing::phase("write:   of which encoding");
1550
        let Some(body) = st.write_index() else {
1551
            return;
1552
        };
1553
        drop(encoding);
1554
        #[cfg(test)]
1555
        assert_eq!(
1556
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1557
            Some(body.clone()),
1558
            "a state index reads back as written"
1559
        );
1560
        let mut heads = st.maximal(deps);
1561
        heads.sort();
1562
        let mut w = crate::flat::Writer::default();
1563
        w.count(heads.len());
1564
        for h in &heads {
1565
            w.object(h);
1566
        }
1567
        let split = 4 + u32::from_le_bytes(body[..4].try_into().unwrap()) as usize;
1568
        w.fixed(blake3::hash(&body[..split]).as_bytes());
1569
        let mut sum = blake3::Hasher::new();
1570
        sum.update_rayon(&body[split..]);
1571
        w.fixed(sum.finalize().as_bytes());
1572
        w.fixed(&body);
1573
        let path = self.state_index_path(&heads);
1574
        let _ = fs::create_dir_all(self.oxy.join("index"));
1575
        let _ = write_cache(&path, &w.0);
1576
        // The last two used: the index of a state moved away from stays for
1577
        // a move back. Older ones (and the unnamed one of before) go.
1578
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
1579
            let _ = fs::remove_file(old);
1580
        }
1581
        let _ = fs::remove_file(
1582
            self.oxy
1583
                .join("index")
1584
                .join(format!("state-{}", self.workspace.to_hex())),
1585
        );
1586
    }
1587
1588
    fn locks_dir(&self) -> PathBuf {
1589
        self.oxy.join("locks")
1590
    }
1591
1592
    /// Whether `path` is locked locally for editing (spec §18, advisory).
1593
    pub fn is_locked(&self, path: &str) -> bool {
1594
        self.locks_dir().join(path.replace('/', "%2F")).exists()
1595
    }
1596
1597
    /// Take the advisory local lock on a `lockable` file and make it writable.
1598
    pub fn lock_path(&self, path: &str) -> Result<()> {
1599
        let attrs = self.disk_attributes();
1600
        if !attrs.lookup(path).lockable {
1601
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
1602
        }
1603
        fs::create_dir_all(self.locks_dir())?;
1604
        write_atomic(
1605
            &self.locks_dir().join(path.replace('/', "%2F")),
1606
            std::process::id().to_string().as_bytes(),
1607
        )?;
1608
        set_readonly(&self.root.join(path), false)?;
1609
        Ok(())
1610
    }
1611
1612
    /// Release the local lock and make the file read-only again.
1613
    pub fn unlock_path(&self, path: &str) -> Result<()> {
1614
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
1615
        if self.root.join(path).exists() {
1616
            set_readonly(&self.root.join(path), true)?;
1617
        }
1618
        Ok(())
1619
    }
1620
1621
    /// Whether a repository path is inside the sparse filter (spec §17).
1622
    pub fn in_scope(&self, path: &str) -> bool {
1623
        self.config.sparse_paths.is_empty()
1624
            || self
1625
                .config
1626
                .sparse_paths
1627
                .iter()
1628
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
1629
    }
1630
1631
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
1632
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
1633
    }
1634
1635
    /// Walk the working copy; with a manifest, a file whose size and mtime
1636
    /// match it is not read: an opaque file yields its known blob, and a
1637
    /// text file whose recorded graph key equals its base graph's key in
1638
    /// `keys` (path → key) is marked unchanged; other text files are read
1639
    /// but keep their known hash. Files modified within two seconds of the
1640
    /// manifest are never trusted (a racy stat).
1641
    ///
1642
    /// `.oxyattributes` files are always read, since their content is
1643
    /// needed; and when any of them is not known unchanged (added, removed,
1644
    /// edited, or changed in the base), no text file is taken as unchanged,
1645
    /// because attributes decide how a file compares with the base.
1646
    ///
1647
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
1648
    /// (the base state's files) that exists on disk is included even when
1649
    /// an ignore rule matches it, as in Git.
1650
    fn walk_working_copy_with(
1651
        &self,
1652
        cache: Option<&prompt::Manifest>,
1653
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
1654
        keys: Option<&KeyOf>,
1655
    ) -> Result<BTreeMap<String, FsEntry>> {
1656
        let mut out: BTreeMap<String, FsEntry>;
1657
        let sparse = &self.config.sparse_paths;
1658
        let in_scope = |p: &str| {
1659
            sparse.is_empty()
1660
                || sparse
1661
                    .iter()
1662
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
1663
        };
1664
        let walk_phase = crate::timing::phase("walk:   of which listing");
1665
        let walk::Listing {
1666
            files,
1667
            symlinks,
1668
            nested,
1669
            dirs,
1670
        } = match self.listing_cache.take() {
1671
            Some(l) => l,
1672
            // Ignore rules apply to untracked paths only, so the base's
1673
            // files are not matched against them (an added file is: a rule
1674
            // written after it was snapshotted leaves it out again).
1675
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
1676
        };
1677
        let keys = keys.filter(|k| {
1678
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
1679
            let attrs_unchanged =
1680
                files
1681
                    .iter()
1682
                    .filter(|(r, _, _)| is_attributes(r))
1683
                    .all(|(rel, _, meta)| {
1684
                        stat_cached(rel, meta, cache)
1685
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
1686
                    });
1687
            let none_removed = tracked
1688
                .keys()
1689
                .filter(|r| is_attributes(r))
1690
                .all(|r| on_disk.contains(r.as_str()));
1691
            attrs_unchanged && none_removed
1692
        });
1693
        *self.walked_dirs.borrow_mut() =
1694
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
1695
        drop(walk_phase);
1696
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
1697
        // Reading files is most of a walk's cost; do it in parallel.
1698
        {
1699
            use rayon::prelude::*;
1700
            let mut read: Vec<(String, FsEntry)> = files
1701
                .par_iter()
1702
                .map(|(rel, path, meta)| {
1703
                    // A key is worked out only for a file the manifest
1704
                    // knows with the same stat and a key of its own.
1705
                    let key = keys
1706
                        .filter(|_| !is_attributes(rel))
1707
                        .filter(|_| {
1708
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
1709
                        })
1710
                        .and_then(|k| k(rel));
1711
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
1712
                })
1713
                .collect::<Result<Vec<_>>>()?;
1714
            for (rel, e) in read.iter_mut() {
1715
                // A cached blob the store lost (gc, a partial clone): read the file after all.
1716
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
1717
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
1718
                    e.blob = None;
1719
                }
1720
            }
1721
            // The listing is in path order, so the map is built without
1722
            // searching.
1723
            out = read.into_iter().collect();
1724
            for (rel, target) in symlinks {
1725
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
1726
            }
1727
        }
1728
        drop(_read_phase);
1729
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
1730
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
1731
        // already tracked as subrepo nodes, they contribute their pin;
1732
        // unregistered ones are left alone.
1733
        let modules = self.modules_on_disk();
1734
        let removed = self.removed_subrepos();
1735
        for rel in &removed {
1736
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
1737
                self.clear_removed_subrepo(rel);
1738
            }
1739
        }
1740
        let mut untracked_nested = Vec::new();
1741
        for dir in nested {
1742
            let rel = self.rel_path(&dir);
1743
            if !self.in_scope(&rel) || removed.contains(&rel) {
1744
                continue;
1745
            }
1746
            let registered = modules.entries.get(&rel);
1747
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
1748
            {
1749
                untracked_nested.push(rel);
1750
                continue;
1751
            }
1752
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
1753
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
1754
        }
1755
        untracked_nested.sort();
1756
        *self.untracked_nested.borrow_mut() = untracked_nested;
1757
        // Tracked paths the ignore rules hid.
1758
        for (rel, (kind, blob)) in tracked {
1759
            if out.contains_key(rel) || !self.in_scope(rel) {
1760
                continue;
1761
            }
1762
            let path = self.root.join(rel);
1763
            if *kind == NodeKind::Subrepo {
1764
                if removed.contains(rel) {
1765
                    continue;
1766
                }
1767
                let present =
1768
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
1769
                if present {
1770
                    let pin = subrepos::read_pin(
1771
                        &path,
1772
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
1773
                    )?;
1774
                    out.insert(
1775
                        rel.clone(),
1776
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
1777
                    );
1778
                } else if let Some(b) = blob {
1779
                    // Not cloned (or emptied): the pin stays as recorded, as a
1780
                    // Git gitlink does when its directory is absent.
1781
                    out.insert(
1782
                        rel.clone(),
1783
                        FsEntry {
1784
                            blob: Some(*b),
1785
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
1786
                        },
1787
                    );
1788
                }
1789
                continue;
1790
            }
1791
            let Ok(meta) = fs::symlink_metadata(&path) else {
1792
                continue;
1793
            };
1794
            let ft = meta.file_type();
1795
            if ft.is_symlink() {
1796
                let target = fs::read_link(&path)?;
1797
                out.insert(
1798
                    rel.clone(),
1799
                    FsEntry::new(
1800
                        NodeKind::Symlink,
1801
                        false,
1802
                        target.to_string_lossy().as_bytes().to_vec(),
1803
                    ),
1804
                );
1805
            } else if ft.is_file() {
1806
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
1807
                out.insert(rel.clone(), e);
1808
            }
1809
        }
1810
        Ok(out)
1811
    }
1812
1813
    /// The entry for one regular file, read or served from the stat cache.
1814
    fn file_entry(
1815
        &self,
1816
        rel: &str,
1817
        path: &Path,
1818
        meta: &walk::Stat,
1819
        cache: Option<&prompt::Manifest>,
1820
    ) -> Result<FsEntry> {
1821
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
1822
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
1823
            e.content = std::sync::Arc::new(fs::read(path)?);
1824
            e.blob = None;
1825
        }
1826
        Ok(e)
1827
    }
1828
1829
    /// The non-directory paths of a snapshot with their kinds, for the
1830
    /// walker's `tracked` set.
1831
    pub(crate) fn tracked_kinds(
1832
        snapshot: &Snapshot,
1833
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
1834
        snapshot
1835
            .files
1836
            .iter()
1837
            .filter(|(_, f)| f.kind != NodeKind::Dir)
1838
            .map(|(p, f)| {
1839
                let blob = match &f.content {
1840
                    FileContent::Opaque { blobs } => blobs.first().copied(),
1841
                    _ => None,
1842
                };
1843
                (p.clone(), (f.kind, blob))
1844
            })
1845
            .collect()
1846
    }
1847
1848
    /// A path under the root as a `/`-separated relative string.
1849
    pub(crate) fn rel_path(&self, path: &Path) -> String {
1850
        path.strip_prefix(&self.root)
1851
            .unwrap_or(path)
1852
            .components()
1853
            .map(|c| c.as_os_str().to_string_lossy().to_string())
1854
            .collect::<Vec<_>>()
1855
            .join("/")
1856
    }
1857
}
1858
1859
impl Repo {
1860
    /// Changes reachable from the bookmark and the working copy, newest first.
1861
    pub fn log(&self) -> Result<Vec<LogEntry>> {
1862
        let heads = self.bookmark_heads()?;
1863
        if self.bare {
1864
            return self.log_state(&heads);
1865
        }
1866
        let (wc_hash, _) = self.working_copy()?;
1867
        let mut all = heads.clone();
1868
        all.push(wc_hash);
1869
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
1870
        let mut entries: Vec<LogEntry> = Vec::new();
1871
        // A shallow clone knows changes beyond its boundary from a
1872
        // checkpoint's metadata only: its log comes from the state.
1873
        let metas = if self.is_shallow() {
1874
            self.load_state_history(&all)?
1875
                .changes()
1876
                .map(|(h, m)| (*h, m.clone()))
1877
                .collect()
1878
        } else {
1879
            self.metas_of(&all)?
1880
        };
1881
        for (h, meta) in metas {
1882
            entries.push(LogEntry {
1883
                hash: h,
1884
                change: meta,
1885
                is_working_copy: h == wc_hash,
1886
                is_head: head_set.contains(&h),
1887
            });
1888
        }
1889
        entries.sort_by(|a, b| {
1890
            b.is_working_copy
1891
                .cmp(&a.is_working_copy)
1892
                .then(b.change.hlc.cmp(&a.change.hlc))
1893
                .then(b.hash.cmp(&a.hash))
1894
        });
1895
        Ok(entries)
1896
    }
1897
1898
    /// A window of `log_state`: entries `offset..offset+limit` and the total
1899
    /// count, for paginated views.
1900
    pub fn log_window(
1901
        &self,
1902
        heads: &[ChangeHash],
1903
        offset: usize,
1904
        limit: usize,
1905
    ) -> Result<(Vec<LogEntry>, usize)> {
1906
        let all = self.log_state(heads)?;
1907
        let total = all.len();
1908
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
1909
    }
1910
1911
    /// The log of the state with these heads, newest first, with no working
1912
    /// copy involved (for hosted repositories and any explicit state).
1913
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1914
        // The log needs change metadata only: neither graphs nor the tree.
1915
        if self.is_shallow() {
1916
            return Ok(self.log_of(&self.load_state_history(heads)?));
1917
        }
1918
        let metas = self.metas_of(heads)?;
1919
        let depended: BTreeSet<ChangeHash> = metas
1920
            .iter()
1921
            .flat_map(|(_, m)| m.deps.iter().copied())
1922
            .collect();
1923
        let mut entries: Vec<LogEntry> = metas
1924
            .into_iter()
1925
            .map(|(h, meta)| LogEntry {
1926
                hash: h,
1927
                is_head: !depended.contains(&h),
1928
                change: meta,
1929
                is_working_copy: false,
1930
            })
1931
            .collect();
1932
        entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
1933
        Ok(entries)
1934
    }
1935
1936
    /// Every change of the state with these heads and its metadata, read
1937
    /// without its operations ([`Store::get_change_meta`]). A change beyond
1938
    /// a shallow clone's boundary is left out.
1939
    pub fn metas_of(
1940
        &self,
1941
        heads: &[ChangeHash],
1942
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
1943
        let boundary = self.boundary();
1944
        // The state index holds the metadata of its heads' closure: a
1945
        // change found there is not read from the store (a change object
1946
        // can be as large as the tree it adds).
1947
        let indexed = self.read_state_index_changes();
1948
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
1949
        let mut seen: HashSet<ChangeHash> = HashSet::new();
1950
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1951
        let mut out = Vec::new();
1952
        while let Some(h) = stack.pop() {
1953
            if !seen.insert(h) {
1954
                continue;
1955
            }
1956
            if let Some(meta) = indexed.as_ref().and_then(|m| m.get(&h)) {
1957
                #[cfg(test)]
1958
                assert_eq!(
1959
                    **meta,
1960
                    self.store.get_change_meta(&h)?,
1961
                    "the state index holds a change's metadata"
1962
                );
1963
                stack.extend(meta.deps.iter().copied());
1964
                out.push((h, (**meta).clone()));
1965
                continue;
1966
            }
1967
            let started = std::time::Instant::now();
1968
            let meta = match self.store.get_change_meta(&h) {
1969
                Ok(m) => m,
1970
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
1971
                Err(e) => return Err(e.into()),
1972
            };
1973
            stored += 1;
1974
            from_store += started.elapsed();
1975
            stack.extend(meta.deps.iter().copied());
1976
            out.push((h, meta));
1977
        }
1978
        if stored > 0 && crate::timing::enabled() {
1979
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
1980
        }
1981
        Ok(out)
1982
    }
1983
1984
    /// The log of a state already loaded, newest first.
1985
    /// The history of lines `first..=last` (1-based) of `path` in the
1986
    /// state `heads` make (spec §27): every change that inserted or
1987
    /// deleted one of their atoms, or an atom deleted from between them,
1988
    /// newest first. Exact, as atoms keep their identity across edits.
1989
    pub fn line_history(
1990
        &self,
1991
        heads: &[ChangeHash],
1992
        path: &str,
1993
        first: usize,
1994
        last: usize,
1995
    ) -> Result<Vec<LogEntry>> {
1996
        if first == 0 || last < first {
1997
            return fail(format!(
1998
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
1999
            ));
2000
        }
2001
        let mut state = self.load_state_history(heads)?;
2002
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
2003
            return fail(format!("{path} is not in that state"));
2004
        };
2005
        self.load_graphs_of(&mut state, &[node])?;
2006
        let live = state.live_lines(&node);
2007
        if last > live.len() {
2008
            return fail(format!(
2009
                "{path} has {} lines; asked for {first},{last}",
2010
                live.len()
2011
            ));
2012
        }
2013
        let Some(g) = state.file(&node) else {
2014
            return fail(format!("{path} is not a text file"));
2015
        };
2016
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
2017
        let touched = g.touching(&atoms);
2018
        Ok(self
2019
            .log_of(&state)
2020
            .into_iter()
2021
            .filter(|e| touched.contains(&e.hash))
2022
            .collect())
2023
    }
2024
2025
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
2026
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
2027
        let mut entries: Vec<LogEntry> = state
2028
            .changes()
2029
            .map(|(h, meta)| LogEntry {
2030
                hash: *h,
2031
                change: meta.clone(),
2032
                is_working_copy: false,
2033
                is_head: head_set.contains(h),
2034
            })
2035
            .collect();
2036
        entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
2037
        entries
2038
    }
2039
2040
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2041
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2042
    /// (`resolve_change`).
2043
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
2044
        let view = self.view()?;
2045
        if let Some(st) = view.bookmarks.get(spec) {
2046
            return Ok(self.store.get_state(st)?.heads);
2047
        }
2048
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
2049
            return Ok(self.store.get_state(&st)?.heads);
2050
        }
2051
        if let Some(heads) = self.tag_heads(spec)? {
2052
            return Ok(heads);
2053
        }
2054
        Ok(vec![self.resolve_change(spec)?])
2055
    }
2056
2057
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2058
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
2059
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
2060
        if spec == "@" {
2061
            return Ok(self.working_copy()?.0);
2062
        }
2063
        let view = self.view()?;
2064
        let named = match view.bookmarks.get(spec) {
2065
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
2066
            None => match remote_bookmark(&view, spec) {
2067
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
2068
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2069
            },
2070
        };
2071
        if let Some((kind, heads)) = named {
2072
            return match heads.len() {
2073
                1 => Ok(heads[0]),
2074
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2075
            };
2076
        }
2077
        if spec.is_empty() || spec == "#" {
2078
            return fail("empty change specifier");
2079
        }
2080
        let entries = self.log()?;
2081
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
2082
            entries
2083
                .iter()
2084
                .filter(|e| e.hash.starts_with_hex(hp))
2085
                .collect()
2086
        } else {
2087
            entries
2088
                .iter()
2089
                .filter(|e| e.change.change_id.starts_with_hex(spec))
2090
                .collect()
2091
        };
2092
        match matches.len() {
2093
            1 => Ok(matches[0].hash),
2094
            0 => match self.resolve_in_remotes(spec)? {
2095
                Some(h) => Ok(h),
2096
                None => fail(format!("no change matches {spec:?}")),
2097
            },
2098
            _ => {
2099
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
2100
                if ids.len() == 1 {
2101
                    fail(format!(
2102
                        "change {spec} is divergent: {} variants",
2103
                        matches.len()
2104
                    ))
2105
                } else {
2106
                    fail(format!("{spec:?} is ambiguous"))
2107
                }
2108
            }
2109
        }
2110
    }
2111
2112
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2113
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2114
    /// `None` when none matches, or more than one.
2115
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
2116
        let view = self.view()?;
2117
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
2118
        for bookmarks in view.remotes.values() {
2119
            for st in bookmarks.values() {
2120
                let heads = self.store.get_state(st)?.heads;
2121
                for e in self.log_state(&heads)? {
2122
                    let hit = match spec.strip_prefix('#') {
2123
                        Some(hp) => e.hash.starts_with_hex(hp),
2124
                        None => e.change.change_id.starts_with_hex(spec),
2125
                    };
2126
                    if hit {
2127
                        found.insert(e.hash);
2128
                    }
2129
                }
2130
            }
2131
        }
2132
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
2133
    }
2134
2135
    /// Where a change is when no local bookmark or the working copy holds
2136
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2137
    /// it is held locally, or nowhere.
2138
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
2139
        if self.log()?.iter().any(|e| e.hash == *hash) {
2140
            return Ok(None);
2141
        }
2142
        let view = self.view()?;
2143
        for (remote, bookmarks) in &view.remotes {
2144
            for (name, st) in bookmarks {
2145
                let heads = self.store.get_state(st)?.heads;
2146
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
2147
                    return Ok(Some(format!("{remote}/{name}")));
2148
                }
2149
            }
2150
        }
2151
        Ok(None)
2152
    }
2153
2154
    /// Human-readable description of what a change does, with line content.
2155
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
2156
        let change = self.store.get_change(hash)?;
2157
        let (base, base_snapshot) = self.change_base(&change)?;
2158
        Ok(render_change(&change, &base, &base_snapshot))
2159
    }
2160
2161
    /// The base state of `change` (its dependencies) and its rendering, as
2162
    /// much as showing the change needs: the whole tree, and the graphs and
2163
    /// contents of the files the change edits. Other text files are left
2164
    /// unrendered ([`Snapshot::unrendered`]).
2165
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
2166
        let base = self.load_state_history(&change.deps)?;
2167
        self.render_base_for(change, base)
2168
    }
2169
2170
    /// [`Repo::change_base`] with the base already loaded (the working
2171
    /// copy's comes from the state index).
2172
    pub(crate) fn render_base_for(
2173
        &self,
2174
        change: &Change,
2175
        mut base: State,
2176
    ) -> Result<(State, Snapshot)> {
2177
        let _t = crate::timing::phase("diff: render the base");
2178
        let edited: std::collections::HashSet<NodeId> =
2179
            change.edits.iter().map(|e| e.node()).collect();
2180
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2181
        self.load_graphs_of(&mut base, &nodes)?;
2182
        let snapshot = {
2183
            let _t = crate::timing::phase("diff:   of which materialize");
2184
            base.materialize_nodes(&edited)
2185
        };
2186
        Ok((base, snapshot))
2187
    }
2188
}
2189
2190
fn remove_any(path: &Path) -> std::io::Result<()> {
2191
    let m = fs::symlink_metadata(path)?;
2192
    if m.is_dir() {
2193
        fs::remove_dir_all(path)
2194
    } else {
2195
        fs::remove_file(path)
2196
    }
2197
}
2198
2199
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
2200
    let mut perms = fs::metadata(path)?.permissions();
2201
    perms.set_readonly(readonly);
2202
    fs::set_permissions(path, perms)
2203
}
2204
2205
#[cfg(unix)]
2206
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2207
    use std::os::unix::fs::PermissionsExt;
2208
    let mut perms = fs::metadata(path)?.permissions();
2209
    let mode = perms.mode();
2210
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
2211
    if want != mode {
2212
        perms.set_mode(want);
2213
        fs::set_permissions(path, perms)?;
2214
    }
2215
    Ok(())
2216
}
2217
#[cfg(not(unix))]
2218
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2219
    Ok(())
2220
}
2221
2222
#[cfg(unix)]
2223
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2224
    use std::os::unix::fs::PermissionsExt;
2225
    m.permissions().mode() & 0o111 != 0
2226
}
2227
#[cfg(not(unix))]
2228
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2229
    false
2230
}
2231
2232
fn op_ref(k: OpKey) -> OpRef {
2233
    OpRef {
2234
        change: k.0,
2235
        index: k.1,
2236
    }
2237
}
2238
2239
fn split_path(path: &str) -> (&str, &str) {
2240
    match path.rfind('/') {
2241
        Some(i) => (&path[..i], &path[i + 1..]),
2242
        None => ("", path),
2243
    }
2244
}
2245
2246
/// Whether `rel` is an attributes file (spec §7.6).
2247
fn is_attributes(rel: &str) -> bool {
2248
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
2249
}
2250
2251
/// The manifest entry for `rel` when its size and mtime match it outside
2252
/// the racy window.
2253
fn stat_cached<'m>(
2254
    rel: &str,
2255
    meta: &walk::Stat,
2256
    cache: Option<&'m prompt::Manifest>,
2257
) -> Option<&'m prompt::ManifestEntry> {
2258
    let m = cache?;
2259
    let e = m.entries.get(rel)?;
2260
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
2261
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
2262
}
2263
2264
/// Read one working-copy file, or serve it from the stat cache (spec
2265
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2266
/// an opaque file is not read at all (its stored blob stands in), and a
2267
/// text file the manifest recorded equal to a base graph whose key is
2268
/// `key`, the key the base has now, is not read either: equal keys mean
2269
/// equal renderings, so it still equals the base. Touches no repository
2270
/// state, so the walk runs it in parallel; the caller checks that a cached
2271
/// blob is still in the store.
2272
fn read_file_entry(
2273
    rel: &str,
2274
    path: &Path,
2275
    meta: &walk::Stat,
2276
    cache: Option<&prompt::Manifest>,
2277
    key: Option<[u8; 32]>,
2278
) -> Result<FsEntry> {
2279
    let exec = meta.exec;
2280
    let stat = Some((meta.size, meta.mtime_ns));
2281
    let mut e = match stat_cached(rel, meta, cache) {
2282
        Some(e) if e.blob.is_some() => FsEntry {
2283
            blob: e.blob,
2284
            content_hash: Some(e.hash),
2285
            ..FsEntry::new(NodeKind::File, exec, vec![])
2286
        },
2287
        Some(e) if key.is_some() && e.graph == key => FsEntry {
2288
            content_hash: Some(e.hash),
2289
            unchanged: true,
2290
            graph_key: e.graph,
2291
            ..FsEntry::new(NodeKind::File, exec, vec![])
2292
        },
2293
        Some(e) => FsEntry {
2294
            content_hash: Some(e.hash),
2295
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2296
        },
2297
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2298
    };
2299
    // The stat the manifest records: taken before the read, so a file that
2300
    // changes meanwhile is read again next time.
2301
    e.stat = stat;
2302
    Ok(e)
2303
}