OXYGENHUB
# 6e6668830baf oxygen / crates / oxy-core / src / repo / mod.rs
44.3 KiB · Rust · last changed Snapshots use every core 1 month 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::{verify as verify_signature, Domain, Identity, SecretKey, Signature};
14
use crate::ids::{ChangeId, NodeId, WorkspaceId};
15
use crate::objects::{
16
    Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp,
17
};
18
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
19
use crate::protocol::{
20
    open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef,
21
    SignedAttest, SignedPolicy,
22
};
23
use crate::state::{FileContent, Snapshot, State};
24
use crate::store::{Store, StoreError};
25
#[allow(unused_imports)]
26
use crate::subrepo::Pin;
27
use crate::tree::OpKey;
28
use rand::RngCore;
29
use std::collections::{BTreeMap, BTreeSet, HashMap};
30
use std::fs;
31
use std::io::Write;
32
use std::path::{Path, PathBuf};
33
34
pub const OXY_DIR: &str = ".oxy";
35
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
36
const FORMAT1_LINE: &str = "oxy repository format 1\n";
37
const BINARY_SNIFF: usize = 8 * 1024;
38
/// Loose objects tolerated before a commit packs them (spec §13.4).
39
pub const AUTOPACK_THRESHOLD: usize = 4096;
40
41
#[derive(Debug, thiserror::Error)]
42
pub enum RepoError {
43
    #[error("io: {0}")]
44
    Io(#[from] std::io::Error),
45
    #[error(transparent)]
46
    Store(#[from] StoreError),
47
    #[error(transparent)]
48
    Object(#[from] crate::objects::ObjectError),
49
    #[error(transparent)]
50
    State(#[from] crate::state::StateError),
51
    #[error("{0}")]
52
    Msg(String),
53
}
54
55
pub type Result<T> = std::result::Result<T, RepoError>;
56
57
fn fail<T>(s: impl Into<String>) -> Result<T> {
58
    Err(RepoError::Msg(s.into()))
59
}
60
61
mod bookmarks;
62
mod checkout;
63
mod checkpoint;
64
mod config;
65
mod gc;
66
mod git;
67
mod history;
68
mod hooks;
69
mod identity;
70
mod inspect;
71
mod policy;
72
mod prompt;
73
mod snapshot;
74
mod subrepos;
75
mod sync;
76
mod tags;
77
#[cfg(test)]
78
mod tests;
79
mod workspace;
80
81
pub use bookmarks::{BookmarkInfo, MergeReport};
82
pub use checkout::CheckoutReport;
83
pub use config::{parse_size, read_config_file, Config};
84
pub use gc::GcReport;
85
pub use git::{GitExportReport, GitImportReport};
86
pub use hooks::{json_array, json_str, HookOutcome};
87
pub use identity::{Rotation, SignatureStatus};
88
pub use inspect::{BisectStep, BlameLine};
89
pub use policy::PolicyUpdate;
90
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
91
pub use snapshot::{
92
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
93
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
94
    Selection, SnapshotResult,
95
};
96
pub use subrepos::{SubrepoInfo, SubrepoSync};
97
pub use sync::{FetchReport, PullReport};
98
pub use tags::TagInfo;
99
pub use workspace::{SnapshotLock, WorkspaceInfo};
100
101
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
102
    let tmp = path.with_extension("tmp");
103
    {
104
        let mut f = fs::File::create(&tmp)?;
105
        f.write_all(data)?;
106
        f.sync_all()?;
107
    }
108
    fs::rename(&tmp, path)?;
109
    Ok(())
110
}
111
112
pub struct LogEntry {
113
    pub hash: ChangeHash,
114
    /// Metadata from the state; the full change may be absent in a shallow repository.
115
    pub change: crate::state::ChangeMeta,
116
    pub is_working_copy: bool,
117
    pub is_head: bool,
118
}
119
120
/// A file as found on disk or in an imported tree.
121
pub(crate) struct FsEntry {
122
    pub kind: NodeKind,
123
    pub exec: bool,
124
    /// File content, or a symlink's target. Empty when `blob` is set.
125
    pub content: Vec<u8>,
126
    /// The stored blob of an opaque file whose size and mtime are unchanged
127
    /// since the last manifest (spec §12.3 stat cache); the content was not
128
    /// read.
129
    pub blob: Option<ObjectRef>,
130
    /// BLAKE3 of the content, carried over from the manifest when the stat
131
    /// is unchanged, so the manifest can be rewritten without rehashing.
132
    pub content_hash: Option<String>,
133
}
134
135
impl FsEntry {
136
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
137
        FsEntry {
138
            kind,
139
            exec,
140
            content,
141
            blob: None,
142
            content_hash: None,
143
        }
144
    }
145
}
146
147
pub struct Repo {
148
    /// Oxygen-pinned subrepos skipped by the running Git export.
149
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
150
    root: PathBuf,
151
    oxy: PathBuf,
152
    store: Store,
153
    workspace: WorkspaceId,
154
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
155
    bare: bool,
156
    keys_dir: PathBuf,
157
    user_config: PathBuf,
158
    pub config: Config,
159
}
160
161
/// Marker file of a bare repository, inside `.oxy/`.
162
const BARE_MARKER: &str = "bare";
163
/// Marker of a hosted repository that has no id yet: the first push binds
164
/// it to the pusher's id (spec §16.1).
165
const UNBOUND_MARKER: &str = "unbound";
166
167
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
168
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
169
pub fn default_home() -> PathBuf {
170
    if let Ok(h) = std::env::var("OXY_HOME") {
171
        return PathBuf::from(h);
172
    }
173
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
174
        return PathBuf::from(x).join("oxy");
175
    }
176
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
177
    PathBuf::from(home).join(".config").join("oxy")
178
}
179
180
pub fn default_keys_dir() -> PathBuf {
181
    default_home().join("keys")
182
}
183
184
pub fn default_user_config() -> PathBuf {
185
    default_home().join("config.toml")
186
}
187
188
/// Where `create_identity` records the author.
189
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190
pub enum IdentityScope {
191
    /// The user file: every repository of this user signs with it.
192
    User,
193
    /// This repository only.
194
    Repo,
195
}
196
197
impl Repo {
198
    // ------------------------------------------------------------ lifecycle
199
200
    pub fn init(root: &Path) -> Result<Repo> {
201
        let mut id = [0u8; 16];
202
        rand::rngs::OsRng.fill_bytes(&mut id);
203
        Self::init_with_id(root, id)
204
    }
205
206
    /// Initialize a repository with a given repository ID (clones share the
207
    /// ID of their origin, spec §14.4).
208
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
209
        fs::create_dir_all(root)?;
210
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
211
        let oxy = root.join(OXY_DIR);
212
        if oxy.exists() {
213
            return fail(format!("{} is already an oxy repository", root.display()));
214
        }
215
        fs::create_dir_all(oxy.join("ops"))?;
216
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
217
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
218
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
219
        config.save(&oxy.join("config"))?;
220
        let workspace = WorkspaceId::random();
221
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
222
        let store = Store::open(oxy.join("objects"))?;
223
        let repo = Repo {
224
            git_export_skipped: Default::default(),
225
            root,
226
            oxy,
227
            store,
228
            workspace,
229
            bare: false,
230
            keys_dir: default_keys_dir(),
231
            user_config: default_user_config(),
232
            config,
233
        };
234
        repo.register_workspace(&workspace, &repo.root)?;
235
236
        let wc = repo.new_working_copy(vec![], "");
237
        let wc_hash = repo.store.put_change(&wc)?;
238
        let mut view = View::default();
239
        view.bookmarks.insert(
240
            repo.config.bookmark.clone(),
241
            repo.store.put_state(&StateObject::new(vec![]))?,
242
        );
243
        view.workspaces.insert(workspace, wc_hash);
244
        repo.record_op(&[], "oxy init", view)?;
245
        Ok(repo)
246
    }
247
248
    /// Create a bare repository: an object store, operation log and
249
    /// references with no workspace and no working copy, for hosting
250
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
251
    pub fn init_bare(root: &Path) -> Result<Repo> {
252
        let mut id = [0u8; 16];
253
        rand::rngs::OsRng.fill_bytes(&mut id);
254
        Self::init_bare_with_id(root, id)
255
    }
256
257
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
258
        fs::create_dir_all(root)?;
259
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
260
        let oxy = root.join(OXY_DIR);
261
        if oxy.exists() {
262
            return fail(format!("{} is already an oxy repository", root.display()));
263
        }
264
        fs::create_dir_all(oxy.join("ops"))?;
265
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
266
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
267
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
268
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
269
        config.save(&oxy.join("config"))?;
270
        let store = Store::open(oxy.join("objects"))?;
271
        let repo = Repo {
272
            git_export_skipped: Default::default(),
273
            root,
274
            oxy,
275
            store,
276
            workspace: WorkspaceId::ZERO,
277
            bare: true,
278
            keys_dir: default_keys_dir(),
279
            user_config: default_user_config(),
280
            config,
281
        };
282
        let mut view = View::default();
283
        view.bookmarks.insert(
284
            repo.config.bookmark.clone(),
285
            repo.store.put_state(&StateObject::new(vec![]))?,
286
        );
287
        repo.record_op(&[], "oxy init --bare", view)?;
288
        Ok(repo)
289
    }
