OXYGENHUB

Coverage / crates/oxy-core/src/repo/mod.rs 88.8%

1834 of 2066 lines run, 429 of 697 functions · run #322 on main · run missed

1
//! A repository on disk: the `.oxy` directory, one workspace, the operation
2
//! log, and the working-copy change (spec §12, §13.1).
3
//!
4
//! Not yet implemented from the spec: packs, checkpoints, multiple
5
//! workspaces, multi-signer policy updates, and the `objects`/`checkpoint`
6
//! endpoints. A repository without a policy is unverified and accepts
7
//! unsigned pushes; with one, everything received is checked (spec §14.5). Changes are signed individually when `core.sign` is
8
//! `change`; the default `seal` leaves them unsigned until push exists.
9
10
use crate::attest::{Attest, AttestBody};
11
use crate::diff::{ranges, split_lines, text_edits};
12
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
13
use crate::identity::{
14
    verify as verify_signature, Delegate, Domain, Identity, Scope, SecretKey, Signature,
15
};
16
use crate::ids::{ChangeId, NodeId, WorkspaceId};
17
use crate::objects::{
18
    Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp,
19
};
20
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
21
use crate::protocol::{
22
    open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef,
23
    SignedAttest, SignedPolicy,
24
};
25
use crate::state::{FileContent, Snapshot, State};
26
use crate::store::{Store, StoreError};
27
#[allow(unused_imports)]
28
use crate::subrepo::Pin;
29
use crate::tree::OpKey;
30
use rand::RngCore;
31
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
32
use std::fs;
33
use std::io::Write;
34
use std::path::{Path, PathBuf};
35
36
pub const OXY_DIR: &str = ".oxy";
37
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
38
const FORMAT1_LINE: &str = "oxy repository format 1\n";
39
const BINARY_SNIFF: usize = 8 * 1024;
40
/// Loose objects tolerated before a commit packs them (spec §13.4).
41
pub const AUTOPACK_THRESHOLD: usize = 4096;
42
43
#[derive(Debug, thiserror::Error)]
44
pub enum RepoError {
45
    #[error("io: {0}")]
46
    Io(#[from] std::io::Error),
47
    #[error(transparent)]
48
    Store(#[from] StoreError),
49
    #[error(transparent)]
50
    Object(#[from] crate::objects::ObjectError),
51
    #[error(transparent)]
52
    State(#[from] crate::state::StateError),
53
    #[error("{0}")]
54
    Msg(String),
55
    /// The operation would leave a conflict where none may be (a rebased
56
    /// change cannot hold one); the caller may offer another way.
57
    #[error("{0}")]
58
    Conflicted(String),
59
}
60
61
pub type Result<T> = std::result::Result<T, RepoError>;
62
63
/// The operation head's reference record on a store that is not this
64
/// disk's directory (oxygen#68).
65
pub const HEAD_RECORD: &str = "ops/head";
66
67
/// How often recording an operation reads the head again when other
68
/// processes keep moving it.
69
const HEAD_TRIES: usize = 8;
70
71
/// The object store of the repository directory `oxy`: `.oxy/objects`,
72
/// or the store `storage.url` names behind a cache of `storage.cache`
73
/// bytes in `.oxy/cache` (oxygen#68). `.oxy/objects` is then only
74
/// scratch space: packs being written, and derived caches.
752436×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762436×
    let Some(url) = &config.storage_url else {
772431×
        return Ok(Store::open(oxy.join("objects"))?);
78
    };
795×
    let options = crate::protocol::RemoteOptions {
805×
        cache_dir: Some(oxy.join("cache")),
815×
        ..Default::default()
825×
    };
835×
    let remote = crate::protocol::open_store(url, &options)
845×
        .ok_or_else(|| {
851×
            RepoError::Msg(format!(
861×
                "storage.url {url}: this oxy cannot open that kind of store (dir://, or s3://, gs:// and az:// in builds with cloud stores)"
871×
            ))
881×
        })?
894×
        .map_err(|e| RepoError::Msg(format!("open the repository's store {url}: {e}")))?;
904×
    let cached = crate::strata::CachingStore::open(
914×
        std::sync::Arc::from(remote),
924×
        oxy.join("cache"),
934×
        config.storage_cache,
94
    )
954×
    .map_err(|e| RepoError::Msg(format!("open the cache for {url}: {e}")))?;
964×
    Ok(Store::open_on(
974×
        std::sync::Arc::new(cached),
984×
        oxy.join("objects"),
990×
    )?)
1002436×
}
101
102162×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103162×
    Err(RepoError::Msg(s.into()))
104162×
}
105
106
mod bookmarks;
107
mod checkout;
108
mod checkpoint;
109
mod config;
110
mod doctor;
111
mod fsck;
112
mod gc;
113
mod git;
114
mod history;
115
mod hooks;
116
mod hosted;
117
mod identity;
118
mod inspect;
119
mod keyless;
120
mod ops;
121
mod policy;
122
mod prompt;
123
mod receipts;
124
mod revset;
125
mod snapshot;
126
pub mod strata;
127
mod subrepos;
128
mod sync;
129
mod tags;
130
#[cfg(test)]
131
mod tests;
132
mod touched;
133
mod transparency;
134
mod walk;
135
mod workspace;
136
137
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
138
pub use checkout::CheckoutReport;
139
pub use config::{parse_size, read_config_file, Config};
140
pub use doctor::{Check, DoctorReport, Health};
141
pub use fsck::{FsckReport, Problem, Severity};
142
pub use gc::GcReport;
143
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
144
pub use hooks::{json_array, json_str, HookOutcome};
145
pub use hosted::FileEdit;
146
pub use identity::{Rotation, SignatureStatus};
147
pub use inspect::{BisectStep, BlameLine, Description};
148
pub use keyless::home_key;
149
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
150
pub use policy::PolicyUpdate;
151
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
152
pub use receipts::ReceiptInfo;
153
pub use revset::{Revset, REVSET_BUDGET};
154
pub use snapshot::{
155
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
156
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
157
    Selection, SnapshotResult,
158
};
159
pub use subrepos::{SubrepoInfo, SubrepoSync};
160
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT};
161
pub use tags::TagInfo;
162
pub use transparency::LogAudit;
163
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
164
165
/// The file name under which per-bookmark or per-tag data is kept: `/`
166
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
167
/// than a directory that would clash with it.
1684065×
pub(crate) fn name_file(name: &str) -> String {
1694065×
    name.replace('%', "%25").replace('/', "%2F")
1704065×
}
171
172
/// The name a [`name_file`] file name stands for.
17343×
pub(crate) fn file_name_to_name(file: &str) -> String {
17443×
    file.replace("%2F", "/").replace("%25", "%")
17543×
}
176
1777156×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1787156×
    Ok(crate::durable::write_atomic(path, data)?)
1797156×
}
180
181
/// Replace a cache file: whole or not at all, but without waiting for the
182
/// disk. A cache checks its own bytes when read, so one a crash leaves
183
/// short or stale is rebuilt rather than trusted.
184
/// How many changes a state index may fall behind its working copy before
185
/// it is written again; until then each load replays them.
186
const INDEX_REPLAY_LIMIT: usize = 16;
187
/// The changes whose encodings are kept for building graphs: a batch of
188
/// files often takes inline text from a few changes in turn.
189
const CHANGE_CACHE_COUNT: usize = 4;
190
const CHANGE_CACHE_BYTES: usize = 512 << 20;
191
/// How many state indexes a workspace keeps.
192
const STATE_INDEXES_KEPT: usize = 2;
193
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
194
1952792×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1962792×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1972792×
    fs::write(&tmp, data)?;
1982792×
    fs::rename(&tmp, path)?;
1992792×
    Ok(())
2002792×
}
201
202
pub struct LogEntry {
203
    pub hash: ChangeHash,
204
    /// Metadata from the state; the full change may be absent in a shallow repository.
205
    pub change: crate::state::ChangeMeta,
206
    pub is_working_copy: bool,
207
    pub is_head: bool,
208
}
209
210
/// A text file's base graph key, by path, as a walk asks for it.
211
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
212
213
/// A file as found on disk or in an imported tree.
214
#[derive(Clone)]
215
pub(crate) struct FsEntry {
216
    pub kind: NodeKind,
217
    pub exec: bool,
218
    /// File content, or a symlink's target. Empty when `blob` is set.
219
    /// Shared, so a new file's insert holds it without a copy.
220
    pub content: std::sync::Arc<Vec<u8>>,
221
    /// The stored blob of an opaque file whose size and mtime are unchanged
222
    /// since the last manifest (spec §12.3 stat cache); the content was not
223
    /// read.
224
    pub blob: Option<ObjectRef>,
225
    /// BLAKE3 of the content, carried over from the manifest when the stat
226
    /// is unchanged, so the manifest can be rewritten without rehashing.
227
    pub content_hash: Option<[u8; 32]>,
228
    /// A text file known equal to the base's rendering without reading it:
229
    /// its stat matches the manifest and the manifest recorded it equal to
230
    /// a base file graph with the same key (spec §12.3). `content` is empty.
231
    pub unchanged: bool,
232
    /// The base graph key this file equals, for the next manifest.
233
    pub graph_key: Option<[u8; 32]>,
234
    /// Size and mtime already known to be current (a checkout leaving the
235
    /// file as it was), so the manifest need not stat it again.
236
    pub stat: Option<(u64, u128)>,
237
}
238
239
impl FsEntry {
24022545×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
24122545×
        FsEntry {
24222545×
            kind,
24322545×
            exec,
24422545×
            content: std::sync::Arc::new(content),
24522545×
            blob: None,
24622545×
            content_hash: None,
24722545×
            unchanged: false,
24822545×
            graph_key: None,
24922545×
            stat: None,
25022545×
        }
25122545×
    }
252
}
253
254
pub struct Repo {
255
    /// The key a host accepts certified updates with (spec §14.7): when
256
    /// set, accepting a reference update signed by a short-lived key also
257
    /// records the host's acceptance and its time.
258
    pub(crate) acceptor: Option<std::sync::Arc<(Identity, crate::identity::SecretKey)>>,
259
    /// With `author.signer = keyless`, the fresh key the hub last
260
    /// certified and when its certificate ends (spec §14.7): kept in memory
261
    /// only, for one command.
262
    pub(crate) keyless_key: std::cell::RefCell<Option<(KeyId, crate::identity::SecretKey, u64)>>,
263
    /// Oxygen-pinned subrepos skipped by the running Git export.
264
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
265
    /// The manifest as last read, with the file identity it was read from,
266
    /// so one command parses it once (see `read_manifest`).
267
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
268
    /// A listing of the working copy left by a failed clean check, for the
269
    /// snapshot that follows it to reuse; taken by the next walk and
270
    /// dropped whenever the manifest is written.
271
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
272
    /// The nested repositories the last walk left out, being neither
273
    /// registered nor tracked subrepos (oxygen#43).
274
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
275
    /// New untracked files the last walk left out for their size, with
276
    /// their sizes (oxygen#98).
277
    pub(crate) skipped_large: std::cell::RefCell<Vec<(String, u64)>>,
278
    root: PathBuf,
279
    oxy: PathBuf,
280
    store: Store,
281
    workspace: WorkspaceId,
282
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
283
    bare: bool,
284
    keys_dir: PathBuf,
285
    user_config: PathBuf,
286
    pub config: Config,
287
    /// What the working copy's file system can represent (spec §7.7).
288
    platform: crate::portable::Platform,
289
    /// The encodings of the changes last read for their inline inserts,
290
    /// oldest first.
291
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
292
    /// `--at-op`: read the repository as it was after this operation;
293
    /// recording an operation is refused.
294
    at_op: Option<ObjectRef>,
295
    /// The directories (with their times) and nested repositories of the
296
    /// last walk, for the manifest written from it.
297
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
298
    /// The directories a manifest check listed, for its restamp only.
299
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
300
}
301
302
/// A walk's directories with their times, and its nested repositories.
303
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
304
305
/// Marker file of a bare repository, inside `.oxy/`.
306
const BARE_MARKER: &str = "bare";
307
/// Marker of a hosted repository that has no id yet: the first push binds
308
/// it to the pusher's id (spec §16.1).
309
const UNBOUND_MARKER: &str = "unbound";
310
311
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
312
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
3137551×
pub fn default_home() -> PathBuf {
3147551×
    if let Ok(h) = std::env::var("OXY_HOME") {
3157545×
        return PathBuf::from(h);
3166×
    }
3176×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3180×
        return PathBuf::from(x).join("oxy");
3196×
    }
320
    // Windows has no HOME as a rule: the roaming profile's application
321
    // data, as Windows programs keep theirs.
322
    #[cfg(windows)]
323
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
324
        return PathBuf::from(d).join("oxy");
325
    }
3266×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3276×
    PathBuf::from(home).join(".config").join("oxy")
