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