290
291
    /// A bare repository with no id yet. Its `id()` is all zero until the
292
    /// first push binds it (`bind_id`), so an existing repository can be
293
    /// pushed to a freshly created hosted one and keep its identity.
294
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
295
        let repo = Self::init_bare_with_id(root, [0; 16])?;
296
        fs::remove_file(repo.oxy.join("id"))?;
297
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
298
        Ok(repo)
299
    }
300
301
    pub fn is_unbound(&self) -> bool {
302
        self.oxy.join(UNBOUND_MARKER).is_file()
303
    }
304
305
    /// Give an unbound repository its id.
306
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
307
        if !self.is_unbound() {
308
            return fail("this repository already has an id");
309
        }
310
        if id == [0; 16] {
311
            return fail("a repository id cannot be all zero");
312
        }
313
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
314
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
315
        Ok(())
316
    }
317
318
    /// Whether this repository has no working copy (`init_bare`).
319
    pub fn is_bare(&self) -> bool {
320
        self.bare
321
    }
322
323
    /// Open the repository containing `start` (searching upwards).
324
    pub fn open(start: &Path) -> Result<Repo> {
325
        let start = start.canonicalize()?;
326
        let mut dir: Option<&Path> = Some(&start);
327
        while let Some(d) = dir {
328
            let oxy = d.join(OXY_DIR);
329
            if oxy.is_file() {
330
                // A secondary workspace (spec §12.2): the file points at the repository.
331
                let text = fs::read_to_string(&oxy)?;
332
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
333
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
334
                };
335
                let format = fs::read_to_string(shared.join("format"))?;
336
                if format != FORMAT_LINE {
337
                    return fail(format!("unsupported repository format: {}", format.trim()));
338
                }
339
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
340
                let store = Store::open(shared.join("objects"))?;
341
                let mut repo = Repo {
342
                    git_export_skipped: Default::default(),
343
                    root: d.to_path_buf(),
344
                    oxy: shared,
345
                    store,
346
                    workspace,
347
                    bare: false,
348
                    keys_dir: default_keys_dir(),
349
                    user_config: default_user_config(),
350
                    config,
351
                };
352
                repo.apply_workspace_bookmark();
353
                return Ok(repo);
354
            }
355
            if oxy.is_dir() {
356
                let format = fs::read_to_string(oxy.join("format"))?;
357
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
358
                let bare = oxy.join(BARE_MARKER).is_file();
359
                let workspace = if bare {
360
                    WorkspaceId::ZERO
361
                } else {
362
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
363
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
364
                };
365
                let store = Store::open(oxy.join("objects"))?;
366
                let mut repo = Repo {
367
                    git_export_skipped: Default::default(),
368
                    root: d.to_path_buf(),
369
                    oxy,
370
                    store,
371
                    workspace,
372
                    bare,
373
                    keys_dir: default_keys_dir(),
374
                    user_config: default_user_config(),
375
                    config,
376
                };
377
                if !bare {
378
                    repo.apply_workspace_bookmark();
379
                }
380
                if format == FORMAT1_LINE {
381
                    repo.migrate_format1()?;
382
                } else if format != FORMAT_LINE {
383
                    return fail(format!("unsupported repository format: {}", format.trim()));
384
                }
385
                return Ok(repo);
386
            }
387
            dir = d.parent();
388
        }