3287551×
}
329
3302437×
pub fn default_keys_dir() -> PathBuf {
3312437×
    default_home().join("keys")
3322437×
}
333
3344872×
pub fn default_user_config() -> PathBuf {
3354872×
    default_home().join("config.toml")
3364872×
}
337
338
/// Where `create_identity` records the author.
339
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
340
pub enum IdentityScope {
341
    /// The user file: every repository of this user signs with it.
342
    User,
343
    /// This repository only.
344
    Repo,
345
}
346
347
impl Repo {
348
    // ------------------------------------------------------------ lifecycle
349
350227×
    pub fn init(root: &Path) -> Result<Repo> {
351227×
        let mut id = [0u8; 16];
352227×
        rand::rngs::OsRng.fill_bytes(&mut id);
353227×
        Self::init_with_id(root, id)
354227×
    }
355
356
    /// Initialize a repository with a given repository ID (clones share the
357
    /// ID of their origin, spec §14.4).
358476×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
359476×
        Self::init_on(root, id, None)
360476×
    }
361
362
    /// A new repository with a fresh id, bare or not, on `storage` or in
363
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
36412×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
36512×
        let mut id = [0u8; 16];
36612×
        rand::rngs::OsRng.fill_bytes(&mut id);
36712×
        if bare {
3680×
            Self::init_bare_on(root, id, storage)
369
        } else {
37012×
            Self::init_on(root, id, storage)
371
        }
37212×
    }
373
374
    /// Initialize a repository whose objects and operation head are kept
375
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
376491×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
377491×
        fs::create_dir_all(root)?;
378491×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
379491×
        let oxy = root.join(OXY_DIR);
380491×
        if oxy.exists() {
3811×
            return fail(format!("{} is already an oxy repository", root.display()));
382490×
        }
383490×
        fs::create_dir_all(oxy.join("ops"))?;
384490×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
385490×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
386490×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
387490×
        if let Some(url) = storage {
3883×
            config.set("storage.url", url)?;
389487×
        }
390490×
        config.save(&oxy.join("config"))?;
391490×
        let workspace = WorkspaceId::random();
392490×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
393490×
        let store = open_objects(&oxy, &config)?;
394489×
        let repo = Repo {
395489×
            acceptor: None,
396489×
            keyless_key: Default::default(),
397489×
            last_change: Default::default(),
398489×
            at_op: None,
399489×
            walked_dirs: Default::default(),
400489×
            listed_dirs: Default::default(),
401489×
            git_export_skipped: Default::default(),
402489×
            manifest_cache: Default::default(),
403489×
            listing_cache: Default::default(),
404489×
            untracked_nested: Default::default(),
405489×
            skipped_large: Default::default(),
406489×
            root,
407489×
            oxy,
408489×
            store,
409489×
            workspace,
410489×
            bare: false,
411489×
            keys_dir: default_keys_dir(),
412489×
            platform: crate::portable::Platform::current(),
413489×
            user_config: default_user_config(),
414489×
            config,
415489×
        };
416489×
        repo.register_workspace(&workspace, &repo.root)?;
417
418489×
        let wc = repo.new_working_copy(vec![], "");
419489×
        let wc_hash = repo.store.put_change(&wc)?;
420489×
        let mut view = View::default();
421489×
        view.bookmarks.insert(
422489×
            repo.config.bookmark.clone(),
423489×
            repo.store.put_state(&StateObject::new(vec![]))?,
424
        );
425489×
        view.workspaces.insert(workspace, wc_hash);
426489×
        repo.record_op(&[], "oxy init", view)?;
427487×
        Ok(repo)
428491×
    }
429
430
    /// Create a bare repository: an object store, operation log and
431
    /// references with no workspace and no working copy, for hosting
432
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4335×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4345×
        let mut id = [0u8; 16];
4355×
        rand::rngs::OsRng.fill_bytes(&mut id);
4365×
        Self::init_bare_with_id(root, id)
4375×
    }
438
43940×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
44040×
        Self::init_bare_on(root, id, None)
44140×
    }
442
443
    /// [`Repo::init_on`] for a bare repository.
44440×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
44540×
        fs::create_dir_all(root)?;
44640×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
44740×
        let oxy = root.join(OXY_DIR);
44840×
        if oxy.exists() {
4490×
            return fail(format!("{} is already an oxy repository", root.display()));
45040×
        }
45140×
        fs::create_dir_all(oxy.join("ops"))?;
45240×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
45340×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
45440×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
45540×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
45640×
        if let Some(url) = storage {
4570×
            config.set("storage.url", url)?;
45840×
        }
45940×
        config.save(&oxy.join("config"))?;
46040×
        let store = open_objects(&oxy, &config)?;
46140×
        let repo = Repo {
46240×
            acceptor: None,
46340×
            keyless_key: Default::default(),
46440×
            last_change: Default::default(),
46540×
            at_op: None,
46640×
            walked_dirs: Default::default(),
46740×
            listed_dirs: Default::default(),
46840×
            git_export_skipped: Default::default(),
46940×
            manifest_cache: Default::default(),
47040×
            listing_cache: Default::default(),
47140×
            untracked_nested: Default::default(),
47240×
            skipped_large: Default::default(),
47340×
            root,
47440×
            oxy,
47540×
            store,
47640×
            workspace: WorkspaceId::ZERO,
47740×
            bare: true,
47840×
            keys_dir: default_keys_dir(),
47940×
            platform: crate::portable::Platform::current(),
48040×
            user_config: default_user_config(),
48140×
            config,
48240×
        };
48340×
        let mut view = View::default();
48440×
        view.bookmarks.insert(
48540×
            repo.config.bookmark.clone(),
48640×
            repo.store.put_state(&StateObject::new(vec![]))?,
487
        );
48840×
        repo.record_op(&[], "oxy init --bare", view)?;
48940×
        Ok(repo)
49040×
    }
491
492
    /// A bare repository with no id yet. Its `id()` is all zero until the
493
    /// first push binds it (`bind_id`), so an existing repository can be
494
    /// pushed to a freshly created hosted one and keep its identity.
49514×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
49614×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
49714×
        fs::remove_file(repo.oxy.join("id"))?;
49814×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
49914×
        Ok(repo)
50014×
    }
501
5023534×
    pub fn is_unbound(&self) -> bool {
5033534×
        self.oxy.join(UNBOUND_MARKER).is_file()
5043534×
    }
505
506
    /// Give an unbound repository its id.
50713×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
50813×
        if !self.is_unbound() {
5090×
            return fail("this repository already has an id");
51013×
        }
51113×
        if id == [0; 16] {
5120×
            return fail("a repository id cannot be all zero");
51313×
        }
51413×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
51513×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
51613×
        Ok(())
51713×
    }
518
519
    /// Whether this repository has no working copy (`init_bare`).
52076×
    pub fn is_bare(&self) -> bool {
52176×
        self.bare
52276×
    }
523
524
    /// Open the repository containing `start` (searching upwards).
5251906×
    pub fn open(start: &Path) -> Result<Repo> {
5261906×
        let start = start.canonicalize()?;
5271906×
        let mut dir: Option<&Path> = Some(&start);
5281906×
        while let Some(d) = dir {
5291906×
            let oxy = d.join(OXY_DIR);
5301906×
            if oxy.is_file() {
531
                // A secondary workspace (spec §12.2): the file points at the repository.
5329×
                let text = fs::read_to_string(&oxy)?;
5339×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5340×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
535
                };
5369×
                let format = fs::read_to_string(shared.join("format"))?;
5379×
                if format != FORMAT_LINE {
5380×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5399×
                }
5409×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5419×
                let store = open_objects(&shared, &config)?;
5429×
                let mut repo = Repo {
5439×
                    acceptor: None,
5449×
                    keyless_key: Default::default(),
5459×
                    last_change: Default::default(),
5469×
                    at_op: None,
5479×
                    walked_dirs: Default::default(),
5489×
                    listed_dirs: Default::default(),
5499×
                    git_export_skipped: Default::default(),
5509×
                    manifest_cache: Default::default(),
5519×
                    listing_cache: Default::default(),
5529×
                    untracked_nested: Default::default(),
5539×
                    skipped_large: Default::default(),
5549×
                    root: d.to_path_buf(),
5559×
                    oxy: shared,
5569×
                    store,
5579×
                    workspace,
5589×
                    bare: false,
5599×
                    keys_dir: default_keys_dir(),
5609×
                    platform: crate::portable::Platform::current(),
5619×
                    user_config: default_user_config(),
5629×
                    config,
5639×
                };
5649×
                repo.apply_workspace_bookmark();
5659×
                return Ok(repo);
5661897×
            }
5671897×
            if oxy.is_dir() {
5681897×
                let format = fs::read_to_string(oxy.join("format"))?;
5691897×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5701897×
                let bare = oxy.join(BARE_MARKER).is_file();
5711897×
                let workspace = if bare {
572148×
                    WorkspaceId::ZERO
573
                } else {
5741749×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5751749×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
576
                };
5771897×
                let store = open_objects(&oxy, &config)?;
5781897×
                let mut repo = Repo {
5791897×
                    acceptor: None,
5801897×
                    keyless_key: Default::default(),
5811897×
                    last_change: Default::default(),
5821897×
                    at_op: None,
5831897×
                    walked_dirs: Default::default(),
5841897×
                    listed_dirs: Default::default(),
5851897×
                    git_export_skipped: Default::default(),
5861897×
                    manifest_cache: Default::default(),
5871897×
                    listing_cache: Default::default(),
5881897×
                    untracked_nested: Default::default(),
5891897×
                    skipped_large: Default::default(),
5901897×
                    root: d.to_path_buf(),
5911897×
                    oxy,
5921897×
                    store,
5931897×
                    workspace,
5941897×
                    bare,
5951897×
                    keys_dir: default_keys_dir(),
5961897×
                    platform: crate::portable::Platform::current(),
5971897×
                    user_config: default_user_config(),
5981897×
                    config,
5991897×
                };
6001897×
                if !bare {
6011749×
                    repo.apply_workspace_bookmark();
6021749×
                }
6031897×
                if format == FORMAT1_LINE {
6041×
                    repo.migrate_format1()?;
6051896×
                } else if format != FORMAT_LINE {
6060×
                    return fail(format!("unsupported repository format: {}", format.trim()));
6071896×
                }
6081897×
                return Ok(repo);
6090×
            }
6100×
            dir = d.parent();
611
        }
6120×
        fail(format!(
613
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
6140×
            start.display()
615
        ))
6161906×
    }
617
618
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
619
    /// into format 2, where each bookmark names a `state` object.
6201×
    fn migrate_format1(&self) -> Result<()> {
6211×
        let (head, version) = self.read_head()?;
622
        // Collect the chain root-first.
6231×
        let mut chain: Vec<Format1Op> = Vec::new();
6241×
        let mut cur = Some(head);
6253×
        while let Some(r) = cur {
6262×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
6272×
            cur = op.parents.first().copied();
6282×
            chain.push(op);
629
        }
6301×
        chain.reverse();
6311×
        let mut new_parent: Option<ObjectRef> = None;
6322×
        for old in chain {
6332×
            let mut view = View::default();
6342×
            for (name, heads) in &old.view.bookmarks {
6352×
                view.bookmarks.insert(
6362×
                    name.clone(),
6372×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
638
                );
639
            }
6402×
            view.workspaces = old.view.workspaces.clone();
6412×
            let op = Op {
6422×
                parents: new_parent.into_iter().collect(),
6432×
                hlc: old.hlc,
6442×
                command: old.command,
6452×
                view,
6462×
                workspace: None,
6472×
                undoes: None,
6482×
            };
6492×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
650
        }
6511×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6520×
            return fail("the operation log changed while it was rewritten; run the command again");
6531×
        }
6541×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6551×
        Ok(())
6561×
    }
657
658
    /// Pack automatically once many loose objects have accumulated.
659645×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
660645×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6610×
            self.store.pack_loose()?;
6620×
            self.store.merge_packs()?;
663645×
        }
664645×
        Ok(())
665645×
    }
666
667
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6683247×
    pub fn id(&self) -> Result<[u8; 16]> {
6693247×
        if self.is_unbound() {
67019×
            return Ok([0; 16]);
6713228×
        }
6723228×
        let path = self.oxy.join("id");
6733228×
        match fs::read_to_string(&path) {
6743228×
            Ok(h) => hex::decode(h.trim())
6753228×
                .ok()
6763228×
                .and_then(|v| v.try_into().ok())
6773228×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6780×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6790×
                let mut id = [0u8; 16];
6800×
                rand::rngs::OsRng.fill_bytes(&mut id);
6810×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6820×
                Ok(id)
683
            }
6840×
            Err(e) => Err(e.into()),
685
        }
6863247×
    }
