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