389
        fail(format!(
390
            "no oxy repository found at or above {}",
391
            start.display()
392
        ))
393
    }
394
395
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
396
    /// into format 2, where each bookmark names a `state` object.
397
    fn migrate_format1(&self) -> Result<()> {
398
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
399
        let head = ObjectRef::from_hex(hex.trim())
400
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
401
        // Collect the chain root-first.
402
        let mut chain: Vec<Format1Op> = Vec::new();
403
        let mut cur = Some(head);
404
        while let Some(r) = cur {
405
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
406
            cur = op.parents.first().copied();
407
            chain.push(op);
408
        }
409
        chain.reverse();
410
        let mut new_parent: Option<ObjectRef> = None;
411
        for old in chain {
412
            let mut view = View::default();
413
            for (name, heads) in &old.view.bookmarks {
414
                view.bookmarks.insert(
415
                    name.clone(),
416
                    self.store.put_state(&StateObject::new(heads.clone()))?,
417
                );
418
            }
419
            view.workspaces = old.view.workspaces.clone();
420
            let op = Op {
421
                parents: new_parent.into_iter().collect(),
422
                hlc: old.hlc,
423
                command: old.command,
424
                view,
425
            };
426
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
427
        }
428
        write_atomic(
429
            &self.oxy.join("ops").join("head"),
430
            new_parent.unwrap().to_hex().as_bytes(),
431
        )?;
432
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
433
        Ok(())
434
    }
435
436
    /// Pack automatically once many loose objects have accumulated.
437
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
438
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
439
            self.store.pack_loose()?;
440
            self.store.merge_packs()?;
441
        }
442
        Ok(())
443
    }
444
445
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
446
    pub fn id(&self) -> Result<[u8; 16]> {
447
        if self.is_unbound() {
448
            return Ok([0; 16]);
449
        }
450
        let path = self.oxy.join("id");
451
        match fs::read_to_string(&path) {
452
            Ok(h) => hex::decode(h.trim())
453
                .ok()
454
                .and_then(|v| v.try_into().ok())
455
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
456
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
457
                let mut id = [0u8; 16];
458
                rand::rngs::OsRng.fill_bytes(&mut id);
459
                write_atomic(&path, hex::encode(id).as_bytes())?;
460
                Ok(id)
461
            }
462
            Err(e) => Err(e.into()),
463
        }
464
    }
465
466
    pub fn root(&self) -> &Path {
467
        &self.root
468
    }
469
    pub fn store(&self) -> &Store {
470
        &self.store
471
    }