687
68862×
    pub fn root(&self) -> &Path {
68962×
        &self.root
69062×
    }
691509×
    pub fn store(&self) -> &Store {
692509×
        &self.store
693509×
    }
69410×
    pub fn workspace(&self) -> WorkspaceId {
69510×
        self.workspace
69610×
    }
697
698
    /// Use a different user directory for keys and the user config file
699
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
700
    /// Act as if the working copy were on another platform's file system
701
    /// (tests of Windows and macOS behaviour on any host).
702
    /// Accept certified updates as `identity` (a host's key), recording when
703
    /// (spec §14.7).
7041×
    pub fn with_acceptor(mut self, identity: Identity, sk: crate::identity::SecretKey) -> Repo {
7051×
        self.acceptor = Some(std::sync::Arc::new((identity, sk)));
7061×
        self
7071×
    }
708
7092×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
7102×
        self.platform = platform;
7112×
        self
7122×
    }
713
7140×
    pub fn platform(&self) -> crate::portable::Platform {
7150×
        self.platform
7160×
    }
717
718177×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
719177×
        let dir = dir.into();
720177×
        self.keys_dir = dir.join("keys");
721177×
        self.user_config = dir.join("config.toml");
722177×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
723177×
            self.config = c;
724177×
        }
725177×
        self.apply_workspace_bookmark();
726177×
        self
727177×
    }
728
729
    /// The workspace's current bookmark (spec §10.1) overrides the
730
    /// configured default when `oxy bookmark switch` has recorded one.
7311935×
    fn apply_workspace_bookmark(&mut self) {
7321935×
        if let Ok(b) = fs::read_to_string(
7331935×
            self.oxy
7341935×
                .join("workspaces")
7351935×
                .join(self.workspace.to_hex())
7361935×
                .join("bookmark"),
7371935×
        ) {
73835×
            let b = b.trim();
73935×
            if !b.is_empty() {
74035×
                self.config.bookmark = b.to_string();
74135×
            }
7421900×
        }
7431935×
    }
744
7452×
    pub fn user_config_path(&self) -> &Path {
7462×
        &self.user_config
7472×
    }
748
749
    /// Set a key in the user file and refresh the effective configuration.
75022×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
75122×
        Config::set_user(&self.user_config, key, value)?;
75221×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
75321×
        Ok(())
75422×
    }
755
756370×
    pub fn save_config(&self) -> Result<()> {
757370×
        self.config.save(&self.oxy.join("config"))
758370×
    }
759
7604247×
    fn author(&self) -> KeyId {
7614247×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7624247×
    }
763
}
764
765
impl Repo {
7661631×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7671631×
        let mut c = Change {
7681631×
            version: crate::objects::CHANGE_VERSION,
7691631×
            change_id: ChangeId::random(),
7701631×
            deps,
7711631×
            author: self.author(),
7721631×
            hlc: Hlc::now(),
7731631×
            message: message.into(),
7741631×
            tree_ops: vec![],
7751631×
            edits: vec![],
7761631×
            kind: ChangeKind::WorkingCopy,
7771631×
        };
7781631×
        c.normalize();
7791631×
        c
7801631×
    }
781
782
    // ------------------------------------------------------------ operation log
783
78413791×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
78513791×
        if let Some(r) = self.at_op {
7865×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
78713786×
        }
78813786×
        let r = self.head_ref()?;
78913784×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
79013784×
        Ok((r, op))
79113791×
    }
792
7939567×
    pub fn view(&self) -> Result<View> {
7949567×
        Ok(self.head_op()?.1.view)
7959567×
    }
796
7973365×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
7983365×
        self.record_op_undoing(parents, command, view, None)
7993365×
    }
800
801
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
8023368×
    fn record_op_undoing(
8033368×
        &self,
8043368×
        parents: &[ObjectRef],
8053368×
        command: &str,
8063368×
        view: View,
8073368×
        undoes: Option<ObjectRef>,
8083368×
    ) -> Result<ObjectRef> {
8093368×
        if self.at_op.is_some() {
8101×
            return fail(
811
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
812
            );
8133367×
        }
8143367×
        let op = Op {
8153367×
            parents: parents.to_vec(),
8163367×
            hlc: Hlc::now(),
8173367×
            command: command.into(),
8183367×
            view,
8193367×
            workspace: Some(self.workspace),
8203367×
            undoes,
8213367×
        };
8223367×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
823
        // The head is the commit point: everything it names must be on disk first.
8243365×
        let flushing = crate::timing::phase("op: flush the store");
8253365×
        self.store.flush()?;
8263363×
        drop(flushing);
827
        // Compare and swap (spec §12.1): when another process recorded an
828
        // operation since this one read the head, the two are merged
829
        // instead of one overwriting the other. On this disk the head moves
830
        // under a short lock; on any other store by its record's version,
831
        // and a record that moved meanwhile is read again and merged again.
8323363×
        let _lock = if self.store.is_local() {
8333355×
            Some(self.lock_ops()?)
834
        } else {
8358×
            None
836
        };
8373363×
        let Some(parent) = parents.first() else {
838
            // The first operation (init): there is no head yet.
839529×
            if !self.swap_head(&r, None)? {
8402×
                return fail(format!(
841
                    "{} already holds a repository's operation log",
8422×
                    self.store.backend().describe()
843
                ));
844527×
            }
845527×
            return Ok(r);
846
        };
8472834×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8482834×
        for _ in 0..HEAD_TRIES {
8492834×
            let (current, version) = self.read_head()?;
8502834×
            let to = if current == *parent {
8512823×
                r
852
            } else {
85311×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
85410×
                let merged = Op {
85511×
                    parents: vec![current, r],
85611×
                    hlc: Hlc::now(),
85711×
                    command: format!("{command} (merged with a concurrent operation)"),
85811×
                    view: self.merge_views(&base, &op.view, &theirs)?,
85910×
                    workspace: Some(self.workspace),
86010×
                    undoes: None,
861
                };
86210×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
86310×
                self.store.flush()?;
86410×
                m
865
            };
8662833×
            if self.swap_head(&to, version.as_ref())? {
8672827×
                return Ok(to);
8680×
            }
869
        }
8700×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8713368×
    }
872
873
    /// The operation head's lock, held only while the head pointer moves.
8743365×
    fn lock_ops(&self) -> Result<FileLock> {
8753365×
        fs::create_dir_all(self.oxy.join("ops"))?;
8763365×
        FileLock::acquire(
8773365×
            self.oxy.join("ops").join("lock"),
8783365×
            "another oxy process holds the operation log",
879
        )
8803365×
    }
881
88213788×
    fn head_ref(&self) -> Result<ObjectRef> {
88313788×
        Ok(self.read_head()?.0)
88413788×
    }
885
886
    /// The operation head, and on a store its record's version for
887
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
888
    /// any other store (a bucket, or memory in tests) it is the store's
889
    /// [`HEAD_RECORD`] reference record (oxygen#68).
89016711×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
89116711×
        if self.store.is_local() {
89216692×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
89316692×
            let r = ObjectRef::from_hex(hex.trim())
89416692×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
89516689×
            return Ok((r, None));
89619×
        }
89719×
        let backend = self.store.backend();
89819×
        match backend.read_ref(HEAD_RECORD) {
89919×
            Ok(Some((bytes, version))) => {
90019×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
9010×
                    || {
9020×
                        RepoError::Msg(format!(
9030×
                            "the operation head in {} is corrupt",
9040×
                            backend.describe()
9050×
                        ))
9060×
                    },
9070×
                )?;
90819×
                Ok((r, Some(version)))
909
            }
9100×
            Ok(None) => fail(format!(
911
                "{} holds no operation log (no {HEAD_RECORD} record)",
9120×
                backend.describe()
913
            )),
9140×
            Err(e) => fail(format!("read the operation head: {e}")),
915
        }
91616711×
    }
917
918
    /// Move the operation head to `to` from the `expected` version
919
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
920
    /// disk the caller holds the operations lock and the head always
921
    /// moves; on a store it moves only if the record is unchanged, and
922
    /// `false` says another process moved it first.
9233375×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
9243375×
        if self.store.is_local() {
9253365×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
9263359×
            return Ok(true);
92710×
        }
92810×
        match self
92910×
            .store
93010×
            .backend()
93110×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
932
        {
9337×
            Ok(_) => Ok(true),
9343×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
9350×
            Err(e) => fail(format!("move the operation head: {e}")),
936
        }
9373375×
    }
938
939
    /// Three-way merge of two views that both started from `base` (spec
940
    /// §12.1). A reference only one side changed takes that side's value.
941
    /// When both changed it differently: a bookmark keeps both sides'
942
    /// heads (it may then have several), a change beats a deletion, a
943
    /// workspace changed by both is an error (only one of them matches the
944
    /// files on disk), and otherwise this process's value wins for remote
945
    /// references and the policy, the first value for a tag (tags never
946
    /// move).
94711×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
94838×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
94938×
            b: &BTreeMap<K, V>,
95038×
            o: &BTreeMap<K, V>,
95138×
            t: &BTreeMap<K, V>,
95238×
            mut both: impl FnMut(&V, &V) -> Result<V>,
95338×
        ) -> Result<BTreeMap<K, V>> {
95438×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
95538×
            let mut out = BTreeMap::new();
95639×
            for k in keys {
95739×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
95839×
                let v = if ov == tv || tv == bv {
95920×
                    ov.cloned()
96019×
                } else if ov == bv {
96111×
                    tv.cloned()
962
                } else {
9638×
                    match (ov, tv) {
9648×
                        (Some(x), Some(y)) => Some(both(x, y)?),
9650×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
9660×
                        (None, None) => None,
967
                    }
968
                };
96938×
                if let Some(v) = v {
97038×
                    out.insert(k.clone(), v);
97138×
                }
972
            }
97337×
            Ok(out)
97438×
        }
97511×
        let bookmarks = pick(
97611×
            &base.bookmarks,
97711×
            &ours.bookmarks,
97811×
            &theirs.bookmarks,
9797×
            |x, y| {
9807×
                let mut heads = self.store.get_state(x)?.heads;
9817×
                heads.extend(self.store.get_state(y)?.heads);
9827×
                let heads = self.load_state(&heads)?.maximal(&heads);
9837×
                Ok(self.store.put_state(&StateObject::new(heads))?)
9847×
            },
9850×
        )?;
986
        // Two operations that both replaced one workspace's working copy
987
        // cannot both be right: the files on disk match only one of them.
988
        // The working-copy lock keeps this from happening; should it happen
989
        // anyway, this operation is not recorded.
99011×
        let workspaces = pick(
99111×
            &base.workspaces,
99211×
            &ours.workspaces,
99311×
            &theirs.workspaces,
9941×
            |_, _| {
9951×
                fail(
996
                    "another oxy process changed this working copy at the same time; \
997
                     this command was not recorded: check `oxy status` and run it again",
998
                )
9991×
            },
10001×
        )?;
100110×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
100210×
        let empty = BTreeMap::new();
100310×
        let names: BTreeSet<&String> = base
100410×
            .remotes
100510×
            .keys()
100610×
            .chain(ours.remotes.keys())
100710×
            .chain(theirs.remotes.keys())
100810×
            .collect();
100910×
        let mut remotes = BTreeMap::new();
101010×
        for n in names {
10116×
            let m = pick(
10126×
                base.remotes.get(n).unwrap_or(&empty),
10136×
                ours.remotes.get(n).unwrap_or(&empty),
10146×
                theirs.remotes.get(n).unwrap_or(&empty),
10150×
                |x, _| Ok(*x),
10160×
            )?;
10176×
            if !m.is_empty() {
10186×
                remotes.insert(n.clone(), m);
10196×
            }
1020
        }
102110×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
102210×
            ours.policy
10230×
        } else if ours.policy == base.policy {
10240×
            theirs.policy
1025
        } else {
10260×
            ours.policy.or(theirs.policy)
1027
        };
102810×
        self.store.flush()?;
102910×
        Ok(View {
103010×
            bookmarks,
103110×
            workspaces,
103210×
            remotes,
103310×
            policy,
103410×
            tags,
103510×
        })
103611×
    }
1037
103848×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
103948×
        let mut out = Vec::new();
104048×
        let (mut r, mut op) = self.head_op()?;
1041
        loop {
1042261×
            let next = op.parents.first().copied();
1043261×
            out.push((r, op));
1044261×
            match next {
1045213×
                Some(p) => {
1046213×
                    r = p;
1047213×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1048
                }
104948×
                None => break,
1050
            }
1051
        }
105248×
        Ok(out)
105348×
    }
1054
1055
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1056
    ///
1057
    /// The command undone is the newest one this workspace ran: operations
1058
    /// that only recorded a working-copy snapshot are skipped (the files are
1059
    /// still on disk and the next snapshot recreates them), as are pushes