472
    pub fn workspace(&self) -> WorkspaceId {
473
        self.workspace
474
    }
475
476
    /// Use a different user directory for keys and the user config file
477
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
478
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
479
        let dir = dir.into();
480
        self.keys_dir = dir.join("keys");
481
        self.user_config = dir.join("config.toml");
482
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
483
            self.config = c;
484
        }
485
        self.apply_workspace_bookmark();
486
        self
487
    }
488
489
    /// The workspace's current bookmark (spec §10.1) overrides the
490
    /// configured default when `oxy bookmark switch` has recorded one.
491
    fn apply_workspace_bookmark(&mut self) {
492
        if let Ok(b) = fs::read_to_string(
493
            self.oxy
494
                .join("workspaces")
495
                .join(self.workspace.to_hex())
496
                .join("bookmark"),
497
        ) {
498
            let b = b.trim();
499
            if !b.is_empty() {
500
                self.config.bookmark = b.to_string();
501
            }
502
        }
503
    }
504
505
    pub fn user_config_path(&self) -> &Path {
506
        &self.user_config
507
    }
508
509
    /// Set a key in the user file and refresh the effective configuration.
510
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
511
        Config::set_user(&self.user_config, key, value)?;
512
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
513
        Ok(())
514
    }
515
516
    pub fn save_config(&self) -> Result<()> {
517
        self.config.save(&self.oxy.join("config"))
518
    }
519
520
    fn author(&self) -> KeyId {
521
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
522
    }
523
}
524
525
impl Repo {
526
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
527
        let mut c = Change {
528
            change_id: ChangeId::random(),
529
            deps,
530
            author: self.author(),
531
            hlc: Hlc::now(),
532
            message: message.into(),
533
            tree_ops: vec![],
534
            edits: vec![],
535
            kind: ChangeKind::WorkingCopy,
536
        };
537
        c.normalize();
538
        c
539
    }
540
541
    // ------------------------------------------------------------ operation log
542
543
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
544
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
545
        let r = ObjectRef::from_hex(hex.trim())
546
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
547
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
548
        Ok((r, op))
549
    }
550
551
    pub fn view(&self) -> Result<View> {
552
        Ok(self.head_op()?.1.view)
553
    }
554
555
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
556
        let op = Op {
557
            parents: parents.to_vec(),
558
            hlc: Hlc::now(),
559
            command: command.into(),
560
            view,
561
        };
562
        let r = self.store.put(ObjectType::Op, &op.encode())?;
563
        write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?;
564
        Ok(r)
565
    }
566
567
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
568
        let mut out = Vec::new();
569
        let (mut r, mut op) = self.head_op()?;
570
        loop {
571
            let next = op.parents.first().copied();
572
            out.push((r, op));
573
            match next {
574
                Some(p) => {
575
                    r = p;
576
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
577
                }
578
                None => break,
579
            }
580
        }
581
        Ok(out)
582
    }
583
584
    /// Undo the last user command (spec §12.1). Operations that only recorded
585
    /// a working-copy snapshot are skipped, since the files are still on disk
586
    /// and the next snapshot recreates them.
587
    pub fn undo(&self) -> Result<Op> {
588
        let (_, mut op) = self.head_op()?;
589
        while op.is_snapshot() {
590
            let Some(parent) = op.parents.first() else {
591
                break;
592
            };
593
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
594
        }
595
        let Some(parent) = op.parents.first() else {
596
            return fail("nothing to undo");
597
        };
598
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
599
        write_atomic(
600
            &self.oxy.join("ops").join("head"),
601
            parent.to_hex().as_bytes(),
602
        )?;
603
        self.drop_manifest();
604
        Ok(parent_op)
605
    }
606
607
    /// The last operation that was not a snapshot.
608
    pub fn last_command(&self) -> Result<Op> {
609
        let (_, mut op) = self.head_op()?;
610
        while op.is_snapshot() {
611
            let Some(parent) = op.parents.first() else {
612
                break;
613
            };
614
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
615
        }
616
        Ok(op)
617
    }
618
619
    // ------------------------------------------------------------ states
620
621
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
622
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
623
        if let Some(st) = self.load_state_checkpointed(heads)? {
624
            return Ok(st);
625
        }
626
        self.load_state_full(heads)
627
    }
628
629
    /// Load the dependency closure of `heads` change by change.
630
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
631
        let mut state = State::new();
632
        let mut stack: Vec<ChangeHash> = heads.to_vec();
633
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
634
        while let Some(h) = stack.pop() {
635
            if !seen.insert(h) {
636
                continue;
637
            }
638
            let c = self.store.get_change(&h)?;
639
            stack.extend(c.deps.iter().copied());
640
            state.add_unchecked(c);
641
        }
642
        state.validate()?;
643
        Ok(state)
644
    }
645
646
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
647
        if self.bare {
648
            return fail("this is a bare repository: it has no working copy");
649
        }
650
        let view = self.view()?;
651
        let h = *view
652
            .workspaces
653
            .get(&self.workspace)
654
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
655
        Ok((h, self.store.get_change(&h)?))
656
    }
657
658
    /// Heads of a bookmark's state (spec §10.1).
659
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
660
        match view.bookmarks.get(bookmark) {
661
            Some(st) => Ok(self.store.get_state(st)?.heads),
662
            None => Ok(vec![]),
663
        }
664
    }
665
666
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
667
        self.heads_of(&self.view()?, &self.config.bookmark)
668
    }
669
670
    // ------------------------------------------------------------ blobs
671
672
    fn blob_for(content: &[u8]) -> Blob {
673
        Blob {
674
            length: content.len() as u64,
675
            chunks: crate::chunk::chunks(content)
676
                .into_iter()
677
                .map(|c| hash_object(ObjectType::Chunk, c))
678
                .collect(),
679
        }
680
    }
681
682
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
683
        Self::blob_for(content).hash()
684
    }
685
686
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
687
        for c in crate::chunk::chunks(content) {
688
            self.store.put_chunk(c)?;
689
        }
690
        Ok(self
691
            .store
692
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
693
    }
694
695
    /// Read a blob's content, fetching it from the remote that withheld it
696
    /// when it is lazily absent (spec §13.5).
697
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
698
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
699
            self.fetch_lazy_blob(r)?;
700
        }
701
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
702
        let mut out = Vec::with_capacity(blob.length as usize);
703
        for c in &blob.chunks {
704
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
705
        }
706
        Ok(out)
707
    }
708
709
    // ------------------------------------------------------------ working copy
710
711
    /// Attributes from the `.oxyattributes` files in the working directory.
712
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
713
        let mut files: Vec<(String, Vec<u8>)> = Vec::new();
714
        if let Ok(b) = fs::read(self.root.join(".oxyattributes")) {
715
            files.push((".oxyattributes".into(), b));
716
        }
717
        let mut wb = ignore::WalkBuilder::new(&self.root);
718
        wb.hidden(false)
719
            .git_ignore(false)
720
            .git_global(false)
721
            .git_exclude(false)
722
            .require_git(false)
723
            .follow_links(false)
724
            .add_custom_ignore_filename(".oxyignore");
725
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
726
        for entry in wb.build().flatten() {
727
            if entry.file_name() == ".oxyattributes"
728
                && entry.path() != self.root.join(".oxyattributes")
729
            {
730
                if let Ok(b) = fs::read(entry.path()) {
731
                    let rel: String = entry
732
                        .path()
733
                        .strip_prefix(&self.root)
734
                        .unwrap()
735
                        .components()
736
                        .map(|c| c.as_os_str().to_string_lossy().to_string())
737
                        .collect::<Vec<_>>()
738
                        .join("/");
739
                    files.push((rel, b));
740
                }
741
            }
742
        }
743
        crate::attributes::Attributes::from_files(
744
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
745
        )
746
    }
747
748
    /// Attributes from a materialized state's `.oxyattributes` files.
749
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
750
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
751
            match &f.content {
752
                FileContent::Text { bytes, .. }
753
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
754
                {
755
                    Some((p.as_str(), bytes.as_slice()))
756
                }
757
                _ => None,
758
            }
759
        }))
760
    }
761
762
    /// Store a blob, raw when the path is `nocompress`.
763
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
764
        if !nocompress {
765
            return self.store_blob(content);
766
        }
767
        for c in crate::chunk::chunks(content) {
768
            self.store.put_chunk_nocompress(c)?;
769
        }
770
        Ok(self
771
            .store
772
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
773
    }
774
775
    fn locks_dir(&self) -> PathBuf {
776
        self.oxy.join("locks")
777
    }
778
779
    /// Whether `path` is locked locally for editing (spec §18, advisory).
780
    pub fn is_locked(&self, path: &str) -> bool {
781
        self.locks_dir().join(path.replace('/', "%2F")).exists()
782
    }
783
784
    /// Take the advisory local lock on a `lockable` file and make it writable.
785
    pub fn lock_path(&self, path: &str) -> Result<()> {
786
        let attrs = self.disk_attributes();
787
        if !attrs.lookup(path).lockable {
788
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
789
        }
790
        fs::create_dir_all(self.locks_dir())?;
791
        write_atomic(
792
            &self.locks_dir().join(path.replace('/', "%2F")),
793
            std::process::id().to_string().as_bytes(),
794
        )?;
795
        set_readonly(&self.root.join(path), false)?;
796
        Ok(())
797
    }
798
799
    /// Release the local lock and make the file read-only again.
800
    pub fn unlock_path(&self, path: &str) -> Result<()> {
801
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
802
        if self.root.join(path).exists() {
803
            set_readonly(&self.root.join(path), true)?;
804
        }
805
        Ok(())
806
    }
807
808
    /// Whether a repository path is inside the sparse filter (spec §17).
809
    pub fn in_scope(&self, path: &str) -> bool {
810
        self.config.sparse_paths.is_empty()
811
            || self
812
                .config
813
                .sparse_paths
814
                .iter()
815
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
816
    }
817
818
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
819
        self.walk_working_copy_with(None, &BTreeMap::new())
820
    }
821
822
    /// A walker over the working copy that never enters a nested repository