1060
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1061
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1062
    /// operations are never undone, and a command an earlier undo already
1063
    /// reverted is passed over, so undoing again goes further back.
1064
    ///
1065
    /// When nothing newer came from another workspace, the operation head
1066
    /// moves back to before the command. Otherwise the command is reverted
1067
    /// in place: every reference it changed goes back to its value before
1068
    /// it, recorded as a new operation that names it, and anything another
1069
    /// workspace changed since is kept. A reference both the command and a
1070
    /// later operation of another workspace changed is not guessed at: the
1071
    /// undo is refused, naming it.
1072
    ///
1073
    /// When the working copy is clean and was clean after the command's
1074
    /// predecessor, its files follow too, since nothing on disk can be
1075
    /// lost; otherwise they stay as they are (an undone commit's edits come
1076
    /// back as uncommitted work).
107716×
    pub fn undo(&self) -> Result<Undone> {
107816×
        let _wc = self.lock_working_copy()?;
107916×
        let clean_now =
108016×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
108116×
        let (head_ref, head) = self.head_op()?;
108216×
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
108340×
        let load = |r: &ObjectRef| -> Result<Op> {
108440×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
108540×
        };
108616×
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
108716×
        let mut pending_checkout: Option<Op> = None;
108816×
        let mut others = 0usize;
108916×
        let (mut r, mut op) = (head_ref, head.clone());
109015×
        let (target_ref, target, parent) = loop {
109141×
            let parent = match op.parents.first() {
109240×
                Some(p) => Some((*p, load(p)?)),
10931×
                None => None,
1094
            };
109541×
            if skip.contains(&r) {
10961×
                pending_checkout = None;
109740×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
109810×
                // A push cannot be taken back: undoing it would only make
109910×
                // this repository forget what the remote holds.
110030×
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
110110×
                others += 1;
110220×
            } else if let Some(u) = op.undoes {
11031×
                skip.insert(u);
11041×
                pending_checkout = None;
110519×
            } else if op.command.ends_with(" (checkout)") {
11063×
                pending_checkout = Some(op.clone());
11073×
            } else {
110816×
                match parent {
110915×
                    Some((_, p)) => break (r, op, p),
11101×
                    None => return fail("nothing to undo in this workspace"),
1111
                }
1112
            }
111325×
            match parent {
111425×
                Some((pr, p)) => (r, op) = (pr, p),
11150×
                None => return fail("nothing to undo in this workspace"),
1116
            }
1117
        };
111815×
        let before = parent.view;
111915×
        let after = pending_checkout
112015×
            .map(|o| o.view)
112115×
            .unwrap_or_else(|| target.view.clone());
112215×
        let changes = self.view_changes(&before, &after)?;
112315×
        let pushed = self.pushed_by(&before, &after, &head.view)?;
112415×
        let restored_wc = before.workspaces.get(&self.workspace).copied();
112515×
        if others == 0 {
1126
            // Only this workspace's operations since: move the head back.
112710×
            let _lock = if self.store.is_local() {
112810×
                Some(self.lock_ops()?)
1129
            } else {
11300×
                None
1131
            };
113210×
            let parent_ref = *target.parents.first().expect("the target has a parent");
113310×
            let (now, version) = self.read_head()?;
113410×
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
11350×
                return fail("another oxy command ran while undoing; run undo again");
113610×
            }
1137
        } else {
11385×
            let view = self.revert_view(&head.view, &before, &after)?;
11393×
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1140
        }
114113×
        self.drop_manifest();
114213×
        if let Some(then) = restored_wc {
114313×
            if clean_now && Some(then) != wc_now {
1144
                // Past `core.snapshot-retention` the working copy may be
1145
                // gone: the files then stay as they are.
114610×
                let Ok(wc) = self.store.get_change(&then) else {
11470×
                    return Ok(Undone {
11480×
                        command: target.command,
11490×
                        changes,
11500×
                        others_kept: others,
11510×
                        pushed,
11520×
                    });
1153
                };
115410×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
11558×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1156
                    // The files differ from the restored working copy by
1157
                    // exactly what the undone command did: nothing else is
1158
                    // on disk, as the working copy was clean.
11598×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
11602×
                }
11613×
            }
11620×
        }
116313×
        Ok(Undone {
116413×
            command: target.command,
116513×
            changes,
116613×
            others_kept: others,
116713×
            pushed,
116813×
        })
116916×
    }
1170
1171
    /// Whether operation `op` was a push: it changed only what this
1172
    /// repository knows of remotes.
117331×
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
117431×
        let Some(p) = parent else {
11751×
            return false;
1176
        };
117730×
        op.command.starts_with("oxy push")
11781×
            && op.view.bookmarks == p.view.bookmarks
11791×
            && op.view.tags == p.view.tags
11801×
            && op.view.workspaces == p.view.workspaces
11811×
            && op.view.policy == p.view.policy
118231×
    }
1183
1184
    /// Whether operation `op` (whose predecessor is `parent`) was this
1185
    /// workspace's. Operations record their workspace (oxygen#99); for older
1186
    /// ones it is read from the view: one that changed only other
1187
    /// workspaces' working copies was theirs, anything else counts as ours.
118830×
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
118930×
        if let Some(w) = op.workspace {
119030×
            return w == self.workspace;
11910×
        }
11920×
        let Some(p) = parent else {
11930×
            return true;
1194
        };
11950×
        let ids: BTreeSet<&WorkspaceId> = op
11960×
            .view
11970×
            .workspaces
11980×
            .keys()
11990×
            .chain(p.view.workspaces.keys())
12000×
            .collect();
12010×
        let moved: Vec<&WorkspaceId> = ids
12020×
            .into_iter()
12030×
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
12040×
            .collect();
12050×
        moved.is_empty() || moved.contains(&&self.workspace)
120630×
    }
1207
1208
    /// `current` with what changed from `before` to `after` put back, this
1209
    /// workspace's working copy included; refused when a later operation
1210
    /// changed one of the same references again.
12115×
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
121210×
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
121310×
            cur: &mut BTreeMap<K, V>,
121410×
            before: &BTreeMap<K, V>,
121510×
            after: &BTreeMap<K, V>,
121610×
            name: impl Fn(&K) -> String,
121710×
            clashes: &mut Vec<String>,
121810×
        ) {
121910×
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
122010×
            for k in keys {
12215×
                let (b, a) = (before.get(k), after.get(k));
12225×
                if a == b {
12234×
                    continue;
12241×
                }
12251×
                if cur.get(k) != a {
12261×
                    clashes.push(name(k));
12271×
                    continue;
12280×
                }
12290×
                match b {
12300×
                    Some(v) => cur.insert(k.clone(), v.clone()),
12310×
                    None => cur.remove(k),
1232
                };
1233
            }
123410×
        }
12355×
        let mut out = current.clone();
12365×
        let mut clashes = Vec::new();
1237
        // A bookmark another workspace moved since is put back head by
1238
        // head: the heads the command added go, the heads it replaced
1239
        // return, and the other workspace's heads stay. Only when a later
1240
        // change was built on one the command added is that not possible.
12415×
        let names: BTreeSet<&String> = before
12425×
            .bookmarks
12435×
            .keys()
12445×
            .chain(after.bookmarks.keys())
12455×
            .collect();
12468×
        for name in names {
12478×
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
12488×
            let cur = current.bookmarks.get(name);
12498×
            if a == b {
12504×
                continue;
12514×
            }
12524×
            if cur == a {
12532×
                match b {
12542×
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
12550×
                    None => out.bookmarks.remove(name),
1256
                };
12572×
                continue;
12582×
            }
12592×
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
12600×
                clashes.push(format!("bookmark {name}"));
12610×
                continue;
1262
            };
12632×
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
12642×
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
12652×
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
12662×
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
12672×
            if !added.iter().all(|h| now.contains(h)) {
12681×
                clashes.push(format!(
1269
                    "bookmark {name} (a later change builds on this one)"
1270
                ));
12711×
                continue;
12721×
            }
12731×
            let mut heads: Vec<ChangeHash> = now
12741×
                .iter()
12753×
                .filter(|h| !added.contains(h))
12761×
                .chain(was.difference(&became))
12771×
                .copied()
12781×
                .collect();
12791×
            heads.sort();
12801×
            heads.dedup();
12811×
            let heads = self.load_state(&heads)?.maximal(&heads);
12821×
            out.bookmarks.insert(
12831×
                name.clone(),
12841×
                self.store.put_state(&StateObject::new(heads))?,
1285
            );
1286
        }
1287
12885×
        back(
12895×
            &mut out.tags,
12905×
            &before.tags,
12915×
            &after.tags,
12920×
            |k| format!("tag {k}"),
12935×
            &mut clashes,
1294
        );
12955×
        let mine = self.workspace;
129615×
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
129715×
            v.workspaces
129815×
                .iter()
129929×
                .filter(|(k, _)| **k != mine)
130015×
                .map(|(k, v)| (*k, *v))
130115×
                .collect()
130215×
        };
13035×
        let mut theirs = others(&out);
13045×
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
13051×
            Some(p) => format!("the workspace at {}", p.display()),
13060×
            None => format!("workspace {}", id.to_hex()),
13071×
        };
13085×
        back(
13095×
            &mut theirs,
13105×
            &others(before),
13115×
            &others(after),
13125×
            workspace_name,
13135×
            &mut clashes,
1314
        );
13155×
        let empty = BTreeMap::new();
13165×
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
13175×
        for n in names {
13180×
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
13190×
            back(
13200×
                &mut cur,
13210×
                before.remotes.get(n).unwrap_or(&empty),
13220×
                after.remotes.get(n).unwrap_or(&empty),
13230×
                |k| format!("{n}/{k}"),
13240×
                &mut clashes,
1325
            );
13260×
            if cur.is_empty() {
13270×
                out.remotes.remove(n);
13280×
            } else {
13290×
                out.remotes.insert(n.clone(), cur);
13300×
            }
1331
        }
13325×
        if before.policy != after.policy {
13330×
            if out.policy == after.policy {
13340×
                out.policy = before.policy;
13350×
            } else {
13360×
                clashes.push("the policy".into());
13370×
            }
13385×
        }
13395×
        if !clashes.is_empty() {
13402×
            return fail(format!(
1341
                "undo would also take back what another workspace has done since to {}; \
1342
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
13432×
                clashes.join(", ")
1344
            ));
13453×
        }
13463×
        out.workspaces = theirs;
13473×
        match before.workspaces.get(&mine) {
13483×
            Some(wc) => out.workspaces.insert(mine, *wc),
13490×
            None => out.workspaces.remove(&mine),
1350
        };
13513×
        Ok(out)
13525×
    }
1353
1354
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1355
    /// in `now` already holds: undoing them locally leaves them there.
135615×
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
135715×
        let mut out = Vec::new();
135818×
        for (name, st) in &after.bookmarks {
135918×
            if before.bookmarks.get(name) == Some(st) {
13604×
                continue;
136114×
            }
136214×
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
136314×
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
13640×
                None => BTreeSet::new(),
1365
            };
136614×
            let added: Vec<ChangeHash> = self
136714×
                .store
136814×
                .get_state(st)?
1369
                .heads
137014×
                .into_iter()
137120×
                .filter(|h| !had.contains(h))
137214×
                .collect();
137314×
            if added.is_empty() {
13741×
                continue;
137513×
            }
137613×
            for (remote, bookmarks) in &now.remotes {
13771×
                if let Some(rs) = bookmarks.get(name) {
13781×
                    let theirs = self.store.get_state(rs)?.heads;
13791×
                    if added.iter().any(|h| theirs.contains(h)) {
13801×
                        out.push((name.clone(), remote.clone()));
13811×
                    }
13820×
                }
1383
            }
1384
        }
138515×
        Ok(out)
138615×
    }
1387
1388
    /// The last operation that was not a snapshot.
13892×
    pub fn last_command(&self) -> Result<Op> {
13902×
        let (_, mut op) = self.head_op()?;
13914×
        while op.is_snapshot() {
13922×
            let Some(parent) = op.parents.first() else {
13930×
                break;
1394
            };
13952×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1396
        }
13972×
        Ok(op)
13982×
    }
1399
1400
    // ------------------------------------------------------------ states
1401
1402
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1403203×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1404203×
        if let Some(st) = self.load_state_checkpointed(heads)? {
14054×
            return Ok(st);
1406198×
        }
1407198×
        self.load_state_full(heads)
1408203×
    }
1409
1410
    /// The state of `heads` for its history (changes, tree, metadata) with
1411
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1412
    /// and friends. Build the graphs a command needs with
1413
    /// [`Repo::load_graphs_of`].
14141713×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
14151713×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
141631×
            return Ok(st);
14171682×
        }
14181682×
        self.load_state_replayed(heads, State::new_history_only())
14191713×
    }
1420
1421
    /// Build these file graphs in a history-only state.
14221793×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
14231793×
        state
14241793×
            .load_graphs(
14251793×
                nodes,
142654×
                |refs| {
142754×
                    self.read_blobs(refs).map_err(|e| {
14283×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14293×
                    })
143054×
                },
14312035×
                |h| self.change_bytes(h),
1432
            )
14331793×
            .map_err(|e| self.index_damage(e))
14341793×
    }
1435
1436
    /// An error building graphs, and when it is a state index found
1437
    /// damaged (a file's history that does not match its hash), the
1438
    /// workspace's state indexes removed: they are rebuilt from history by
1439
    /// the next command.
14404×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
14414×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
14423×
            return e.into();
1443
        };
14442×
        for path in self.state_indexes() {
14452×
            let _ = fs::remove_file(path);
14462×
        }
14471×
        RepoError::Msg(format!(
14481×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
14491×
        ))
14504×
    }
1451
1452
    /// The graphs of `nodes` of a history-only state, built beside it (see
1453
    /// [`State::build_graphs_detached`]).
145477×
    pub fn build_graphs_detached(
145577×
        &self,
145677×
        state: &State,
145777×
        nodes: &[crate::ids::NodeId],
145877×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
145977×
        Ok(state
146077×
            .build_graphs_detached(
146177×
                nodes,
14620×
                |refs| {
14630×
                    self.read_blobs(refs).map_err(|e| {
14640×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14650×
                    })
14660×
                },
146783×
                |h| self.change_bytes(h),
1468
            )
146977×
            .map_err(|e| self.index_damage(e))?
147077×
            .into_iter()
147177×
            .collect())
147277×
    }
1473
1474
    /// The contents of texts [`State::single_text`] gave: blobs read in
1475
    /// one go, inline ones from their changes.
1476353×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1477
        use crate::objects::TextRef;
1478353×
        let refs: Vec<ObjectRef> = texts
1479353×
            .iter()
14805541×
            .filter_map(|t| match t {
14811×
                TextRef::Blob(r, _, _) => Some(*r),
14825540×
                TextRef::Inline { .. } => None,
14835541×
            })
1484353×
            .collect();
1485353×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1486353×
        let mut out = Vec::with_capacity(texts.len());
14875541×
        for t in texts {
14885541×
            let lines = match t {
14891×
                TextRef::Blob(_, count, form) => {
14901×
                    let content = blobs
14911×
                        .next()
14921×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
14931×
                    crate::objects::text_lines(&content, *count, *form)?
1494
                }
14955540×
                TextRef::Inline { change, start, end } => {
14965540×
                    let bytes = self.change_bytes(change)?;
14975540×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
14980×
                        RepoError::Msg("an inline insert lies outside its change".into())
14990×
                    })?;
15005540×
                    crate::objects::inline_lines(range)?
1501
                }
1502
            };
15035541×
            out.push(lines.bytes().to_vec());
1504
        }
1505353×
        Ok(out)
1506353×
    }
1507
1508
    /// Build every graph a history-only state still lacks, making it full.
15091827×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
15101827×
        state
15111827×
            .load_all_graphs(
151216×
                |refs| {
151316×
                    self.read_blobs(refs).map_err(|e| {
15140×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15150×
                    })
151616×
                },
15173822×
                |h| self.change_bytes(h),
1518
            )
15191827×
            .map_err(|e| self.index_damage(e))
15201827×
    }
1521
1522
    /// A change's encoding, for building graphs of its inline inserts. The
1523
    /// last few read are kept: a checkout building graphs a batch at a
1524
    /// time reads the same large changes for every batch, often in turn.
152511480×
    fn change_bytes(
152611480×
        &self,
152711480×
        h: &ChangeHash,
152811480×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
152911480×
        let mut cache = self.last_change.borrow_mut();
153019730×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
15318980×
            let hit = cache.remove(i);
15328980×
            let b = hit.1.clone();
15338980×
            cache.push(hit);
15348980×
            return Ok(b);
15352500×
        }
15362500×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
15370×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
15380×
        })?);
15392500×
        cache.push((*h, b.clone()));
1540
        // The last few, within a memory budget; the newest always stays.
15414025×
        while cache.len() > CHANGE_CACHE_COUNT
15422500×
            || (cache.len() > 1
15437488×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15441525×
        {
15451525×
            cache.remove(0);
15461525×
        }
15472500×
        Ok(b)
154811480×
    }
1549
1550
    /// Load the dependency closure of `heads` change by change.
1551252×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1552252×
        self.load_state_replayed(heads, State::new())
1553252×
    }
1554
15553263×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
15563263×
        let history = state.is_history_only();
15573263×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
15583263×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1559
        {
15603263×
            let _t = crate::timing::phase("load: read and add changes");
15613263×
            let (mut read, mut add, mut fetch) = (
15623263×
                std::time::Duration::ZERO,
15633263×
                std::time::Duration::ZERO,
15643263×
                std::time::Duration::ZERO,
15653263×
            );
156613045×
            while let Some(h) = stack.pop() {
1567
                // A change the state holds brings its history with it.
15689785×
                if !seen.insert(h) || state.contains(&h) {
15692318×
                    continue;
15707467×
                }
15717467×
                let t0 = std::time::Instant::now();
1572
                // A history-only state reads text only for the graphs it
1573
                // builds; either way the hash is the one asked for.
15747467×
                let (c, texts) = if history {
15756166×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
15766165×
                    fetch += t0.elapsed();
15776165×
                    Change::decode_skeleton(&bytes, h)
15786165×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1579
                } else {
15801301×
                    (self.store.get_change(&h)?, Vec::new())
1581
                };
15827464×
                read += t0.elapsed();
15837464×
                stack.extend(c.deps.iter().copied());
15847464×
                let t1 = std::time::Instant::now();
15857464×
                state.add_known(h, c, texts);
15867464×
                add += t1.elapsed();
1587
            }
15883260×
            crate::timing::record("load:   of which reading", read);
15893260×
            crate::timing::record("load:     of which fetching", fetch);
15903260×
            crate::timing::record("load:   of which applying", add);
1591
        }
15923260×
        let _t = crate::timing::phase("load: validate");
15933260×
        state.validate()?;
15943260×
        Ok(state)
15953263×
    }
1596
15972319×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
15982319×
        if self.bare {
15992×
            return fail("this is a bare repository: it has no working copy");
16002317×
        }
16012317×
        let view = self.view()?;
16022317×
        let h = *view
16032317×
            .workspaces
16042317×
            .get(&self.workspace)
16052317×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
16062316×
        Ok((h, self.store.get_change(&h)?))
16072319×
    }
1608
1609
    /// Heads of a bookmark's state (spec §10.1).
16101767×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
16111767×
        match view.bookmarks.get(bookmark) {
16121767×
            Some(st) => Ok(self.store.get_state(st)?.heads),
16130×
            None => Ok(vec![]),
1614
        }
16151767×
    }
1616
1617508×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1618508×
        self.heads_of(&self.view()?, &self.config.bookmark)
1619508×
    }
1620
1621
    // ------------------------------------------------------------ blobs
1622
1623399×
    fn blob_for(content: &[u8]) -> Blob {
1624399×
        Blob::of(content)
1625399×
    }
1626
1627246×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1628246×
        Self::blob_for(content).hash()
1629246×
    }
1630
1631151×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1632194×
        for c in crate::chunk::chunks(content) {
1633194×
            self.store.put_chunk(c)?;
1634
        }
1635151×
        Ok(self
1636151×
            .store
1637151×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1638151×
    }
1639
1640
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1641
    /// all their chunks, are read in parallel; a blob the store lacks goes
1642
    /// through [`Repo::read_blob`], which may fetch it lazily.
1643427×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1644427×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1645427×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
164680×
            blobs.push(match got {
164775×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
16480×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
16495×
                Err(crate::store::StoreError::NotFound(_)) => None,
16500×
                Err(e) => return Err(e.into()),
1651
            });
1652
        }
1653427×
        let chunk_refs: Vec<ObjectRef> = blobs
1654427×
            .iter()
1655427×
            .flatten()
1656427×
            .flat_map(|b| b.chunks.iter().copied())
1657427×
            .collect();
1658427×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1659427×
        let mut out = Vec::with_capacity(refs.len());
1660427×
        for (r, blob) in refs.iter().zip(blobs) {
166180×
            match blob {
16625×
                None => out.push(self.read_blob(r)?),
166375×
                Some(b) => {
166475×
                    let mut content = Vec::with_capacity(b.length as usize);
1665114×
                    for c in &b.chunks {
1666114×
                        match chunks.next() {
1667114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
16680×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
16690×
                            Some(Err(e)) => return Err(e.into()),
16700×
                            None => return fail("chunk list ended early"),
1671
                        }
1672
                    }
167375×
                    out.push(content);
1674
                }
1675
            }
1676
        }
1677422×
        Ok(out)
1678427×
    }
1679
1680
    /// Read a blob's content, fetching it from the remote that withheld it
1681
    /// when it is lazily absent (spec §13.5).
1682113×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1683113×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
16844×
            self.fetch_lazy_blob(r)?;
1685109×
        }
1686113×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1687108×
        let mut out = Vec::with_capacity(blob.length as usize);
1688135×
        for c in &blob.chunks {
1689135×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1690
        }
1691108×
        Ok(out)
1692113×
    }
1693
1694
    // ------------------------------------------------------------ working copy
1695
1696
    /// Attributes from the `.oxyattributes` files in the working directory.
16972×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1698
        // Nested repositories and ignored paths are left out, as in a walk.
16998×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
17002×
        let files: Vec<(String, Vec<u8>)> = listing
17012×
            .files
17022×
            .into_iter()
17032×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
17042×
            .collect();
17052×
        crate::attributes::Attributes::from_files(
17062×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1707
        )
17082×
    }
1709
1710
    /// Folders holding a repository of their own that the last look at the
1711
    /// working copy left out, not being subrepos (oxygen#43).
171229×
    pub fn untracked_nested(&self) -> Vec<String> {
171329×
        self.untracked_nested.borrow().clone()
171429×
    }
1715
1716
    /// New untracked files the last snapshot left out for being larger than
1717
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
171833×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
171933×
        self.skipped_large.borrow().clone()
172033×
    }
1721
1722
    /// Attributes from a materialized state's `.oxyattributes` files.
17233×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
17246×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
17256×
            match &f.content {
17266×
                FileContent::Text { bytes, .. }
17276×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1728
                {
17290×
                    Some((p.as_str(), bytes.as_slice()))
1730
                }
17316×
                _ => None,
1732
            }
17336×
        }))
17343×
    }
1735
1736
    /// Store a blob, raw when the path is `nocompress`.
1737132×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1738132×
        if !nocompress {
1739130×
            return self.store_blob(content);
17402×
        }
17412×
        for c in crate::chunk::chunks(content) {
17422×
            self.store.put_chunk_nocompress(c)?;
1743
        }
17442×
        Ok(self
17452×
            .store
17462×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1747132×
    }
1748
1749
    /// This workspace's state index (oxygen#41): its working copy's base,
1750
    /// saved so a snapshot reads it rather than replaying history.
1751
    /// The state index of the state with these heads: this workspace keeps
1752
    /// the last few it used, named by their heads, so moving between two
1753
    /// states finds both.
17542406×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
17552406×
        let mut heads = heads.to_vec();
17562406×
        heads.sort();
17572406×
        let mut h = blake3::Hasher::new();
17582406×
        for c in &heads {
17592337×
            h.update(&c.0);
17602337×
        }
17612406×
        self.oxy.join("index").join(format!(
17622406×
            "{}{}",
17632406×
            self.state_index_prefix(),
17642406×
            &h.finalize().to_hex()[..16]
17652406×
        ))
17662406×
    }
1767
17684717×
    fn state_index_prefix(&self) -> String {
17694717×
        format!("state-{}-", self.workspace.to_hex())
17704717×
    }
1771
1772
    /// This workspace's state indexes, newest first.
17732311×
    fn state_indexes(&self) -> Vec<PathBuf> {
17742311×
        let prefix = self.state_index_prefix();
17752311×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
17762311×
            .into_iter()
17772311×
            .flatten()
17782311×
            .flatten()
17792311×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
17802311×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
17812311×
            .collect();
17822311×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
17832311×
        found.into_iter().map(|(_, p)| p).collect()
17842311×
    }
1785
1786
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1787
    /// from this workspace's state index when it holds that history: every
1788
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1789
    /// is loaded from history and indexed for next time.
17902001×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
17912001×
        if let Some((st, heads)) = self.read_state_index(deps) {
17921603×
            let mut have = st.maximal(deps);
17931603×
            have.sort();
17941603×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1795
                // Re-encoding reads every history: one found damaged is
1796
                // left to the build that reads it, which reports it.
1797
                #[cfg(test)]
1798161×
                if let Some(mine) = st.write_index() {
1799159×
                    assert_eq!(
1800159×
                        Some(mine),
1801159×
                        self.load_state_history(deps)?.write_index(),
1802
                        "a state index holds the state history gives"
1803
                    );
18042×
                }
1805274×
                return Ok(st);
18061329×
            }