823
    /// (a directory below the root holding `.oxy` or `.git`); the directories
824
    /// it skipped are collected into `nested`.
825
    pub(crate) fn walker(
826
        &self,
827
        nested: &std::sync::Arc<std::sync::Mutex<Vec<PathBuf>>>,
828
    ) -> ignore::WalkBuilder {
829
        let mut wb = ignore::WalkBuilder::new(&self.root);
830
        wb.hidden(false)
831
            .git_ignore(false)
832
            .git_global(false)
833
            .git_exclude(false)
834
            .require_git(false)
835
            .follow_links(false)
836
            .add_custom_ignore_filename(".oxyignore");
837
        let nested = nested.clone();
838
        wb.filter_entry(move |e| {
839
            if e.file_name() == OXY_DIR {
840
                return false;
841
            }
842
            if e.depth() > 0
843
                && e.file_type().is_some_and(|t| t.is_dir())
844
                && (e.path().join(OXY_DIR).exists() || e.path().join(".git").exists())
845
            {
846
                nested.lock().unwrap().push(e.path().to_path_buf());
847
                return false;
848
            }
849
            true
850
        });
851
        wb
852
    }
853
854
    /// Walk the working copy; with a manifest, a file whose size and mtime
855
    /// match it is not read: an opaque file yields its known blob, a text
856
    /// file is read but keeps its known hash. Files modified within two
857
    /// seconds of the manifest are never trusted (a racy stat).
858
    ///
859
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
860
    /// (the base state's files) that exists on disk is included even when
861
    /// an ignore rule matches it, as in Git.
862
    fn walk_working_copy_with(
863
        &self,
864
        cache: Option<&prompt::Manifest>,
865
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
866
    ) -> Result<BTreeMap<String, FsEntry>> {
867
        let nested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
868
        let wb = self.walker(&nested);
869
        let mut out = BTreeMap::new();
870
        let mut files: Vec<(String, PathBuf, fs::Metadata)> = Vec::new();
871
        for entry in wb.build() {
872
            let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?;
873
            let path = entry.path();
874
            if path == self.root {
875
                continue;
876
            }
877
            let rel = path.strip_prefix(&self.root).unwrap();
878
            let rel: String = rel
879
                .components()
880
                .map(|c| c.as_os_str().to_string_lossy().to_string())
881
                .collect::<Vec<_>>()
882
                .join("/");
883
            let Some(ft) = entry.file_type() else {
884
                continue;
885
            };
886
            if ft.is_dir() || !self.in_scope(&rel) {
887
                continue;
888
            }
889
            if ft.is_symlink() {
890
                let target = fs::read_link(path)?;
891
                out.insert(
892
                    rel,
893
                    FsEntry::new(
894
                        NodeKind::Symlink,
895
                        false,
896
                        target.to_string_lossy().as_bytes().to_vec(),
897
                    ),
898
                );
899
            } else if ft.is_file() {
900
                let meta = entry
901
                    .metadata()
902
                    .map_err(|e| RepoError::Msg(e.to_string()))?;
903
                files.push((rel, path.to_path_buf(), meta));
904
            }
905
        }
906
        // Reading files is most of a walk's cost; do it in parallel.
907
        {
908
            use rayon::prelude::*;
909
            let read: Vec<(String, FsEntry)> = files
910
                .par_iter()
911
                .map(|(rel, path, meta)| {
912
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache)?))
913
                })
914
                .collect::<Result<Vec<_>>>()?;
915
            for (rel, mut e) in read {
916
                // A cached blob the store lost (gc, a partial clone): read the file after all.
917
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
918
                    e.content = fs::read(self.root.join(&rel))?;
919
                    e.blob = None;
920
                }
921
                out.insert(rel, e);
922
            }
923
        }
924
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
925
        // already tracked as subrepo nodes, they contribute their pin;
926
        // unregistered ones are left alone.
927
        let modules = self.modules_on_disk();
928
        let removed = self.removed_subrepos();
929
        for rel in &removed {
930
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
931
                self.clear_removed_subrepo(rel);
932
            }
933
        }
934
        let nested_dirs = std::mem::take(&mut *nested.lock().unwrap());
935
        for dir in nested_dirs {
936
            let rel = self.rel_path(&dir);
937
            if !self.in_scope(&rel) || removed.contains(&rel) {
938
                continue;
939
            }
940
            let registered = modules.entries.get(&rel);
941
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
942
            {
943
                continue;
944
            }
945
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
946
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
947
        }
948
        // Tracked paths the ignore rules hid.