1807
            // An index a few changes behind (a commit, a pull since): add
1808
            // what it lacks, as long as all it holds is history of `deps`.
1809
            // Anything amiss (a change beyond a shallow boundary) takes the
1810
            // long way instead.
18111329×
            let (indexed, started) = (st.len(), std::time::Instant::now());
18121329×
            if let Ok(st) = self.load_state_replayed(deps, st) {
18131328×
                let mut all = deps.to_vec();
18141328×
                all.extend(heads.iter().copied());
18151328×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
18161328×
                within.sort();
18171328×
                want.sort();
18181328×
                if within == want {
1819
                    #[cfg(test)]
1820705×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1821
                    // Writing the index costs far more than replaying a
1822
                    // few small changes: it is rewritten once it falls
1823
                    // behind, or when replaying took long (large changes).
18241326×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
18251326×
                        || started.elapsed() > INDEX_REPLAY_TIME
18263×
                    {
18273×
                        self.write_state_index(deps, &st);
18281323×
                    }
18291326×
                    return Ok(st);
18302×
                }
18311×
            }
1832398×
        }
1833401×
        let st = self.load_state_history(deps)?;
1834401×
        self.write_state_index(deps, &st);
1835401×
        Ok(st)
18362001×
    }
1837
1838
    /// Two history-only states hold the same changes and render the same
1839
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1840
    /// the checkpoint's graphs as the bases of its files' histories.
1841
    #[cfg(test)]
1842705×
    fn assert_same_state(&self, a: &State, b: &State) {
18431410×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1844705×
        assert_eq!(ids(a), ids(b), "the same changes");
18451410×
        let files = |s: &State| {
18461410×
            let mut s = s.clone();
18471410×
            self.load_all_graphs(&mut s).unwrap();
18481410×
            s.materialize().files
18491410×
        };
1850705×
        assert_eq!(files(a), files(b), "the same files");
1851705×
    }
1852
1853
    /// The state index file: its heads, a hash of its changes block and one
1854
    /// of the rest, then the body [`State::write_index`] gives, whose first
1855
    /// block is the changes. Hashed in two parts so the log can read and
1856
    /// check the changes alone.
1857
    /// The index of `deps` if there is one, else the newest, which the
1858
    /// caller may bring up to date.
18592001×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1860
        use std::io::Read;
18612001×
        let _t = crate::timing::phase("load: state index");
18622001×
        let exact = self.state_index_path(deps);
18632001×
        let reading = crate::timing::phase("load:   of which reading the file");
18642001×
        let mut f = match fs::File::open(&exact) {
1865274×
            Ok(f) => {
1866
                // Used now: the newest, so the last to be dropped.
1867274×
                let _ = fs::File::options()
1868274×
                    .write(true)
1869274×
                    .open(&exact)
1870274×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1871274×
                f
1872
            }
18731727×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1874
        };
18751603×
        let total = f.metadata().ok()?.len();
18761603×
        let mut word = [0u8; 4];
18771603×
        f.read_exact(&mut word).ok()?;
18781603×
        let n = u32::from_le_bytes(word) as usize;
18791603×
        let mut head = vec![0u8; 32 * n + 64 + 8];
18801603×
        f.read_exact(&mut head).ok()?;
18811603×
        let heads: Vec<ChangeHash> = head[..32 * n]
18821603×
            .chunks_exact(32)
18831603×
            .map(|c| ObjectRef(c.try_into().unwrap()))
18841603×
            .collect();
18851603×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
18861603×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
18871603×
        let at = (4 + head.len()) as u64;
18881603×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
18890×
            return None;
18901603×
        }
1891
        // The front only: the files' histories after it are read, each
1892
        // checked by its own hash, when a command builds that file.
18931603×
        let mut front = vec![0u8; front_len as usize];
18941603×
        f.read_exact(&mut front).ok()?;
18951603×
        drop(reading);
18961603×
        let checking = crate::timing::phase("load:   of which checking the file");
18971603×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
18981603×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
18993206×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
19001603×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
19010×
            return None;
19021603×
        }
19031603×
        drop(checking);
19041603×
        let histories = crate::state::Histories::File(
19051603×
            std::sync::Arc::new(f),
19061603×
            at + front_len,
19071603×
            total - at - front_len,
19081603×
        );
19091603×
        Some((State::read_index_front(&front, histories).ok()?, heads))
19102001×
    }
1911
1912
    /// The changes of this workspace's state index (the closure of its
1913
    /// heads), read without the rest of the index.
1914
    #[allow(clippy::type_complexity)]
1915177×
    pub(crate) fn read_state_index_changes(
1916177×
        &self,
1917177×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1918
        use std::io::Read;
1919177×
        let _t = crate::timing::phase("load: state index changes");
1920177×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1921160×
        let mut word = [0u8; 4];
1922160×
        f.read_exact(&mut word).ok()?;
1923160×
        let n = u32::from_le_bytes(word) as usize;
1924
        // Heads, the two sums, the front's length, then the changes block.
1925160×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1926160×
        f.read_exact(&mut head).ok()?;
1927160×
        let heads: Vec<ChangeHash> = head[..32 * n]
1928160×
            .chunks_exact(32)
1929160×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1930160×
            .collect();
1931160×
        let sum = &head[32 * n..32 * n + 32];
1932160×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1933160×
        let mut changes = vec![0u8; 4 + len];
1934160×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1935160×
        f.read_exact(&mut changes[4..]).ok()?;
1936160×
        let checking = crate::timing::phase("load:   of which checking");
1937160×
        let mut h = blake3::Hasher::new();
1938160×
        h.update_rayon(&changes);
1939160×
        if h.finalize().as_bytes() != sum {
19400×
            return None;
1941160×
        }
1942160×
        drop(checking);
1943160×
        let _decoding = crate::timing::phase("load:   of which decoding");
1944160×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
1945177×
    }
1946
1947
    /// Save `st`, the history-only state of `deps`, as this workspace's
1948
    /// state index; quietly nothing when it cannot be (it is only a cache).
1949405×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1950405×
        let _t = crate::timing::phase("write: state index");
1951405×
        let encoding = crate::timing::phase("write:   of which encoding");
1952405×
        let Some(body) = st.write_index() else {
19530×
            return;
1954
        };
1955405×
        drop(encoding);
1956
        #[cfg(test)]
1957221×
        assert_eq!(
1958221×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1959221×
            Some(body.clone()),
1960
            "a state index reads back as written"
1961
        );
1962405×
        let mut heads = st.maximal(deps);
1963405×
        heads.sort();
1964405×
        let mut w = crate::flat::Writer::default();
1965405×
        w.count(heads.len());
1966405×
        for h in &heads {
196717×
            w.object(h);
196817×
        }
1969
        // The body is the front's length, the front, then the files'
1970
        // histories, which carry their own hashes: the sums cover the
1971
        // front's changes block and the rest of the front.
1972405×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
1973405×
        let front = &body[8..8 + front_len];
1974405×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
1975810×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1976405×
        w.fixed(&sum(&front[..split]));
1977405×
        w.fixed(&sum(&front[split..]));
1978405×
        w.fixed(&body);
1979405×
        let path = self.state_index_path(&heads);
1980405×
        let _ = fs::create_dir_all(self.oxy.join("index"));
1981405×
        let _ = write_cache(&path, &w.0);
1982
        // The last two used: the index of a state moved away from stays for
1983
        // a move back. Older ones (and the unnamed one of before) go.
1984405×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
19851×
            let _ = fs::remove_file(old);
19861×
        }
1987405×
        let _ = fs::remove_file(
1988405×
            self.oxy
1989405×
                .join("index")
1990405×
                .join(format!("state-{}", self.workspace.to_hex())),
1991405×
        );
1992405×
    }
1993
19946×
    fn locks_dir(&self) -> PathBuf {
19956×
        self.oxy.join("locks")
19966×
    }
1997
1998
    /// Whether `path` is locked locally for editing (spec §18, advisory).
19993×
    pub fn is_locked(&self, path: &str) -> bool {
20003×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
20013×
    }
2002
2003
    /// Take the advisory local lock on a `lockable` file and make it writable.
20042×
    pub fn lock_path(&self, path: &str) -> Result<()> {
20052×
        let attrs = self.disk_attributes();
20062×
        if !attrs.lookup(path).lockable {
20071×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
20081×
        }
20091×
        fs::create_dir_all(self.locks_dir())?;
20101×
        write_atomic(
20111×
            &self.locks_dir().join(path.replace('/', "%2F")),
20121×
            std::process::id().to_string().as_bytes(),
20130×
        )?;
20141×
        set_readonly(&self.root.join(path), false)?;
20151×
        Ok(())
20162×
    }
2017
2018
    /// Release the local lock and make the file read-only again.
20191×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
20201×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
20211×
        if self.root.join(path).exists() {
20221×
            set_readonly(&self.root.join(path), true)?;
20230×
        }
20241×
        Ok(())
20251×
    }
2026
2027
    /// Whether a repository path is inside the sparse filter (spec §17).
202824277×
    pub fn in_scope(&self, path: &str) -> bool {
202924277×
        self.config.sparse_paths.is_empty()
203082×
            || self
203182×
                .config
203282×
                .sparse_paths
203382×
                .iter()
203499×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
203524277×
    }
2036
20371×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
20381×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
20391×
    }
2040
2041
    /// Walk the working copy; with a manifest, a file whose size and mtime
2042
    /// match it is not read: an opaque file yields its known blob, and a
2043
    /// text file whose recorded graph key equals its base graph's key in
2044
    /// `keys` (path → key) is marked unchanged; other text files are read
2045
    /// but keep their known hash. Files modified within two seconds of the
2046
    /// manifest are never trusted (a racy stat).
2047
    ///
2048
    /// `.oxyattributes` files are always read, since their content is
2049
    /// needed; and when any of them is not known unchanged (added, removed,
2050
    /// edited, or changed in the base), no text file is taken as unchanged,
2051
    /// because attributes decide how a file compares with the base.
2052
    ///
2053
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2054
    /// (the base state's files) that exists on disk is included even when
2055
    /// an ignore rule matches it, as in Git.
20561283×
    fn walk_working_copy_with(
20571283×
        &self,
20581283×
        cache: Option<&prompt::Manifest>,
20591283×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
20601283×
        keys: Option<&KeyOf>,
20611283×
    ) -> Result<BTreeMap<String, FsEntry>> {
2062
        let mut out: BTreeMap<String, FsEntry>;
20631283×
        let sparse = &self.config.sparse_paths;
20649080×
        let in_scope = |p: &str| {
20659080×
            sparse.is_empty()
20667×
                || sparse
20677×
                    .iter()
20687×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
20699080×
        };
20701283×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2071
        let walk::Listing {
20721283×
            files,
20731283×
            symlinks,
20741283×
            nested,
20751283×
            dirs,
20761283×
        } = match self.listing_cache.take() {
2077176×
            Some(l) => l,
2078
            // Ignore rules apply to untracked paths only, so the base's
2079
            // files are not matched against them (an added file is: a rule
2080
            // written after it was snapshotted leaves it out again).
20819092×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2082
        };
2083
        // A new file larger than the limit is left out and named, not taken
2084
        // in unseen (oxygen#98): a build's output or a downloaded image
2085
        // would otherwise be stored by the next status, kept by the
2086
        // operation log. Files tracked, or already in the working copy, stay.
20871283×
        let limit = self.config.max_new_file;
20881283×
        let mut skipped = Vec::new();
20891283×
        let files: Vec<_> = files
20901283×
            .into_iter()
209112065×
            .filter(|(rel, _, meta)| {
209212065×
                let new = !tracked.contains_key(rel)
20933116×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
209412065×
                if limit > 0 && new && meta.size > limit {
20953×
                    skipped.push((rel.clone(), meta.size));
20963×
                    return false;
209712062×
                }
209812062×
                true
209912065×
            })
21001283×
            .collect();
21011283×
        *self.skipped_large.borrow_mut() = skipped;
21021283×
        let keys = keys.filter(|k| {
210312050×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
21041280×
            let attrs_unchanged =
21051280×
                files
21061280×
                    .iter()
210712031×
                    .filter(|(r, _, _)| is_attributes(r))
21081280×
                    .all(|(rel, _, meta)| {
21099×
                        stat_cached(rel, meta, cache)
21109×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
21119×
                    });
21121280×
            let none_removed = tracked
21131280×
                .keys()
21149041×
                .filter(|r| is_attributes(r))
21151280×
                .all(|r| on_disk.contains(r.as_str()));
21161280×
            attrs_unchanged && none_removed
21171280×
        });
21181283×
        *self.walked_dirs.borrow_mut() =
21191283×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
21201283×
        drop(walk_phase);
21211283×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2122
        // Reading files is most of a walk's cost; do it in parallel.
2123
        {
2124
            use rayon::prelude::*;
21251283×
            let mut read: Vec<(String, FsEntry)> = files
21261283×
                .par_iter()
212712062×
                .map(|(rel, path, meta)| {
2128
                    // A key is worked out only for a file the manifest
2129
                    // knows with the same stat and a key of its own.
213012062×
                    let key = keys
213112062×
                        .filter(|_| !is_attributes(rel))
213212062×
                        .filter(|_| {
213312022×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
213412022×
                        })
213512062×
                        .and_then(|k| k(rel));
213612062×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
213712062×
                })
21381283×
                .collect::<Result<Vec<_>>>()?;
213912060×
            for (rel, e) in read.iter_mut() {
2140
                // A cached blob the store lost (gc, a partial clone): read the file after all.
214112060×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
21420×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
21430×
                    e.blob = None;
214412060×
                }
2145
            }
2146
            // The listing is in path order, so the map is built without
2147
            // searching.
21481282×
            out = read.into_iter().collect();
21491282×
            for (rel, target) in symlinks {
21502×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
21512×
            }
2152
        }
21531282×
        drop(_read_phase);
21541282×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2155
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2156
        // already tracked as subrepo nodes, they contribute their pin;
2157
        // unregistered ones are left alone.
21581282×
        let modules = self.modules_on_disk();
21591282×
        let removed = self.removed_subrepos();
21601282×
        for rel in &removed {
21613×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
21621×
                self.clear_removed_subrepo(rel);
21632×
            }
2164
        }
21651282×
        let mut untracked_nested = Vec::new();
21661282×
        for dir in nested {
216731×
            let rel = self.rel_path(&dir);
216831×
            if !self.in_scope(&rel) || removed.contains(&rel) {
21693×
                continue;
217028×
            }
217128×
            let registered = modules.entries.get(&rel);
217228×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2173
            {
21741×
                untracked_nested.push(rel);
21751×
                continue;
217627×
            }
217727×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
217827×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2179
        }
21801282×
        untracked_nested.sort();
21811282×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2182
        // Tracked paths the ignore rules hid.
21831282×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
218483×
            if !self.in_scope(rel) {
218510×
                continue;
218673×
            }
218773×
            let path = self.root.join(rel);
218873×
            if *kind == NodeKind::Subrepo {
21894×
                if removed.contains(rel) {
21902×
                    continue;
21912×
                }
21922×
                let present =
21932×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
21942×
                if present {
21950×
                    let pin = subrepos::read_pin(
21960×
                        &path,
21970×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
21980×
                    )?;
21990×
                    out.insert(
22000×
                        rel.clone(),
22010×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2202
                    );
22032×
                } else if let Some(b) = blob {
22042×
                    // Not cloned (or emptied): the pin stays as recorded, as a
22052×
                    // Git gitlink does when its directory is absent.
22062×
                    out.insert(
22072×
                        rel.clone(),
22082×
                        FsEntry {
22092×
                            blob: Some(*b),
22102×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
22112×
                        },
22122×
                    );
22132×
                }
22142×
                continue;
221569×
            }
221669×
            let Ok(meta) = fs::symlink_metadata(&path) else {
221769×
                continue;
2218
            };
22190×
            let ft = meta.file_type();
22200×
            if ft.is_symlink() {
22210×
                let target = fs::read_link(&path)?;
22220×
                out.insert(
22230×
                    rel.clone(),
22240×
                    FsEntry::new(
22250×
                        NodeKind::Symlink,
2226
                        false,
22270×
                        target.to_string_lossy().as_bytes().to_vec(),
2228
                    ),
2229
                );
22300×
            } else if ft.is_file() {
22310×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
22320×
                out.insert(rel.clone(), e);
22330×
            }
2234
        }
22351282×
        Ok(out)
22361283×
    }
2237
2238
    /// The entry for one regular file, read or served from the stat cache.
22390×
    fn file_entry(
22400×
        &self,
22410×
        rel: &str,
22420×
        path: &Path,
22430×
        meta: &walk::Stat,
22440×
        cache: Option<&prompt::Manifest>,
22450×
    ) -> Result<FsEntry> {
22460×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
22470×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
22480×
            e.content = std::sync::Arc::new(fs::read(path)?);
22490×
            e.blob = None;
22500×
        }
22510×
        Ok(e)
22520×
    }
2253
2254
    /// The non-directory paths of a snapshot with their kinds, for the
2255
    /// walker's `tracked` set.
22562×
    pub(crate) fn tracked_kinds(
22572×
        snapshot: &Snapshot,
22582×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
22592×
        snapshot
22602×
            .files
22612×
            .iter()
226212×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
22638×
            .map(|(p, f)| {
22648×
                let blob = match &f.content {
22654×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
22664×
                    _ => None,
2267
                };
22688×
                (p.clone(), (f.kind, blob))
22698×
            })
22702×
            .collect()
22712×
    }
2272
2273
    /// A path under the root as a `/`-separated relative string.
227470×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
227570×
        path.strip_prefix(&self.root)
227670×
            .unwrap_or(path)
227770×
            .components()
2278134×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
227970×
            .collect::<Vec<_>>()
228070×
            .join("/")
228170×
    }
2282
}
2283
2284
impl Repo {
2285
    /// Changes reachable from the bookmark and the working copy, newest first.
228695×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
228795×
        let heads = self.bookmark_heads()?;
228895×
        if self.bare {
22891×
            return self.log_state(&heads);
229094×
        }
229194×
        let (wc_hash, wc) = self.working_copy()?;
229294×
        let mut all = heads.clone();
229394×
        all.push(wc_hash);
229494×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
229594×
        let mut entries: Vec<LogEntry> = Vec::new();
2296
        // A shallow clone knows changes beyond its boundary from a
2297
        // checkpoint's metadata only: its log comes from the state.
229894×
        let metas = if self.is_shallow() {
22991×
            self.load_state_history(&all)?
23001×
                .changes()
23019×
                .map(|(h, m)| (*h, m.clone()))
23021×
                .collect()
2303
        } else {
2304
            // The working copy's change is in hand, and is never in the
2305
            // state index: its metadata is not looked up again.
230693×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
230793×
            below.extend(wc.deps.iter().copied());
230893×
            let _t = crate::timing::phase("log: metadata");
230993×
            let mut metas = self.metas_of(&below)?;
2310325×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
231193×
                // First, where the log puts it, so the order may hold.
231293×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
231393×
            }
231493×
            metas
2315
        };
231694×
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2317427×
            hash: h,
2318427×
            change: meta,
2319427×
            is_working_copy: h == wc_hash,
2320427×
            is_head: head_set.contains(&h),
2321427×
        }));
232294×
        let _sorting = crate::timing::phase("log: sort");
2323
        // The hash makes the order total, so an unstable sort gives the same.
2324
        // From the state index the order already holds (oxygen#94).
2325843×
        let order = |a: &LogEntry, b: &LogEntry| {
2326843×
            b.is_working_copy
2327843×
                .cmp(&a.is_working_copy)
2328843×
                .then(crate::state::log_order(
2329843×
                    (&a.hash, &a.change.hlc),
2330843×
                    (&b.hash, &b.change.hlc),
2331
                ))
2332843×
        };
2333201×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
233449×
            entries.sort_unstable_by(order);
233549×
        }
233694×
        Ok(entries)
233795×
    }
2338
2339
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2340
    /// count, for paginated views.
23410×
    pub fn log_window(
23420×
        &self,
23430×
        heads: &[ChangeHash],
23440×
        offset: usize,
23450×
        limit: usize,
23460×
    ) -> Result<(Vec<LogEntry>, usize)> {
23470×
        let all = self.log_state(heads)?;
23480×
        let total = all.len();
23490×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
23500×
    }
2351
2352
    /// The log of the state with these heads, newest first, with no working
2353
    /// copy involved (for hosted repositories and any explicit state).
235410×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2355
        // The log needs change metadata only: neither graphs nor the tree.
235610×
        if self.is_shallow() {
23570×
            return Ok(self.log_of(&self.load_state_history(heads)?));
235810×
        }
235910×
        let metas = self.metas_of(heads)?;
236010×
        let depended: BTreeSet<ChangeHash> = metas
236110×
            .iter()
236230×
            .flat_map(|(_, m)| m.deps.iter().copied())
236310×
            .collect();
236410×
        let mut entries: Vec<LogEntry> = metas
236510×
            .into_iter()
236610×
            .map(|(h, meta)| LogEntry {
236730×
                hash: h,
236830×
                is_head: !depended.contains(&h),
236930×
                change: meta,
2370
                is_working_copy: false,
237130×
            })
237210×
            .collect();
237339×
        let order = |a: &LogEntry, b: &LogEntry| {
237439×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
237539×
        };
237613×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
23774×
            entries.sort_unstable_by(order);
23786×
        }
237910×
        Ok(entries)
238010×
    }
2381
2382
    /// Every change of the state with these heads and its metadata, read
2383
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2384
    /// a shallow clone's boundary is left out.
2385177×
    pub fn metas_of(
2386177×
        &self,
2387177×
        heads: &[ChangeHash],
2388177×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2389177×
        let boundary = self.boundary();
2390
        // The state index holds the metadata of its heads' closure: a
2391
        // change found there is not read from the store (a change object
2392
        // can be as large as the tree it adds).
2393177×
        let read = self.read_state_index_changes();
2394
        // Every one of `heads` in the index, and every head of the index
2395
        // among them: their closure is the index's changes, all of them
2396
        // (it is closed), and no walk is needed to find it.
2397177×
        if let Some((index_heads, all)) = &read {
2398160×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2399160×
            let in_index = || {
2400160×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2401160×
                    index_heads.iter().collect();
2402
                // Usually the heads asked are the index's: no set of all.
2403160×
                heads.iter().all(|h| index_heads.contains(h)) || {
2404160×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2405160×
                        all.iter().map(|(h, _)| h).collect();
2406160×
                    heads.iter().all(|h| all.contains(h))
2407
                }
2408160×
            };
2409160×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
24100×
                let (_, all) = read.expect("matched above");
2411
                #[cfg(test)]
2412
                {
2413
                    // The walk the shortcut saves finds the same changes.
24140×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
24150×
                    let mut stack = heads.to_vec();
24160×
                    while let Some(h) = stack.pop() {
24170×
                        if seen.insert(h) {
24180×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
24190×
                        }
2420
                    }
24210×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2422
                }
24230×
                return Ok(all);
2424160×
            }
242517×
        }
2426177×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2427177×
            read.map(|(_, all)| all.into_iter().collect());
2428177×
        let _walk = crate::timing::phase("metadata: walk");
2429177×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2430177×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2431177×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2432177×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
24331277×
        while let Some(h) = stack.pop() {
24341100×
            if !seen.insert(h) {
2435461×
                continue;
2436639×
            }
2437
            // Taken out of the index's map, each once: not copied.
2438639×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2439
                #[cfg(test)]
24400×
                assert_eq!(
2441
                    meta,
24420×
                    self.store.get_change_meta(&h)?,
2443
                    "the state index holds a change's metadata"
2444
                );
24450×
                stack.extend(meta.deps.iter().copied());
24460×
                out.push((h, meta));
24470×
                continue;
2448639×
            }
2449639×
            let started = std::time::Instant::now();
2450639×
            let meta = match self.store.get_change_meta(&h) {
2451639×
                Ok(m) => m,
24520×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
24530×
                Err(e) => return Err(e.into()),
2454
            };
2455639×
            stored += 1;
2456639×
            from_store += started.elapsed();
2457639×
            stack.extend(meta.deps.iter().copied());
2458639×
            out.push((h, meta));
2459
        }
2460177×
        if stored > 0 && crate::timing::enabled() {
24610×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2462177×
        }
2463177×
        Ok(out)
2464177×
    }
2465
2466
    /// The log of a state already loaded, newest first.
2467
    /// The history of lines `first..=last` (1-based) of `path` in the
2468
    /// state `heads` make (spec §27): every change that inserted or
2469
    /// deleted one of their atoms, or an atom deleted from between them,
2470
    /// newest first. Exact, as atoms keep their identity across edits.
24716×
    pub fn line_history(
24726×
        &self,
24736×
        heads: &[ChangeHash],
24746×
        path: &str,
24756×
        first: usize,
24766×
        last: usize,
24776×
    ) -> Result<Vec<LogEntry>> {
24786×
        if first == 0 || last < first {
24791×
            return fail(format!(
2480
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2481
            ));
24825×
        }
24835×
        let mut state = self.load_state_history(heads)?;
24845×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
24851×
            return fail(format!("{path} is not in that state"));
2486
        };