949
        for (rel, (kind, blob)) in tracked {
950
            if out.contains_key(rel) || !self.in_scope(rel) {
951
                continue;
952
            }
953
            let path = self.root.join(rel);
954
            if *kind == NodeKind::Subrepo {
955
                if removed.contains(rel) {
956
                    continue;
957
                }
958
                let present =
959
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
960
                if present {
961
                    let pin = subrepos::read_pin(
962
                        &path,
963
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
964
                    )?;
965
                    out.insert(
966
                        rel.clone(),
967
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
968
                    );
969
                } else if let Some(b) = blob {
970
                    // Not cloned (or emptied): the pin stays as recorded, as a
971
                    // Git gitlink does when its directory is absent.
972
                    out.insert(
973
                        rel.clone(),
974
                        FsEntry {
975
                            kind: NodeKind::Subrepo,
976
                            exec: false,
977
                            content: vec![],
978
                            blob: Some(*b),
979
                            content_hash: None,
980
                        },
981
                    );
982
                }
983
                continue;
984
            }
985
            let Ok(meta) = fs::symlink_metadata(&path) else {
986
                continue;
987
            };
988
            let ft = meta.file_type();
989
            if ft.is_symlink() {
990
                let target = fs::read_link(&path)?;
991
                out.insert(
992
                    rel.clone(),
993
                    FsEntry::new(
994
                        NodeKind::Symlink,
995
                        false,
996
                        target.to_string_lossy().as_bytes().to_vec(),
997
                    ),
998
                );
999
            } else if ft.is_file() {
1000
                let e = self.file_entry(rel, &path, &meta, cache)?;
1001
                out.insert(rel.clone(), e);
1002
            }
1003
        }
1004
        Ok(out)
1005
    }
1006
1007
    /// The entry for one regular file, read or served from the stat cache.
1008
    fn file_entry(
1009
        &self,
1010
        rel: &str,
1011
        path: &Path,
1012
        meta: &fs::Metadata,
1013
        cache: Option<&prompt::Manifest>,
1014
    ) -> Result<FsEntry> {
1015
        let mut e = read_file_entry(rel, path, meta, cache)?;
1016
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
1017
            e.content = fs::read(path)?;
1018
            e.blob = None;
1019
        }
1020
        Ok(e)
1021
    }
1022
1023
    /// The non-directory paths of a snapshot with their kinds, for the
1024
    /// walker's `tracked` set.
1025
    pub(crate) fn tracked_kinds(
1026
        snapshot: &Snapshot,
1027
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
1028
        snapshot
1029
            .files
1030
            .iter()
1031
            .filter(|(_, f)| f.kind != NodeKind::Dir)
1032
            .map(|(p, f)| {
1033
                let blob = match &f.content {
1034
                    FileContent::Opaque { blobs } => blobs.first().copied(),
1035
                    _ => None,
1036
                };
1037
                (p.clone(), (f.kind, blob))
1038
            })
1039
            .collect()
1040
    }
1041
1042
    /// A path under the root as a `/`-separated relative string.
1043
    pub(crate) fn rel_path(&self, path: &Path) -> String {
1044
        path.strip_prefix(&self.root)
1045
            .unwrap_or(path)
1046
            .components()
1047
            .map(|c| c.as_os_str().to_string_lossy().to_string())
1048
            .collect::<Vec<_>>()
1049
            .join("/")
1050
    }
1051
}
1052
1053
impl Repo {
1054
    /// Changes reachable from the bookmark and the working copy, newest first.
1055
    pub fn log(&self) -> Result<Vec<LogEntry>> {
1056
        let heads = self.bookmark_heads()?;
1057
        if self.bare {
1058
            return self.log_state(&heads);
1059
        }
1060
        let (wc_hash, _) = self.working_copy()?;
1061
        let mut all = heads.clone();
1062
        all.push(wc_hash);
1063
        let state = self.load_state(&all)?;
1064
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
1065
        let mut entries: Vec<LogEntry> = Vec::new();
1066
        for (h, meta) in state.changes() {
1067
            entries.push(LogEntry {
1068
                hash: *h,
1069
                change: meta.clone(),
1070
                is_working_copy: *h == wc_hash,
1071
                is_head: head_set.contains(h),
1072
            });
1073
        }
1074
        entries.sort_by(|a, b| {
1075
            b.is_working_copy
1076
                .cmp(&a.is_working_copy)
1077
                .then(b.change.hlc.cmp(&a.change.hlc))
1078
                .then(b.hash.cmp(&a.hash))
1079
        });
1080
        Ok(entries)
1081
    }
1082
1083
    /// The log of the state with these heads, newest first, with no working
1084
    /// copy involved (for hosted repositories and any explicit state).
1085
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1086
        let state = self.load_state(heads)?;
1087
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
1088
        let mut entries: Vec<LogEntry> = state
1089
            .changes()
1090
            .map(|(h, meta)| LogEntry {
1091
                hash: *h,
1092
                change: meta.clone(),
1093
                is_working_copy: false,
1094
                is_head: head_set.contains(h),
1095
            })
1096
            .collect();
1097
        entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
1098
        Ok(entries)
1099
    }
1100
1101
    /// Resolve a spec to a set of heads: a tag name, the current bookmark's
1102
    /// name, or a single change (`resolve_change`).
1103
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
1104
        let view = self.view()?;
1105
        if let Some(st) = view.bookmarks.get(spec) {
1106
            return Ok(self.store.get_state(st)?.heads);
1107
        }
1108
        if let Some(heads) = self.tag_heads(spec)? {
1109
            return Ok(heads);
1110
        }
1111
        Ok(vec![self.resolve_change(spec)?])
1112
    }
1113
1114
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working copy), or bookmark.
1115
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
1116
        if spec == "@" {
1117
            return Ok(self.working_copy()?.0);
1118
        }
1119
        if let Some(st) = self.view()?.bookmarks.get(spec) {
1120
            let heads = self.store.get_state(st)?.heads;
1121
            return match heads.len() {
1122
                1 => Ok(heads[0]),
1123
                n => fail(format!("bookmark {spec} has {n} heads; name a change, or use it where a state is expected")),
1124
            };
1125
        }
1126
        if spec.is_empty() || spec == "#" {
1127
            return fail("empty change specifier");
1128
        }
1129
        let entries = self.log()?;
1130
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
1131
            entries
1132
                .iter()
1133
                .filter(|e| e.hash.starts_with_hex(hp))
1134
                .collect()
1135
        } else {
1136
            entries
1137
                .iter()
1138
                .filter(|e| e.change.change_id.starts_with_hex(spec))
1139
                .collect()
1140
        };
1141
        match matches.len() {
1142
            1 => Ok(matches[0].hash),
1143
            0 => fail(format!("no change matches {spec:?}")),
1144
            _ => {
1145
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
1146
                if ids.len() == 1 {
1147
                    fail(format!(
1148
                        "change {spec} is divergent: {} variants",
1149
                        matches.len()
1150
                    ))
1151
                } else {
1152
                    fail(format!("{spec:?} is ambiguous"))
1153
                }
1154
            }
1155
        }
1156
    }
1157
1158
    /// Human-readable description of what a change does, with line content.
1159
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
1160
        let change = self.store.get_change(hash)?;
1161
        let base = self.load_state(&change.deps)?;
1162
        let base_snapshot = base.materialize();
1163
        Ok(render_change(&change, &base, &base_snapshot))
1164
    }
1165
}
1166
1167
fn remove_any(path: &Path) -> std::io::Result<()> {
1168
    let m = fs::symlink_metadata(path)?;
1169
    if m.is_dir() {
1170
        fs::remove_dir_all(path)
1171
    } else {
1172
        fs::remove_file(path)
1173
    }
1174
}
1175
1176
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
1177
    let mut perms = fs::metadata(path)?.permissions();
1178
    perms.set_readonly(readonly);
1179
    fs::set_permissions(path, perms)
1180
}
1181
1182
#[cfg(unix)]
1183
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
1184
    use std::os::unix::fs::PermissionsExt;
1185
    let mut perms = fs::metadata(path)?.permissions();
1186
    let mode = perms.mode();
1187
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
1188
    if want != mode {
1189
        perms.set_mode(want);
1190
        fs::set_permissions(path, perms)?;
1191
    }
1192
    Ok(())
1193
}
1194
#[cfg(not(unix))]
1195
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
1196
    Ok(())
1197
}
1198
1199
#[cfg(unix)]
1200
fn is_executable(m: &fs::Metadata) -> bool {
1201
    use std::os::unix::fs::PermissionsExt;
1202
    m.permissions().mode() & 0o111 != 0
1203
}
1204
#[cfg(not(unix))]
1205
fn is_executable(_m: &fs::Metadata) -> bool {
1206
    false
1207
}
1208
1209
fn op_ref(k: OpKey) -> OpRef {
1210
    OpRef {
1211
        change: k.0,
1212
        index: k.1,
1213
    }
1214
}
1215
1216
fn split_path(path: &str) -> (&str, &str) {
1217
    match path.rfind('/') {
1218
        Some(i) => (&path[..i], &path[i + 1..]),
1219
        None => ("", path),
1220
    }
1221
}
1222
1223
/// One regular file's entry from disk, or from the stat cache when its
1224
/// size and mtime match the manifest outside the racy window. Touches no
1225
/// repository state, so the walk runs it in parallel; the caller checks
1226
/// that a cached blob is still in the store.
1227
fn read_file_entry(
1228
    rel: &str,
1229
    path: &Path,
1230
    meta: &fs::Metadata,
1231
    cache: Option<&prompt::Manifest>,
1232
) -> Result<FsEntry> {
1233
    let exec = is_executable(meta);
1234
    let cached = cache.and_then(|m| {
1235
        let e = m.entries.get(rel)?;
1236
        let mtime_ns = prompt::mtime_ns(meta);
1237
        let racy = mtime_ns + 2_000_000_000 >= m.written_ns;
1238
        (e.size == meta.len() && e.mtime_ns == mtime_ns && !racy).then_some(e)
1239
    });
1240
    Ok(match cached {
1241
        Some(e) if e.blob.is_some() => FsEntry {
1242
            kind: NodeKind::File,
1243
            exec,
1244
            content: vec![],
1245
            blob: e.blob,
1246
            content_hash: Some(e.hash.clone()),
1247
        },
1248
        Some(e) => FsEntry {
1249
            kind: NodeKind::File,
1250
            exec,
1251
            content: fs::read(path)?,
1252
            blob: None,
1253
            content_hash: Some(e.hash.clone()),
1254
        },
1255
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
1256
    })
1257
}