24874×
        self.load_graphs_of(&mut state, &[node])?;
24884×
        let live = state.live_lines(&node);
24894×
        if last > live.len() {
24901×
            return fail(format!(
2491
                "{path} has {} lines; asked for {first},{last}",
24921×
                live.len()
2493
            ));
24943×
        }
24953×
        let Some(g) = state.file(&node) else {
24960×
            return fail(format!("{path} is not a text file"));
2497
        };
24983×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
24993×
        let touched = g.touching(&atoms);
25003×
        Ok(self
25013×
            .log_of(&state)
25023×
            .into_iter()
250313×
            .filter(|e| touched.contains(&e.hash))
25043×
            .collect())
25056×
    }
2506
25078×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
25088×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
25098×
        let mut entries: Vec<LogEntry> = state
25108×
            .changes()
25118×
            .map(|(h, meta)| LogEntry {
251231×
                hash: *h,
251331×
                change: meta.clone(),
2514
                is_working_copy: false,
251531×
                is_head: head_set.contains(h),
251631×
            })
25178×
            .collect();
251840×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
25198×
        entries
25208×
    }
2521
2522
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2523
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2524
    /// (`resolve_change`).
252567×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
252667×
        let view = self.view()?;
252767×
        if let Some(st) = view.bookmarks.get(spec) {
252839×
            return Ok(self.store.get_state(st)?.heads);
252928×
        }
253028×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
25312×
            return Ok(self.store.get_state(&st)?.heads);
253226×
        }
253326×
        if let Some(heads) = self.tag_heads(spec)? {
25342×
            return Ok(heads);
253524×
        }
253624×
        Ok(vec![self.resolve_change(spec)?])
253767×
    }
2538
2539
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2540
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
254136×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
254236×
        if spec == "@" {
25430×
            return Ok(self.working_copy()?.0);
254436×
        }
254536×
        let view = self.view()?;
254636×
        let named = match view.bookmarks.get(spec) {
25471×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
254835×
            None => match remote_bookmark(&view, spec) {
25491×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
255034×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2551
            },
2552
        };
255336×
        if let Some((kind, heads)) = named {
25543×
            return match heads.len() {
25553×
                1 => Ok(heads[0]),
25560×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2557
            };
255833×
        }
255933×
        if spec.is_empty() || spec == "#" {
25600×
            return fail("empty change specifier");
256133×
        }
256233×
        let entries = self.log()?;
2563
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2564
        // cannot be a ChangeId, which has 32 (oxygen#103).
256533×
        let full_hash =
2566128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
256733×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
256827×
            entries
256927×
                .iter()
2570109×
                .filter(|e| e.hash.starts_with_hex(hp))
257127×
                .collect()
2572
        } else {
25736×
            entries
25746×
                .iter()
257521×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
25766×
                .collect()
2577
        };
257833×
        match matches.len() {
257928×
            1 => Ok(matches[0].hash),
25805×
            0 => match self.resolve_in_remotes(spec)? {
25811×
                Some(h) => Ok(h),
25824×
                None => fail(format!("no change matches {spec:?}")),
2583
            },
2584
            _ => {
25850×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
25860×
                if ids.len() == 1 {
25870×
                    fail(format!(
2588
                        "change {spec} is divergent: {} variants",
25890×
                        matches.len()
2590
                    ))
2591
                } else {
25920×
                    fail(format!("{spec:?} is ambiguous"))
2593
                }
2594
            }
2595
        }
259636×
    }
2597
2598
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2599
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2600
    /// `None` when none matches, or more than one.
26015×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
26025×
        let view = self.view()?;
26035×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
26045×
        for bookmarks in view.remotes.values() {
26053×
            for st in bookmarks.values() {
26063×
                let heads = self.store.get_state(st)?.heads;
26077×
                for e in self.log_state(&heads)? {
26087×
                    let hit = match spec.strip_prefix('#') {
26092×
                        Some(hp) => e.hash.starts_with_hex(hp),
26105×
                        None => e.change.change_id.starts_with_hex(spec),
2611
                    };
26127×
                    if hit {
26131×
                        found.insert(e.hash);
26146×
                    }
2615
                }
2616
            }
2617
        }
26185×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
26195×
    }
2620
2621
    /// Where a change is when no local bookmark or the working copy holds
2622
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2623
    /// it is held locally, or nowhere.
26243×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
26256×
        if self.log()?.iter().any(|e| e.hash == *hash) {
26262×
            return Ok(None);
26271×
        }
26281×
        let view = self.view()?;
26291×
        for (remote, bookmarks) in &view.remotes {
26301×
            for (name, st) in bookmarks {
26311×
                let heads = self.store.get_state(st)?.heads;
26321×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
26331×
                    return Ok(Some(format!("{remote}/{name}")));
26340×
                }
2635
            }
2636
        }
26370×
        Ok(None)
26383×
    }
2639
2640
    /// Human-readable description of what a change does, with line content.
26413×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
26423×
        let change = self.store.get_change(hash)?;
26433×
        let (base, base_snapshot) = self.change_base(&change)?;
26443×
        Ok(render_change(&change, &base, &base_snapshot))
26453×
    }
2646
2647
    /// The base state of `change` (its dependencies) and its rendering, as
2648
    /// much as showing the change needs: the whole tree, and the graphs and
2649
    /// contents of the files the change edits. Other text files are left
2650
    /// unrendered ([`Snapshot::unrendered`]).
26516×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
26526×
        let base = self.load_state_history(&change.deps)?;
26536×
        self.render_base_for(change, base)
26546×
    }
2655
2656
    /// The base for showing `change` alone: the graphs of the files it
2657
    /// edits built, and the base's tree with no file rendered, which is
2658
    /// all [`render_change`](snapshot::render_change) and
2659
    /// [`diff_files_of`](snapshot::diff_files_of) read.
26603×
    pub(crate) fn tree_base_for(
26613×
        &self,
26623×
        change: &Change,
26633×
        mut base: State,
26643×
    ) -> Result<(State, Snapshot)> {
26653×
        let _t = crate::timing::phase("diff: the base's tree");
26663×
        let edited: std::collections::HashSet<NodeId> =
26678×
            change.edits.iter().map(|e| e.node()).collect();
26683×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
26693×
        self.load_graphs_of(&mut base, &nodes)?;
26703×
        let snapshot = Snapshot {
26713×
            tree: base.tree().view(),
26723×
            files: BTreeMap::new(),
26733×
            unrendered: BTreeSet::new(),
26743×
        };
26753×
        Ok((base, snapshot))
26763×
    }
2677
2678
    /// [`Repo::change_base`] with the base already loaded (the working
2679
    /// copy's comes from the state index).
2680211×
    pub(crate) fn render_base_for(
2681211×
        &self,
2682211×
        change: &Change,
2683211×
        mut base: State,
2684211×
    ) -> Result<(State, Snapshot)> {
2685211×
        let _t = crate::timing::phase("diff: render the base");
2686211×
        let edited: std::collections::HashSet<NodeId> =
2687417×
            change.edits.iter().map(|e| e.node()).collect();
2688211×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2689211×
        self.load_graphs_of(&mut base, &nodes)?;
2690211×
        let snapshot = {
2691211×
            let _t = crate::timing::phase("diff:   of which materialize");
2692211×
            base.materialize_nodes(&edited)
2693
        };
2694211×
        Ok((base, snapshot))
2695211×
    }
2696
}
2697
26980×
fn remove_any(path: &Path) -> std::io::Result<()> {
26990×
    let m = fs::symlink_metadata(path)?;
27000×
    if m.is_dir() {
27010×
        fs::remove_dir_all(path)
2702
    } else {
27030×
        fs::remove_file(path)
2704
    }
27050×
}
2706
27075×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
27085×
    let mut perms = fs::metadata(path)?.permissions();
27095×
    perms.set_readonly(readonly);
27105×
    fs::set_permissions(path, perms)
27115×
}
2712
2713
#[cfg(unix)]
27145853×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2715
    use std::os::unix::fs::PermissionsExt;
27165853×
    let mut perms = fs::metadata(path)?.permissions();
27175853×
    let mode = perms.mode();
27185853×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
27195853×
    if want != mode {
27204×
        perms.set_mode(want);
27214×
        fs::set_permissions(path, perms)?;
27225849×
    }
27235853×
    Ok(())
27245853×
}
2725
#[cfg(not(unix))]
2726
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2727
    Ok(())
2728
}
2729
2730
#[cfg(unix)]
273116275×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2732
    use std::os::unix::fs::PermissionsExt;
273316275×
    m.permissions().mode() & 0o111 != 0
273416275×
}
2735
#[cfg(not(unix))]
2736
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2737
    false
2738
}
2739
274012832×
fn op_ref(k: OpKey) -> OpRef {
274112832×
    OpRef {
274212832×
        change: k.0,
274312832×
        index: k.1,
274412832×
    }
274512832×
}
2746
27476046×
fn split_path(path: &str) -> (&str, &str) {
27486046×
    match path.rfind('/') {
27495059×
        Some(i) => (&path[..i], &path[i + 1..]),
2750987×
        None => ("", path),
2751
    }
27526046×
}
2753
2754
/// Whether `rel` is an attributes file (spec §7.6).
275567198×
fn is_attributes(rel: &str) -> bool {
275667198×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
275767198×
}
2758
2759
/// The manifest entry for `rel` when its size and mtime match it outside
2760
/// the racy window.
276124093×
fn stat_cached<'m>(
276224093×
    rel: &str,
276324093×
    meta: &walk::Stat,
276424093×
    cache: Option<&'m prompt::Manifest>,
276524093×
) -> Option<&'m prompt::ManifestEntry> {
276624093×
    let m = cache?;
276719145×
    let e = m.entries.get(rel)?;
276817796×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
276917796×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
277024093×
}
2771
2772
/// Read one working-copy file, or serve it from the stat cache (spec
2773
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2774
/// an opaque file is not read at all (its stored blob stands in), and a
2775
/// text file the manifest recorded equal to a base graph whose key is
2776
/// `key`, the key the base has now, is not read either: equal keys mean
2777
/// equal renderings, so it still equals the base. Touches no repository
2778
/// state, so the walk runs it in parallel; the caller checks that a cached
2779
/// blob is still in the store.
278012062×
fn read_file_entry(
278112062×
    rel: &str,
278212062×
    path: &Path,
278312062×
    meta: &walk::Stat,
278412062×
    cache: Option<&prompt::Manifest>,
278512062×
    key: Option<[u8; 32]>,
278612062×
) -> Result<FsEntry> {
278712062×
    let exec = meta.exec;
278812062×
    let stat = Some((meta.size, meta.mtime_ns));
278912062×
    let mut e = match stat_cached(rel, meta, cache) {
27904249×
        Some(e) if e.blob.is_some() => FsEntry {
27911×
            blob: e.blob,
27921×
            content_hash: Some(e.hash),
27931×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27941×
        },
27954248×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
27964243×
            content_hash: Some(e.hash),
27974243×
            unchanged: true,
27984243×
            graph_key: e.graph,
27994243×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28004243×
        },
28015×
        Some(e) => FsEntry {
28025×
            content_hash: Some(e.hash),
28035×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2804
        },
28057813×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2806
    };
2807
    // The stat the manifest records: taken before the read, so a file that
2808
    // changes meanwhile is read again next time.
280912061×
    e.stat = stat;
281012061×
    Ok(e)
281112062×
}
2812
2813
/// Two maps side by side in key order: each key of either, with its value
2814
/// in each. Linear, with no lookups, for maps of a whole tree.
28152587×
pub(crate) fn join<'a, A, B>(
28162587×
    a: &'a BTreeMap<String, A>,
28172587×
    b: &'a BTreeMap<String, B>,
28182587×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
28192587×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
282035682×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
28212587×
        (None, None) => None,
28222941×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
28235829×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
282424325×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2825330×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2826302×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2827
            std::cmp::Ordering::Equal => {
282823693×
                let (k, va) = a.next()?;
282923693×
                let (_, vb) = b.next()?;
283023693×
                Some((k, Some(va), Some(vb)))
2831
            }
2832
        },
283335682×
    })
28342587×
}
2835
2836
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2837
/// lookups.
28381283×
pub(crate) fn missing_from<'a, A, B>(
28391283×
    a: &'a BTreeMap<String, A>,
28401283×
    b: &BTreeMap<String, B>,
28411283×
) -> Vec<(&'a String, &'a A)> {
28421283×
    let mut keys = b.keys().peekable();
28431283×
    a.iter()
28449051×
        .filter(|(k, _)| {
284517424×
            while keys.next_if(|kb| *kb < *k).is_some() {}
28469051×
            keys.peek() != Some(k)
28479051×
        })
28481283×
        .collect()
28491283×
}