OXYGENHUB

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

1834 of 2066 lines run, 429 of 694 functions · run #318 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.
752479×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762479×
    let Some(url) = &config.storage_url else {
772474×
        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×
    )?)
1002479×
}
101
102165×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103165×
    Err(RepoError::Msg(s.into()))
104165×
}
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 walk;
134
mod workspace;
135
136
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
137
pub use checkout::CheckoutReport;
138
pub use config::{parse_size, read_config_file, Config};
139
pub use doctor::{Check, DoctorReport, Health};
140
pub use fsck::{FsckReport, Problem, Severity};
141
pub use gc::GcReport;
142
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
143
pub use hooks::{json_array, json_str, HookOutcome};
144
pub use hosted::FileEdit;
145
pub use identity::{Rotation, SignatureStatus};
146
pub use inspect::{BisectStep, BlameLine, Description};
147
pub use keyless::home_key;
148
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
149
pub use policy::PolicyUpdate;
150
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
151
pub use receipts::ReceiptInfo;
152
pub use revset::{Revset, REVSET_BUDGET};
153
pub use snapshot::{
154
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
155
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
156
    Selection, SnapshotResult,
157
};
158
pub use subrepos::{SubrepoInfo, SubrepoSync};
159
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT};
160
pub use tags::TagInfo;
161
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
162
163
/// The file name under which per-bookmark or per-tag data is kept: `/`
164
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
165
/// than a directory that would clash with it.
1664130×
pub(crate) fn name_file(name: &str) -> String {
1674130×
    name.replace('%', "%25").replace('/', "%2F")
1684130×
}
169
170
/// The name a [`name_file`] file name stands for.
17143×
pub(crate) fn file_name_to_name(file: &str) -> String {
17243×
    file.replace("%2F", "/").replace("%25", "%")
17343×
}
174
1757262×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1767262×
    Ok(crate::durable::write_atomic(path, data)?)
1777262×
}
178
179
/// Replace a cache file: whole or not at all, but without waiting for the
180
/// disk. A cache checks its own bytes when read, so one a crash leaves
181
/// short or stale is rebuilt rather than trusted.
182
/// How many changes a state index may fall behind its working copy before
183
/// it is written again; until then each load replays them.
184
const INDEX_REPLAY_LIMIT: usize = 16;
185
/// The changes whose encodings are kept for building graphs: a batch of
186
/// files often takes inline text from a few changes in turn.
187
const CHANGE_CACHE_COUNT: usize = 4;
188
const CHANGE_CACHE_BYTES: usize = 512 << 20;
189
/// How many state indexes a workspace keeps.
190
const STATE_INDEXES_KEPT: usize = 2;
191
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
192
1932882×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1942882×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1952882×
    fs::write(&tmp, data)?;
1962882×
    fs::rename(&tmp, path)?;
1972882×
    Ok(())
1982882×
}
199
200
pub struct LogEntry {
201
    pub hash: ChangeHash,
202
    /// Metadata from the state; the full change may be absent in a shallow repository.
203
    pub change: crate::state::ChangeMeta,
204
    pub is_working_copy: bool,
205
    pub is_head: bool,
206
}
207
208
/// A text file's base graph key, by path, as a walk asks for it.
209
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
210
211
/// A file as found on disk or in an imported tree.
212
#[derive(Clone)]
213
pub(crate) struct FsEntry {
214
    pub kind: NodeKind,
215
    pub exec: bool,
216
    /// File content, or a symlink's target. Empty when `blob` is set.
217
    /// Shared, so a new file's insert holds it without a copy.
218
    pub content: std::sync::Arc<Vec<u8>>,
219
    /// The stored blob of an opaque file whose size and mtime are unchanged
220
    /// since the last manifest (spec §12.3 stat cache); the content was not
221
    /// read.
222
    pub blob: Option<ObjectRef>,
223
    /// BLAKE3 of the content, carried over from the manifest when the stat
224
    /// is unchanged, so the manifest can be rewritten without rehashing.
225
    pub content_hash: Option<[u8; 32]>,
226
    /// A text file known equal to the base's rendering without reading it:
227
    /// its stat matches the manifest and the manifest recorded it equal to
228
    /// a base file graph with the same key (spec §12.3). `content` is empty.
229
    pub unchanged: bool,
230
    /// The base graph key this file equals, for the next manifest.
231
    pub graph_key: Option<[u8; 32]>,
232
    /// Size and mtime already known to be current (a checkout leaving the
233
    /// file as it was), so the manifest need not stat it again.
234
    pub stat: Option<(u64, u128)>,
235
}
236
237
impl FsEntry {
23824802×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
23924802×
        FsEntry {
24024802×
            kind,
24124802×
            exec,
24224802×
            content: std::sync::Arc::new(content),
24324802×
            blob: None,
24424802×
            content_hash: None,
24524802×
            unchanged: false,
24624802×
            graph_key: None,
24724802×
            stat: None,
24824802×
        }
24924802×
    }
250
}
251
252
pub struct Repo {
253
    /// The key a host accepts certified updates with (spec §14.7): when
254
    /// set, accepting a reference update signed by a short-lived key also
255
    /// records the host's acceptance and its time.
256
    pub(crate) acceptor: Option<std::sync::Arc<(Identity, crate::identity::SecretKey)>>,
257
    /// With `author.signer = keyless`, the fresh key the hub last
258
    /// certified and when its certificate ends (spec §14.7): kept in memory
259
    /// only, for one command.
260
    pub(crate) keyless_key: std::cell::RefCell<Option<(KeyId, crate::identity::SecretKey, u64)>>,
261
    /// Oxygen-pinned subrepos skipped by the running Git export.
262
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
263
    /// The manifest as last read, with the file identity it was read from,
264
    /// so one command parses it once (see `read_manifest`).
265
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
266
    /// A listing of the working copy left by a failed clean check, for the
267
    /// snapshot that follows it to reuse; taken by the next walk and
268
    /// dropped whenever the manifest is written.
269
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
270
    /// The nested repositories the last walk left out, being neither
271
    /// registered nor tracked subrepos (oxygen#43).
272
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
273
    /// New untracked files the last walk left out for their size, with
274
    /// their sizes (oxygen#98).
275
    pub(crate) skipped_large: std::cell::RefCell<Vec<(String, u64)>>,
276
    root: PathBuf,
277
    oxy: PathBuf,
278
    store: Store,
279
    workspace: WorkspaceId,
280
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
281
    bare: bool,
282
    keys_dir: PathBuf,
283
    user_config: PathBuf,
284
    pub config: Config,
285
    /// What the working copy's file system can represent (spec §7.7).
286
    platform: crate::portable::Platform,
287
    /// The encodings of the changes last read for their inline inserts,
288
    /// oldest first.
289
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
290
    /// `--at-op`: read the repository as it was after this operation;
291
    /// recording an operation is refused.
292
    at_op: Option<ObjectRef>,
293
    /// The directories (with their times) and nested repositories of the
294
    /// last walk, for the manifest written from it.
295
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
296
    /// The directories a manifest check listed, for its restamp only.
297
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
298
}
299
300
/// A walk's directories with their times, and its nested repositories.
301
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
302
303
/// Marker file of a bare repository, inside `.oxy/`.
304
const BARE_MARKER: &str = "bare";
305
/// Marker of a hosted repository that has no id yet: the first push binds
306
/// it to the pusher's id (spec §16.1).
307
const UNBOUND_MARKER: &str = "unbound";
308
309
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
310
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
3117685×
pub fn default_home() -> PathBuf {
3127685×
    if let Ok(h) = std::env::var("OXY_HOME") {
3137679×
        return PathBuf::from(h);
3146×
    }
3156×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3160×
        return PathBuf::from(x).join("oxy");
3176×
    }
318
    // Windows has no HOME as a rule: the roaming profile's application
319
    // data, as Windows programs keep theirs.
320
    #[cfg(windows)]
321
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
322
        return PathBuf::from(d).join("oxy");
323
    }
3246×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3256×
    PathBuf::from(home).join(".config").join("oxy")
3267685×
}
327
3282480×
pub fn default_keys_dir() -> PathBuf {
3292480×
    default_home().join("keys")
3302480×
}
331
3324958×
pub fn default_user_config() -> PathBuf {
3334958×
    default_home().join("config.toml")
3344958×
}
335
336
/// Where `create_identity` records the author.
337
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
338
pub enum IdentityScope {
339
    /// The user file: every repository of this user signs with it.
340
    User,
341
    /// This repository only.
342
    Repo,
343
}
344
345
impl Repo {
346
    // ------------------------------------------------------------ lifecycle
347
348227×
    pub fn init(root: &Path) -> Result<Repo> {
349227×
        let mut id = [0u8; 16];
350227×
        rand::rngs::OsRng.fill_bytes(&mut id);
351227×
        Self::init_with_id(root, id)
352227×
    }
353
354
    /// Initialize a repository with a given repository ID (clones share the
355
    /// ID of their origin, spec §14.4).
356481×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
357481×
        Self::init_on(root, id, None)
358481×
    }
359
360
    /// A new repository with a fresh id, bare or not, on `storage` or in
361
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
36212×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
36312×
        let mut id = [0u8; 16];
36412×
        rand::rngs::OsRng.fill_bytes(&mut id);
36512×
        if bare {
3660×
            Self::init_bare_on(root, id, storage)
367
        } else {
36812×
            Self::init_on(root, id, storage)
369
        }
37012×
    }
371
372
    /// Initialize a repository whose objects and operation head are kept
373
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
374496×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
375496×
        fs::create_dir_all(root)?;
376496×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
377496×
        let oxy = root.join(OXY_DIR);
378496×
        if oxy.exists() {
3791×
            return fail(format!("{} is already an oxy repository", root.display()));
380495×
        }
381495×
        fs::create_dir_all(oxy.join("ops"))?;
382495×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
383495×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
384495×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
385495×
        if let Some(url) = storage {
3863×
            config.set("storage.url", url)?;
387492×
        }
388495×
        config.save(&oxy.join("config"))?;
389495×
        let workspace = WorkspaceId::random();
390495×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
391495×
        let store = open_objects(&oxy, &config)?;
392494×
        let repo = Repo {
393494×
            acceptor: None,
394494×
            keyless_key: Default::default(),
395494×
            last_change: Default::default(),
396494×
            at_op: None,
397494×
            walked_dirs: Default::default(),
398494×
            listed_dirs: Default::default(),
399494×
            git_export_skipped: Default::default(),
400494×
            manifest_cache: Default::default(),
401494×
            listing_cache: Default::default(),
402494×
            untracked_nested: Default::default(),
403494×
            skipped_large: Default::default(),
404494×
            root,
405494×
            oxy,
406494×
            store,
407494×
            workspace,
408494×
            bare: false,
409494×
            keys_dir: default_keys_dir(),
410494×
            platform: crate::portable::Platform::current(),
411494×
            user_config: default_user_config(),
412494×
            config,
413494×
        };
414494×
        repo.register_workspace(&workspace, &repo.root)?;
415
416494×
        let wc = repo.new_working_copy(vec![], "");
417494×
        let wc_hash = repo.store.put_change(&wc)?;
418494×
        let mut view = View::default();
419494×
        view.bookmarks.insert(
420494×
            repo.config.bookmark.clone(),
421494×
            repo.store.put_state(&StateObject::new(vec![]))?,
422
        );
423494×
        view.workspaces.insert(workspace, wc_hash);
424494×
        repo.record_op(&[], "oxy init", view)?;
425492×
        Ok(repo)
426496×
    }
427
428
    /// Create a bare repository: an object store, operation log and
429
    /// references with no workspace and no working copy, for hosting
430
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4315×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4325×
        let mut id = [0u8; 16];
4335×
        rand::rngs::OsRng.fill_bytes(&mut id);
4345×
        Self::init_bare_with_id(root, id)
4355×
    }
436
43740×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
43840×
        Self::init_bare_on(root, id, None)
43940×
    }
440
441
    /// [`Repo::init_on`] for a bare repository.
44240×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
44340×
        fs::create_dir_all(root)?;
44440×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
44540×
        let oxy = root.join(OXY_DIR);
44640×
        if oxy.exists() {
4470×
            return fail(format!("{} is already an oxy repository", root.display()));
44840×
        }
44940×
        fs::create_dir_all(oxy.join("ops"))?;
45040×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
45140×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
45240×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
45340×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
45440×
        if let Some(url) = storage {
4550×
            config.set("storage.url", url)?;
45640×
        }
45740×
        config.save(&oxy.join("config"))?;
45840×
        let store = open_objects(&oxy, &config)?;
45940×
        let repo = Repo {
46040×
            acceptor: None,
46140×
            keyless_key: Default::default(),
46240×
            last_change: Default::default(),
46340×
            at_op: None,
46440×
            walked_dirs: Default::default(),
46540×
            listed_dirs: Default::default(),
46640×
            git_export_skipped: Default::default(),
46740×
            manifest_cache: Default::default(),
46840×
            listing_cache: Default::default(),
46940×
            untracked_nested: Default::default(),
47040×
            skipped_large: Default::default(),
47140×
            root,
47240×
            oxy,
47340×
            store,
47440×
            workspace: WorkspaceId::ZERO,
47540×
            bare: true,
47640×
            keys_dir: default_keys_dir(),
47740×
            platform: crate::portable::Platform::current(),
47840×
            user_config: default_user_config(),
47940×
            config,
48040×
        };
48140×
        let mut view = View::default();
48240×
        view.bookmarks.insert(
48340×
            repo.config.bookmark.clone(),
48440×
            repo.store.put_state(&StateObject::new(vec![]))?,
485
        );
48640×
        repo.record_op(&[], "oxy init --bare", view)?;
48740×
        Ok(repo)
48840×
    }
489
490
    /// A bare repository with no id yet. Its `id()` is all zero until the
491
    /// first push binds it (`bind_id`), so an existing repository can be
492
    /// pushed to a freshly created hosted one and keep its identity.
49314×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
49414×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
49514×
        fs::remove_file(repo.oxy.join("id"))?;
49614×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
49714×
        Ok(repo)
49814×
    }
499
5003617×
    pub fn is_unbound(&self) -> bool {
5013617×
        self.oxy.join(UNBOUND_MARKER).is_file()
5023617×
    }
503
504
    /// Give an unbound repository its id.
50513×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
50613×
        if !self.is_unbound() {
5070×
            return fail("this repository already has an id");
50813×
        }
50913×
        if id == [0; 16] {
5100×
            return fail("a repository id cannot be all zero");
51113×
        }
51213×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
51313×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
51413×
        Ok(())
51513×
    }
516
517
    /// Whether this repository has no working copy (`init_bare`).
51876×
    pub fn is_bare(&self) -> bool {
51976×
        self.bare
52076×
    }
521
522
    /// Open the repository containing `start` (searching upwards).
5231944×
    pub fn open(start: &Path) -> Result<Repo> {
5241944×
        let start = start.canonicalize()?;
5251944×
        let mut dir: Option<&Path> = Some(&start);
5261944×
        while let Some(d) = dir {
5271944×
            let oxy = d.join(OXY_DIR);
5281944×
            if oxy.is_file() {
529
                // A secondary workspace (spec §12.2): the file points at the repository.
5309×
                let text = fs::read_to_string(&oxy)?;
5319×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5320×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
533
                };
5349×
                let format = fs::read_to_string(shared.join("format"))?;
5359×
                if format != FORMAT_LINE {
5360×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5379×
                }
5389×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5399×
                let store = open_objects(&shared, &config)?;
5409×
                let mut repo = Repo {
5419×
                    acceptor: None,
5429×
                    keyless_key: Default::default(),
5439×
                    last_change: Default::default(),
5449×
                    at_op: None,
5459×
                    walked_dirs: Default::default(),
5469×
                    listed_dirs: Default::default(),
5479×
                    git_export_skipped: Default::default(),
5489×
                    manifest_cache: Default::default(),
5499×
                    listing_cache: Default::default(),
5509×
                    untracked_nested: Default::default(),
5519×
                    skipped_large: Default::default(),
5529×
                    root: d.to_path_buf(),
5539×
                    oxy: shared,
5549×
                    store,
5559×
                    workspace,
5569×
                    bare: false,
5579×
                    keys_dir: default_keys_dir(),
5589×
                    platform: crate::portable::Platform::current(),
5599×
                    user_config: default_user_config(),
5609×
                    config,
5619×
                };
5629×
                repo.apply_workspace_bookmark();
5639×
                return Ok(repo);
5641935×
            }
5651935×
            if oxy.is_dir() {
5661935×
                let format = fs::read_to_string(oxy.join("format"))?;
5671935×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5681935×
                let bare = oxy.join(BARE_MARKER).is_file();
5691935×
                let workspace = if bare {
570148×
                    WorkspaceId::ZERO
571
                } else {
5721787×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5731787×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
574
                };
5751935×
                let store = open_objects(&oxy, &config)?;
5761935×
                let mut repo = Repo {
5771935×
                    acceptor: None,
5781935×
                    keyless_key: Default::default(),
5791935×
                    last_change: Default::default(),
5801935×
                    at_op: None,
5811935×
                    walked_dirs: Default::default(),
5821935×
                    listed_dirs: Default::default(),
5831935×
                    git_export_skipped: Default::default(),
5841935×
                    manifest_cache: Default::default(),
5851935×
                    listing_cache: Default::default(),
5861935×
                    untracked_nested: Default::default(),
5871935×
                    skipped_large: Default::default(),
5881935×
                    root: d.to_path_buf(),
5891935×
                    oxy,
5901935×
                    store,
5911935×
                    workspace,
5921935×
                    bare,
5931935×
                    keys_dir: default_keys_dir(),
5941935×
                    platform: crate::portable::Platform::current(),
5951935×
                    user_config: default_user_config(),
5961935×
                    config,
5971935×
                };
5981935×
                if !bare {
5991787×
                    repo.apply_workspace_bookmark();
6001787×
                }
6011935×
                if format == FORMAT1_LINE {
6021×
                    repo.migrate_format1()?;
6031934×
                } else if format != FORMAT_LINE {
6040×
                    return fail(format!("unsupported repository format: {}", format.trim()));
6051934×
                }
6061935×
                return Ok(repo);
6070×
            }
6080×
            dir = d.parent();
609
        }
6100×
        fail(format!(
611
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
6120×
            start.display()
613
        ))
6141944×
    }
615
616
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
617
    /// into format 2, where each bookmark names a `state` object.
6181×
    fn migrate_format1(&self) -> Result<()> {
6191×
        let (head, version) = self.read_head()?;
620
        // Collect the chain root-first.
6211×
        let mut chain: Vec<Format1Op> = Vec::new();
6221×
        let mut cur = Some(head);
6233×
        while let Some(r) = cur {
6242×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
6252×
            cur = op.parents.first().copied();
6262×
            chain.push(op);
627
        }
6281×
        chain.reverse();
6291×
        let mut new_parent: Option<ObjectRef> = None;
6302×
        for old in chain {
6312×
            let mut view = View::default();
6322×
            for (name, heads) in &old.view.bookmarks {
6332×
                view.bookmarks.insert(
6342×
                    name.clone(),
6352×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
636
                );
637
            }
6382×
            view.workspaces = old.view.workspaces.clone();
6392×
            let op = Op {
6402×
                parents: new_parent.into_iter().collect(),
6412×
                hlc: old.hlc,
6422×
                command: old.command,
6432×
                view,
6442×
                workspace: None,
6452×
                undoes: None,
6462×
            };
6472×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
648
        }
6491×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6500×
            return fail("the operation log changed while it was rewritten; run the command again");
6511×
        }
6521×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6531×
        Ok(())
6541×
    }
655
656
    /// Pack automatically once many loose objects have accumulated.
657660×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
658660×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6590×
            self.store.pack_loose()?;
6600×
            self.store.merge_packs()?;
661660×
        }
662660×
        Ok(())
663660×
    }
664
665
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6663323×
    pub fn id(&self) -> Result<[u8; 16]> {
6673323×
        if self.is_unbound() {
66819×
            return Ok([0; 16]);
6693304×
        }
6703304×
        let path = self.oxy.join("id");
6713304×
        match fs::read_to_string(&path) {
6723304×
            Ok(h) => hex::decode(h.trim())
6733304×
                .ok()
6743304×
                .and_then(|v| v.try_into().ok())
6753304×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6760×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6770×
                let mut id = [0u8; 16];
6780×
                rand::rngs::OsRng.fill_bytes(&mut id);
6790×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6800×
                Ok(id)
681
            }
6820×
            Err(e) => Err(e.into()),
683
        }
6843323×
    }
685
68662×
    pub fn root(&self) -> &Path {
68762×
        &self.root
68862×
    }
689523×
    pub fn store(&self) -> &Store {
690523×
        &self.store
691523×
    }
69211×
    pub fn workspace(&self) -> WorkspaceId {
69311×
        self.workspace
69411×
    }
695
696
    /// Use a different user directory for keys and the user config file
697
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
698
    /// Act as if the working copy were on another platform's file system
699
    /// (tests of Windows and macOS behaviour on any host).
700
    /// Accept certified updates as `identity` (a host's key), recording when
701
    /// (spec §14.7).
7021×
    pub fn with_acceptor(mut self, identity: Identity, sk: crate::identity::SecretKey) -> Repo {
7031×
        self.acceptor = Some(std::sync::Arc::new((identity, sk)));
7041×
        self
7051×
    }
706
7072×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
7082×
        self.platform = platform;
7092×
        self
7102×
    }
711
7120×
    pub fn platform(&self) -> crate::portable::Platform {
7130×
        self.platform
7140×
    }
715
716177×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
717177×
        let dir = dir.into();
718177×
        self.keys_dir = dir.join("keys");
719177×
        self.user_config = dir.join("config.toml");
720177×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
721177×
            self.config = c;
722177×
        }
723177×
        self.apply_workspace_bookmark();
724177×
        self
725177×
    }
726
727
    /// The workspace's current bookmark (spec §10.1) overrides the
728
    /// configured default when `oxy bookmark switch` has recorded one.
7291973×
    fn apply_workspace_bookmark(&mut self) {
7301973×
        if let Ok(b) = fs::read_to_string(
7311973×
            self.oxy
7321973×
                .join("workspaces")
7331973×
                .join(self.workspace.to_hex())
7341973×
                .join("bookmark"),
7351973×
        ) {
73635×
            let b = b.trim();
73735×
            if !b.is_empty() {
73835×
                self.config.bookmark = b.to_string();
73935×
            }
7401938×
        }
7411973×
    }
742
7432×
    pub fn user_config_path(&self) -> &Path {
7442×
        &self.user_config
7452×
    }
746
747
    /// Set a key in the user file and refresh the effective configuration.
74822×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
74922×
        Config::set_user(&self.user_config, key, value)?;
75021×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
75121×
        Ok(())
75222×
    }
753
754375×
    pub fn save_config(&self) -> Result<()> {
755375×
        self.config.save(&self.oxy.join("config"))
756375×
    }
757
7584345×
    fn author(&self) -> KeyId {
7594345×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7604345×
    }
761
}
762
763
impl Repo {
7641662×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7651662×
        let mut c = Change {
7661662×
            version: crate::objects::CHANGE_VERSION,
7671662×
            change_id: ChangeId::random(),
7681662×
            deps,
7691662×
            author: self.author(),
7701662×
            hlc: Hlc::now(),
7711662×
            message: message.into(),
7721662×
            tree_ops: vec![],
7731662×
            edits: vec![],
7741662×
            kind: ChangeKind::WorkingCopy,
7751662×
        };
7761662×
        c.normalize();
7771662×
        c
7781662×
    }
779
780
    // ------------------------------------------------------------ operation log
781
78214125×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
78314125×
        if let Some(r) = self.at_op {
7845×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
78514120×
        }
78614120×
        let r = self.head_ref()?;
78714118×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
78814118×
        Ok((r, op))
78914125×
    }
790
7919798×
    pub fn view(&self) -> Result<View> {
7929798×
        Ok(self.head_op()?.1.view)
7939798×
    }
794
7953441×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
7963441×
        self.record_op_undoing(parents, command, view, None)
7973441×
    }
798
799
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
8003444×
    fn record_op_undoing(
8013444×
        &self,
8023444×
        parents: &[ObjectRef],
8033444×
        command: &str,
8043444×
        view: View,
8053444×
        undoes: Option<ObjectRef>,
8063444×
    ) -> Result<ObjectRef> {
8073444×
        if self.at_op.is_some() {
8081×
            return fail(
809
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
810
            );
8113443×
        }
8123443×
        let op = Op {
8133443×
            parents: parents.to_vec(),
8143443×
            hlc: Hlc::now(),
8153443×
            command: command.into(),
8163443×
            view,
8173443×
            workspace: Some(self.workspace),
8183443×
            undoes,
8193443×
        };
8203443×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
821
        // The head is the commit point: everything it names must be on disk first.
8223441×
        let flushing = crate::timing::phase("op: flush the store");
8233441×
        self.store.flush()?;
8243439×
        drop(flushing);
825
        // Compare and swap (spec §12.1): when another process recorded an
826
        // operation since this one read the head, the two are merged
827
        // instead of one overwriting the other. On this disk the head moves
828
        // under a short lock; on any other store by its record's version,
829
        // and a record that moved meanwhile is read again and merged again.
8303439×
        let _lock = if self.store.is_local() {
8313431×
            Some(self.lock_ops()?)
832
        } else {
8338×
            None
834
        };
8353439×
        let Some(parent) = parents.first() else {
836
            // The first operation (init): there is no head yet.
837534×
            if !self.swap_head(&r, None)? {
8382×
                return fail(format!(
839
                    "{} already holds a repository's operation log",
8402×
                    self.store.backend().describe()
841
                ));
842532×
            }
843532×
            return Ok(r);
844
        };
8452905×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8462905×
        for _ in 0..HEAD_TRIES {
8472905×
            let (current, version) = self.read_head()?;
8482905×
            let to = if current == *parent {
8492895×
                r
850
            } else {
85110×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
8529×
                let merged = Op {
85310×
                    parents: vec![current, r],
85410×
                    hlc: Hlc::now(),
85510×
                    command: format!("{command} (merged with a concurrent operation)"),
85610×
                    view: self.merge_views(&base, &op.view, &theirs)?,
8579×
                    workspace: Some(self.workspace),
8589×
                    undoes: None,
859
                };
8609×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
8619×
                self.store.flush()?;
8629×
                m
863
            };
8642904×
            if self.swap_head(&to, version.as_ref())? {
8652898×
                return Ok(to);
8660×
            }
867
        }
8680×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8693444×
    }
870
871
    /// The operation head's lock, held only while the head pointer moves.
8723441×
    fn lock_ops(&self) -> Result<FileLock> {
8733441×
        fs::create_dir_all(self.oxy.join("ops"))?;
8743441×
        FileLock::acquire(
8753441×
            self.oxy.join("ops").join("lock"),
8763441×
            "another oxy process holds the operation log",
877
        )
8783441×
    }
879
88014122×
    fn head_ref(&self) -> Result<ObjectRef> {
88114122×
        Ok(self.read_head()?.0)
88214122×
    }
883
884
    /// The operation head, and on a store its record's version for
885
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
886
    /// any other store (a bucket, or memory in tests) it is the store's
887
    /// [`HEAD_RECORD`] reference record (oxygen#68).
88817116×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
88917116×
        if self.store.is_local() {
89017097×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
89117097×
            let r = ObjectRef::from_hex(hex.trim())
89217097×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
89317094×
            return Ok((r, None));
89419×
        }
89519×
        let backend = self.store.backend();
89619×
        match backend.read_ref(HEAD_RECORD) {
89719×
            Ok(Some((bytes, version))) => {
89819×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
8990×
                    || {
9000×
                        RepoError::Msg(format!(
9010×
                            "the operation head in {} is corrupt",
9020×
                            backend.describe()
9030×
                        ))
9040×
                    },
9050×
                )?;
90619×
                Ok((r, Some(version)))
907
            }
9080×
            Ok(None) => fail(format!(
909
                "{} holds no operation log (no {HEAD_RECORD} record)",
9100×
                backend.describe()
911
            )),
9120×
            Err(e) => fail(format!("read the operation head: {e}")),
913
        }
91417116×
    }
915
916
    /// Move the operation head to `to` from the `expected` version
917
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
918
    /// disk the caller holds the operations lock and the head always
919
    /// moves; on a store it moves only if the record is unchanged, and
920
    /// `false` says another process moved it first.
9213451×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
9223451×
        if self.store.is_local() {
9233441×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
9243435×
            return Ok(true);
92510×
        }
92610×
        match self
92710×
            .store
92810×
            .backend()
92910×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
930
        {
9317×
            Ok(_) => Ok(true),
9323×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
9330×
            Err(e) => fail(format!("move the operation head: {e}")),
934
        }
9353451×
    }
936
937
    /// Three-way merge of two views that both started from `base` (spec
938
    /// §12.1). A reference only one side changed takes that side's value.
939
    /// When both changed it differently: a bookmark keeps both sides'
940
    /// heads (it may then have several), a change beats a deletion, a
941
    /// workspace changed by both is an error (only one of them matches the
942
    /// files on disk), and otherwise this process's value wins for remote
943
    /// references and the policy, the first value for a tag (tags never
944
    /// move).
94510×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
94634×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
94734×
            b: &BTreeMap<K, V>,
94834×
            o: &BTreeMap<K, V>,
94934×
            t: &BTreeMap<K, V>,
95034×
            mut both: impl FnMut(&V, &V) -> Result<V>,
95134×
        ) -> Result<BTreeMap<K, V>> {
95234×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
95334×
            let mut out = BTreeMap::new();
95435×
            for k in keys {
95535×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
95635×
                let v = if ov == tv || tv == bv {
95718×
                    ov.cloned()
95817×
                } else if ov == bv {
95910×
                    tv.cloned()
960
                } else {
9617×
                    match (ov, tv) {
9627×
                        (Some(x), Some(y)) => Some(both(x, y)?),
9630×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
9640×
                        (None, None) => None,
965
                    }
966
                };
96734×
                if let Some(v) = v {
96834×
                    out.insert(k.clone(), v);
96934×
                }
970
            }
97133×
            Ok(out)
97234×
        }
97310×
        let bookmarks = pick(
97410×
            &base.bookmarks,
97510×
            &ours.bookmarks,
97610×
            &theirs.bookmarks,
9776×
            |x, y| {
9786×
                let mut heads = self.store.get_state(x)?.heads;
9796×
                heads.extend(self.store.get_state(y)?.heads);
9806×
                let heads = self.load_state(&heads)?.maximal(&heads);
9816×
                Ok(self.store.put_state(&StateObject::new(heads))?)
9826×
            },
9830×
        )?;
984
        // Two operations that both replaced one workspace's working copy
985
        // cannot both be right: the files on disk match only one of them.
986
        // The working-copy lock keeps this from happening; should it happen
987
        // anyway, this operation is not recorded.
98810×
        let workspaces = pick(
98910×
            &base.workspaces,
99010×
            &ours.workspaces,
99110×
            &theirs.workspaces,
9921×
            |_, _| {
9931×
                fail(
994
                    "another oxy process changed this working copy at the same time; \
995
                     this command was not recorded: check `oxy status` and run it again",
996
                )
9971×
            },
9981×
        )?;
9999×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
10009×
        let empty = BTreeMap::new();
10019×
        let names: BTreeSet<&String> = base
10029×
            .remotes
10039×
            .keys()
10049×
            .chain(ours.remotes.keys())
10059×
            .chain(theirs.remotes.keys())
10069×
            .collect();
10079×
        let mut remotes = BTreeMap::new();
10089×
        for n in names {
10095×
            let m = pick(
10105×
                base.remotes.get(n).unwrap_or(&empty),
10115×
                ours.remotes.get(n).unwrap_or(&empty),
10125×
                theirs.remotes.get(n).unwrap_or(&empty),
10130×
                |x, _| Ok(*x),
10140×
            )?;
10155×
            if !m.is_empty() {
10165×
                remotes.insert(n.clone(), m);
10175×
            }
1018
        }
10199×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
10209×
            ours.policy
10210×
        } else if ours.policy == base.policy {
10220×
            theirs.policy
1023
        } else {
10240×
            ours.policy.or(theirs.policy)
1025
        };
10269×
        self.store.flush()?;
10279×
        Ok(View {
10289×
            bookmarks,
10299×
            workspaces,
10309×
            remotes,
10319×
            policy,
10329×
            tags,
10339×
        })
103410×
    }
1035
103648×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
103748×
        let mut out = Vec::new();
103848×
        let (mut r, mut op) = self.head_op()?;
1039
        loop {
1040261×
            let next = op.parents.first().copied();
1041261×
            out.push((r, op));
1042261×
            match next {
1043213×
                Some(p) => {
1044213×
                    r = p;
1045213×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1046
                }
104748×
                None => break,
1048
            }
1049
        }
105048×
        Ok(out)
105148×
    }
1052
1053
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1054
    ///
1055
    /// The command undone is the newest one this workspace ran: operations
1056
    /// that only recorded a working-copy snapshot are skipped (the files are
1057
    /// still on disk and the next snapshot recreates them), as are pushes
1058
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1059
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1060
    /// operations are never undone, and a command an earlier undo already
1061
    /// reverted is passed over, so undoing again goes further back.
1062
    ///
1063
    /// When nothing newer came from another workspace, the operation head
1064
    /// moves back to before the command. Otherwise the command is reverted
1065
    /// in place: every reference it changed goes back to its value before
1066
    /// it, recorded as a new operation that names it, and anything another
1067
    /// workspace changed since is kept. A reference both the command and a
1068
    /// later operation of another workspace changed is not guessed at: the
1069
    /// undo is refused, naming it.
1070
    ///
1071
    /// When the working copy is clean and was clean after the command's
1072
    /// predecessor, its files follow too, since nothing on disk can be
1073
    /// lost; otherwise they stay as they are (an undone commit's edits come
1074
    /// back as uncommitted work).
107516×
    pub fn undo(&self) -> Result<Undone> {
107616×
        let _wc = self.lock_working_copy()?;
107716×
        let clean_now =
107816×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
107916×
        let (head_ref, head) = self.head_op()?;
108016×
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
108140×
        let load = |r: &ObjectRef| -> Result<Op> {
108240×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
108340×
        };
108416×
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
108516×
        let mut pending_checkout: Option<Op> = None;
108616×
        let mut others = 0usize;
108716×
        let (mut r, mut op) = (head_ref, head.clone());
108815×
        let (target_ref, target, parent) = loop {
108941×
            let parent = match op.parents.first() {
109040×
                Some(p) => Some((*p, load(p)?)),
10911×
                None => None,
1092
            };
109341×
            if skip.contains(&r) {
10941×
                pending_checkout = None;
109540×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
109610×
                // A push cannot be taken back: undoing it would only make
109710×
                // this repository forget what the remote holds.
109830×
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
109910×
                others += 1;
110020×
            } else if let Some(u) = op.undoes {
11011×
                skip.insert(u);
11021×
                pending_checkout = None;
110319×
            } else if op.command.ends_with(" (checkout)") {
11043×
                pending_checkout = Some(op.clone());
11053×
            } else {
110616×
                match parent {
110715×
                    Some((_, p)) => break (r, op, p),
11081×
                    None => return fail("nothing to undo in this workspace"),
1109
                }
1110
            }
111125×
            match parent {
111225×
                Some((pr, p)) => (r, op) = (pr, p),
11130×
                None => return fail("nothing to undo in this workspace"),
1114
            }
1115
        };
111615×
        let before = parent.view;
111715×
        let after = pending_checkout
111815×
            .map(|o| o.view)
111915×
            .unwrap_or_else(|| target.view.clone());
112015×
        let changes = self.view_changes(&before, &after)?;
112115×
        let pushed = self.pushed_by(&before, &after, &head.view)?;
112215×
        let restored_wc = before.workspaces.get(&self.workspace).copied();
112315×
        if others == 0 {
1124
            // Only this workspace's operations since: move the head back.
112510×
            let _lock = if self.store.is_local() {
112610×
                Some(self.lock_ops()?)
1127
            } else {
11280×
                None
1129
            };
113010×
            let parent_ref = *target.parents.first().expect("the target has a parent");
113110×
            let (now, version) = self.read_head()?;
113210×
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
11330×
                return fail("another oxy command ran while undoing; run undo again");
113410×
            }
1135
        } else {
11365×
            let view = self.revert_view(&head.view, &before, &after)?;
11373×
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1138
        }
113913×
        self.drop_manifest();
114013×
        if let Some(then) = restored_wc {
114113×
            if clean_now && Some(then) != wc_now {
1142
                // Past `core.snapshot-retention` the working copy may be
1143
                // gone: the files then stay as they are.
114410×
                let Ok(wc) = self.store.get_change(&then) else {
11450×
                    return Ok(Undone {
11460×
                        command: target.command,
11470×
                        changes,
11480×
                        others_kept: others,
11490×
                        pushed,
11500×
                    });
1151
                };
115210×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
11538×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1154
                    // The files differ from the restored working copy by
1155
                    // exactly what the undone command did: nothing else is
1156
                    // on disk, as the working copy was clean.
11578×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
11582×
                }
11593×
            }
11600×
        }
116113×
        Ok(Undone {
116213×
            command: target.command,
116313×
            changes,
116413×
            others_kept: others,
116513×
            pushed,
116613×
        })
116716×
    }
1168
1169
    /// Whether operation `op` was a push: it changed only what this
1170
    /// repository knows of remotes.
117131×
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
117231×
        let Some(p) = parent else {
11731×
            return false;
1174
        };
117530×
        op.command.starts_with("oxy push")
11761×
            && op.view.bookmarks == p.view.bookmarks
11771×
            && op.view.tags == p.view.tags
11781×
            && op.view.workspaces == p.view.workspaces
11791×
            && op.view.policy == p.view.policy
118031×
    }
1181
1182
    /// Whether operation `op` (whose predecessor is `parent`) was this
1183
    /// workspace's. Operations record their workspace (oxygen#99); for older
1184
    /// ones it is read from the view: one that changed only other
1185
    /// workspaces' working copies was theirs, anything else counts as ours.
118630×
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
118730×
        if let Some(w) = op.workspace {
118830×
            return w == self.workspace;
11890×
        }
11900×
        let Some(p) = parent else {
11910×
            return true;
1192
        };
11930×
        let ids: BTreeSet<&WorkspaceId> = op
11940×
            .view
11950×
            .workspaces
11960×
            .keys()
11970×
            .chain(p.view.workspaces.keys())
11980×
            .collect();
11990×
        let moved: Vec<&WorkspaceId> = ids
12000×
            .into_iter()
12010×
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
12020×
            .collect();
12030×
        moved.is_empty() || moved.contains(&&self.workspace)
120430×
    }
1205
1206
    /// `current` with what changed from `before` to `after` put back, this
1207
    /// workspace's working copy included; refused when a later operation
1208
    /// changed one of the same references again.
12095×
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
121010×
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
121110×
            cur: &mut BTreeMap<K, V>,
121210×
            before: &BTreeMap<K, V>,
121310×
            after: &BTreeMap<K, V>,
121410×
            name: impl Fn(&K) -> String,
121510×
            clashes: &mut Vec<String>,
121610×
        ) {
121710×
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
121810×
            for k in keys {
12195×
                let (b, a) = (before.get(k), after.get(k));
12205×
                if a == b {
12214×
                    continue;
12221×
                }
12231×
                if cur.get(k) != a {
12241×
                    clashes.push(name(k));
12251×
                    continue;
12260×
                }
12270×
                match b {
12280×
                    Some(v) => cur.insert(k.clone(), v.clone()),
12290×
                    None => cur.remove(k),
1230
                };
1231
            }
123210×
        }
12335×
        let mut out = current.clone();
12345×
        let mut clashes = Vec::new();
1235
        // A bookmark another workspace moved since is put back head by
1236
        // head: the heads the command added go, the heads it replaced
1237
        // return, and the other workspace's heads stay. Only when a later
1238
        // change was built on one the command added is that not possible.
12395×
        let names: BTreeSet<&String> = before
12405×
            .bookmarks
12415×
            .keys()
12425×
            .chain(after.bookmarks.keys())
12435×
            .collect();
12448×
        for name in names {
12458×
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
12468×
            let cur = current.bookmarks.get(name);
12478×
            if a == b {
12484×
                continue;
12494×
            }
12504×
            if cur == a {
12512×
                match b {
12522×
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
12530×
                    None => out.bookmarks.remove(name),
1254
                };
12552×
                continue;
12562×
            }
12572×
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
12580×
                clashes.push(format!("bookmark {name}"));
12590×
                continue;
1260
            };
12612×
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
12622×
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
12632×
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
12642×
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
12652×
            if !added.iter().all(|h| now.contains(h)) {
12661×
                clashes.push(format!(
1267
                    "bookmark {name} (a later change builds on this one)"
1268
                ));
12691×
                continue;
12701×
            }
12711×
            let mut heads: Vec<ChangeHash> = now
12721×
                .iter()
12733×
                .filter(|h| !added.contains(h))
12741×
                .chain(was.difference(&became))
12751×
                .copied()
12761×
                .collect();
12771×
            heads.sort();
12781×
            heads.dedup();
12791×
            let heads = self.load_state(&heads)?.maximal(&heads);
12801×
            out.bookmarks.insert(
12811×
                name.clone(),
12821×
                self.store.put_state(&StateObject::new(heads))?,
1283
            );
1284
        }
1285
12865×
        back(
12875×
            &mut out.tags,
12885×
            &before.tags,
12895×
            &after.tags,
12900×
            |k| format!("tag {k}"),
12915×
            &mut clashes,
1292
        );
12935×
        let mine = self.workspace;
129415×
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
129515×
            v.workspaces
129615×
                .iter()
129729×
                .filter(|(k, _)| **k != mine)
129815×
                .map(|(k, v)| (*k, *v))
129915×
                .collect()
130015×
        };
13015×
        let mut theirs = others(&out);
13025×
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
13031×
            Some(p) => format!("the workspace at {}", p.display()),
13040×
            None => format!("workspace {}", id.to_hex()),
13051×
        };
13065×
        back(
13075×
            &mut theirs,
13085×
            &others(before),
13095×
            &others(after),
13105×
            workspace_name,
13115×
            &mut clashes,
1312
        );
13135×
        let empty = BTreeMap::new();
13145×
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
13155×
        for n in names {
13160×
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
13170×
            back(
13180×
                &mut cur,
13190×
                before.remotes.get(n).unwrap_or(&empty),
13200×
                after.remotes.get(n).unwrap_or(&empty),
13210×
                |k| format!("{n}/{k}"),
13220×
                &mut clashes,
1323
            );
13240×
            if cur.is_empty() {
13250×
                out.remotes.remove(n);
13260×
            } else {
13270×
                out.remotes.insert(n.clone(), cur);
13280×
            }
1329
        }
13305×
        if before.policy != after.policy {
13310×
            if out.policy == after.policy {
13320×
                out.policy = before.policy;
13330×
            } else {
13340×
                clashes.push("the policy".into());
13350×
            }
13365×
        }
13375×
        if !clashes.is_empty() {
13382×
            return fail(format!(
1339
                "undo would also take back what another workspace has done since to {}; \
1340
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
13412×
                clashes.join(", ")
1342
            ));
13433×
        }
13443×
        out.workspaces = theirs;
13453×
        match before.workspaces.get(&mine) {
13463×
            Some(wc) => out.workspaces.insert(mine, *wc),
13470×
            None => out.workspaces.remove(&mine),
1348
        };
13493×
        Ok(out)
13505×
    }
1351
1352
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1353
    /// in `now` already holds: undoing them locally leaves them there.
135415×
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
135515×
        let mut out = Vec::new();
135618×
        for (name, st) in &after.bookmarks {
135718×
            if before.bookmarks.get(name) == Some(st) {
13584×
                continue;
135914×
            }
136014×
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
136114×
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
13620×
                None => BTreeSet::new(),
1363
            };
136414×
            let added: Vec<ChangeHash> = self
136514×
                .store
136614×
                .get_state(st)?
1367
                .heads
136814×
                .into_iter()
136920×
                .filter(|h| !had.contains(h))
137014×
                .collect();
137114×
            if added.is_empty() {
13721×
                continue;
137313×
            }
137413×
            for (remote, bookmarks) in &now.remotes {
13751×
                if let Some(rs) = bookmarks.get(name) {
13761×
                    let theirs = self.store.get_state(rs)?.heads;
13771×
                    if added.iter().any(|h| theirs.contains(h)) {
13781×
                        out.push((name.clone(), remote.clone()));
13791×
                    }
13800×
                }
1381
            }
1382
        }
138315×
        Ok(out)
138415×
    }
1385
1386
    /// The last operation that was not a snapshot.
13872×
    pub fn last_command(&self) -> Result<Op> {
13882×
        let (_, mut op) = self.head_op()?;
13894×
        while op.is_snapshot() {
13902×
            let Some(parent) = op.parents.first() else {
13910×
                break;
1392
            };
13932×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1394
        }
13952×
        Ok(op)
13962×
    }
1397
1398
    // ------------------------------------------------------------ states
1399
1400
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1401201×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1402201×
        if let Some(st) = self.load_state_checkpointed(heads)? {
14034×
            return Ok(st);
1404196×
        }
1405196×
        self.load_state_full(heads)
1406201×
    }
1407
1408
    /// The state of `heads` for its history (changes, tree, metadata) with
1409
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1410
    /// and friends. Build the graphs a command needs with
1411
    /// [`Repo::load_graphs_of`].
14121738×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
14131738×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
141431×
            return Ok(st);
14151707×
        }
14161707×
        self.load_state_replayed(heads, State::new_history_only())
14171738×
    }
1418
1419
    /// Build these file graphs in a history-only state.
14201831×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
14211831×
        state
14221831×
            .load_graphs(
14231831×
                nodes,
142454×
                |refs| {
142554×
                    self.read_blobs(refs).map_err(|e| {
14263×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14273×
                    })
142854×
                },
14292063×
                |h| self.change_bytes(h),
1430
            )
14311831×
            .map_err(|e| self.index_damage(e))
14321831×
    }
1433
1434
    /// An error building graphs, and when it is a state index found
1435
    /// damaged (a file's history that does not match its hash), the
1436
    /// workspace's state indexes removed: they are rebuilt from history by
1437
    /// the next command.
14384×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
14394×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
14403×
            return e.into();
1441
        };
14422×
        for path in self.state_indexes() {
14432×
            let _ = fs::remove_file(path);
14442×
        }
14451×
        RepoError::Msg(format!(
14461×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
14471×
        ))
14484×
    }
1449
1450
    /// The graphs of `nodes` of a history-only state, built beside it (see
1451
    /// [`State::build_graphs_detached`]).
145277×
    pub fn build_graphs_detached(
145377×
        &self,
145477×
        state: &State,
145577×
        nodes: &[crate::ids::NodeId],
145677×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
145777×
        Ok(state
145877×
            .build_graphs_detached(
145977×
                nodes,
14600×
                |refs| {
14610×
                    self.read_blobs(refs).map_err(|e| {
14620×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14630×
                    })
14640×
                },
146583×
                |h| self.change_bytes(h),
1466
            )
146777×
            .map_err(|e| self.index_damage(e))?
146877×
            .into_iter()
146977×
            .collect())
147077×
    }
1471
1472
    /// The contents of texts [`State::single_text`] gave: blobs read in
1473
    /// one go, inline ones from their changes.
1474364×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1475
        use crate::objects::TextRef;
1476364×
        let refs: Vec<ObjectRef> = texts
1477364×
            .iter()
14785574×
            .filter_map(|t| match t {
14791×
                TextRef::Blob(r, _, _) => Some(*r),
14805573×
                TextRef::Inline { .. } => None,
14815574×
            })
1482364×
            .collect();
1483364×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1484364×
        let mut out = Vec::with_capacity(texts.len());
14855574×
        for t in texts {
14865574×
            let lines = match t {
14871×
                TextRef::Blob(_, count, form) => {
14881×
                    let content = blobs
14891×
                        .next()
14901×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
14911×
                    crate::objects::text_lines(&content, *count, *form)?
1492
                }
14935573×
                TextRef::Inline { change, start, end } => {
14945573×
                    let bytes = self.change_bytes(change)?;
14955573×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
14960×
                        RepoError::Msg("an inline insert lies outside its change".into())
14970×
                    })?;
14985573×
                    crate::objects::inline_lines(range)?
1499
                }
1500
            };
15015574×
            out.push(lines.bytes().to_vec());
1502
        }
1503364×
        Ok(out)
1504364×
    }
1505
1506
    /// Build every graph a history-only state still lacks, making it full.
15071852×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
15081852×
        state
15091852×
            .load_all_graphs(
151016×
                |refs| {
151116×
                    self.read_blobs(refs).map_err(|e| {
15120×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15130×
                    })
151416×
                },
15153864×
                |h| self.change_bytes(h),
1516
            )
15171852×
            .map_err(|e| self.index_damage(e))
15181852×
    }
1519
1520
    /// A change's encoding, for building graphs of its inline inserts. The
1521
    /// last few read are kept: a checkout building graphs a batch at a
1522
    /// time reads the same large changes for every batch, often in turn.
152311583×
    fn change_bytes(
152411583×
        &self,
152511583×
        h: &ChangeHash,
152611583×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
152711583×
        let mut cache = self.last_change.borrow_mut();
152819891×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
15299087×
            let hit = cache.remove(i);
15309087×
            let b = hit.1.clone();
15319087×
            cache.push(hit);
15329087×
            return Ok(b);
15332496×
        }
15342496×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
15350×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
15360×
        })?);
15372496×
        cache.push((*h, b.clone()));
1538
        // The last few, within a memory budget; the newest always stays.
15394006×
        while cache.len() > CHANGE_CACHE_COUNT
15402496×
            || (cache.len() > 1
15417435×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15421510×
        {
15431510×
            cache.remove(0);
15441510×
        }
15452496×
        Ok(b)
154611583×
    }
1547
1548
    /// Load the dependency closure of `heads` change by change.
1549250×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1550250×
        self.load_state_replayed(heads, State::new())
1551250×
    }
1552
15533337×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
15543337×
        let history = state.is_history_only();
15553337×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
15563337×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1557
        {
15583337×
            let _t = crate::timing::phase("load: read and add changes");
15593337×
            let (mut read, mut add, mut fetch) = (
15603337×
                std::time::Duration::ZERO,
15613337×
                std::time::Duration::ZERO,
15623337×
                std::time::Duration::ZERO,
15633337×
            );
156413399×
            while let Some(h) = stack.pop() {
1565
                // A change the state holds brings its history with it.
156610065×
                if !seen.insert(h) || state.contains(&h) {
15672377×
                    continue;
15687688×
                }
15697688×
                let t0 = std::time::Instant::now();
1570
                // A history-only state reads text only for the graphs it
1571
                // builds; either way the hash is the one asked for.
15727688×
                let (c, texts) = if history {
15736406×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
15746405×
                    fetch += t0.elapsed();
15756405×
                    Change::decode_skeleton(&bytes, h)
15766405×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1577
                } else {
15781282×
                    (self.store.get_change(&h)?, Vec::new())
1579
                };
15807685×
                read += t0.elapsed();
15817685×
                stack.extend(c.deps.iter().copied());
15827685×
                let t1 = std::time::Instant::now();
15837685×
                state.add_known(h, c, texts);
15847685×
                add += t1.elapsed();
1585
            }
15863334×
            crate::timing::record("load:   of which reading", read);
15873334×
            crate::timing::record("load:     of which fetching", fetch);
15883334×
            crate::timing::record("load:   of which applying", add);
1589
        }
15903334×
        let _t = crate::timing::phase("load: validate");
15913334×
        state.validate()?;
15923334×
        Ok(state)
15933337×
    }
1594
15952382×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
15962382×
        if self.bare {
15972×
            return fail("this is a bare repository: it has no working copy");
15982380×
        }
15992380×
        let view = self.view()?;
16002380×
        let h = *view
16012380×
            .workspaces
16022380×
            .get(&self.workspace)
16032380×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
16042379×
        Ok((h, self.store.get_change(&h)?))
16052382×
    }
1606
1607
    /// Heads of a bookmark's state (spec §10.1).
16081810×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
16091810×
        match view.bookmarks.get(bookmark) {
16101810×
            Some(st) => Ok(self.store.get_state(st)?.heads),
16110×
            None => Ok(vec![]),
1612
        }
16131810×
    }
1614
1615513×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1616513×
        self.heads_of(&self.view()?, &self.config.bookmark)
1617513×
    }
1618
1619
    // ------------------------------------------------------------ blobs
1620
1621399×
    fn blob_for(content: &[u8]) -> Blob {
1622399×
        Blob::of(content)
1623399×
    }
1624
1625246×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1626246×
        Self::blob_for(content).hash()
1627246×
    }
1628
1629151×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1630194×
        for c in crate::chunk::chunks(content) {
1631194×
            self.store.put_chunk(c)?;
1632
        }
1633151×
        Ok(self
1634151×
            .store
1635151×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1636151×
    }
1637
1638
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1639
    /// all their chunks, are read in parallel; a blob the store lacks goes
1640
    /// through [`Repo::read_blob`], which may fetch it lazily.
1641438×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1642438×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1643438×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
164480×
            blobs.push(match got {
164575×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
16460×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
16475×
                Err(crate::store::StoreError::NotFound(_)) => None,
16480×
                Err(e) => return Err(e.into()),
1649
            });
1650
        }
1651438×
        let chunk_refs: Vec<ObjectRef> = blobs
1652438×
            .iter()
1653438×
            .flatten()
1654438×
            .flat_map(|b| b.chunks.iter().copied())
1655438×
            .collect();
1656438×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1657438×
        let mut out = Vec::with_capacity(refs.len());
1658438×
        for (r, blob) in refs.iter().zip(blobs) {
165980×
            match blob {
16605×
                None => out.push(self.read_blob(r)?),
166175×
                Some(b) => {
166275×
                    let mut content = Vec::with_capacity(b.length as usize);
1663114×
                    for c in &b.chunks {
1664114×
                        match chunks.next() {
1665114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
16660×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
16670×
                            Some(Err(e)) => return Err(e.into()),
16680×
                            None => return fail("chunk list ended early"),
1669
                        }
1670
                    }
167175×
                    out.push(content);
1672
                }
1673
            }
1674
        }
1675433×
        Ok(out)
1676438×
    }
1677
1678
    /// Read a blob's content, fetching it from the remote that withheld it
1679
    /// when it is lazily absent (spec §13.5).
1680113×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1681113×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
16824×
            self.fetch_lazy_blob(r)?;
1683109×
        }
1684113×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1685108×
        let mut out = Vec::with_capacity(blob.length as usize);
1686135×
        for c in &blob.chunks {
1687135×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1688
        }
1689108×
        Ok(out)
1690113×
    }
1691
1692
    // ------------------------------------------------------------ working copy
1693
1694
    /// Attributes from the `.oxyattributes` files in the working directory.
16952×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1696
        // Nested repositories and ignored paths are left out, as in a walk.
16978×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
16982×
        let files: Vec<(String, Vec<u8>)> = listing
16992×
            .files
17002×
            .into_iter()
17012×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
17022×
            .collect();
17032×
        crate::attributes::Attributes::from_files(
17042×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1705
        )
17062×
    }
1707
1708
    /// Folders holding a repository of their own that the last look at the
1709
    /// working copy left out, not being subrepos (oxygen#43).
171029×
    pub fn untracked_nested(&self) -> Vec<String> {
171129×
        self.untracked_nested.borrow().clone()
171229×
    }
1713
1714
    /// New untracked files the last snapshot left out for being larger than
1715
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
171633×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
171733×
        self.skipped_large.borrow().clone()
171833×
    }
1719
1720
    /// Attributes from a materialized state's `.oxyattributes` files.
17213×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
17226×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
17236×
            match &f.content {
17246×
                FileContent::Text { bytes, .. }
17256×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1726
                {
17270×
                    Some((p.as_str(), bytes.as_slice()))
1728
                }
17296×
                _ => None,
1730
            }
17316×
        }))
17323×
    }
1733
1734
    /// Store a blob, raw when the path is `nocompress`.
1735132×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1736132×
        if !nocompress {
1737130×
            return self.store_blob(content);
17382×
        }
17392×
        for c in crate::chunk::chunks(content) {
17402×
            self.store.put_chunk_nocompress(c)?;
1741
        }
17422×
        Ok(self
17432×
            .store
17442×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1745132×
    }
1746
1747
    /// This workspace's state index (oxygen#41): its working copy's base,
1748
    /// saved so a snapshot reads it rather than replaying history.
1749
    /// The state index of the state with these heads: this workspace keeps
1750
    /// the last few it used, named by their heads, so moving between two
1751
    /// states finds both.
17522475×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
17532475×
        let mut heads = heads.to_vec();
17542475×
        heads.sort();
17552475×
        let mut h = blake3::Hasher::new();
17562476×
        for c in &heads {
17572476×
            h.update(&c.0);
17582476×
        }
17592475×
        self.oxy.join("index").join(format!(
17602475×
            "{}{}",
17612475×
            self.state_index_prefix(),
17622475×
            &h.finalize().to_hex()[..16]
17632475×
        ))
17642475×
    }
1765
17664848×
    fn state_index_prefix(&self) -> String {
17674848×
        format!("state-{}-", self.workspace.to_hex())
17684848×
    }
1769
1770
    /// This workspace's state indexes, newest first.
17712373×
    fn state_indexes(&self) -> Vec<PathBuf> {
17722373×
        let prefix = self.state_index_prefix();
17732373×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
17742373×
            .into_iter()
17752373×
            .flatten()
17762373×
            .flatten()
17772373×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
17782373×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
17792373×
            .collect();
17802373×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
17812373×
        found.into_iter().map(|(_, p)| p).collect()
17822373×
    }
1783
1784
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1785
    /// from this workspace's state index when it holds that history: every
1786
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1787
    /// is loaded from history and indexed for next time.
17882064×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
17892064×
        if let Some((st, heads)) = self.read_state_index(deps) {
17901661×
            let mut have = st.maximal(deps);
17911661×
            have.sort();
17921661×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1793
                // Re-encoding reads every history: one found damaged is
1794
                // left to the build that reads it, which reports it.
1795
                #[cfg(test)]
1796168×
                if let Some(mine) = st.write_index() {
1797167×
                    assert_eq!(
1798167×
                        Some(mine),
1799167×
                        self.load_state_history(deps)?.write_index(),
1800
                        "a state index holds the state history gives"
1801
                    );
18021×
                }
1803281×
                return Ok(st);
18041380×
            }
1805
            // An index a few changes behind (a commit, a pull since): add
1806
            // what it lacks, as long as all it holds is history of `deps`.
1807
            // Anything amiss (a change beyond a shallow boundary) takes the
1808
            // long way instead.
18091380×
            let (indexed, started) = (st.len(), std::time::Instant::now());
18101380×
            if let Ok(st) = self.load_state_replayed(deps, st) {
18111379×
                let mut all = deps.to_vec();
18121379×
                all.extend(heads.iter().copied());
18131379×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
18141379×
                within.sort();
18151379×
                want.sort();
18161379×
                if within == want {
1817
                    #[cfg(test)]
1818705×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1819
                    // Writing the index costs far more than replaying a
1820
                    // few small changes: it is rewritten once it falls
1821
                    // behind, or when replaying took long (large changes).
18221377×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
18231377×
                        || started.elapsed() > INDEX_REPLAY_TIME
18244×
                    {
18254×
                        self.write_state_index(deps, &st);
18261373×
                    }
18271377×
                    return Ok(st);
18282×
                }
18291×
            }
1830403×
        }
1831406×
        let st = self.load_state_history(deps)?;
1832406×
        self.write_state_index(deps, &st);
1833406×
        Ok(st)
18342064×
    }
1835
1836
    /// Two history-only states hold the same changes and render the same
1837
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1838
    /// the checkpoint's graphs as the bases of its files' histories.
1839
    #[cfg(test)]
1840705×
    fn assert_same_state(&self, a: &State, b: &State) {
18411410×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1842705×
        assert_eq!(ids(a), ids(b), "the same changes");
18431410×
        let files = |s: &State| {
18441410×
            let mut s = s.clone();
18451410×
            self.load_all_graphs(&mut s).unwrap();
18461410×
            s.materialize().files
18471410×
        };
1848705×
        assert_eq!(files(a), files(b), "the same files");
1849705×
    }
1850
1851
    /// The state index file: its heads, a hash of its changes block and one
1852
    /// of the rest, then the body [`State::write_index`] gives, whose first
1853
    /// block is the changes. Hashed in two parts so the log can read and
1854
    /// check the changes alone.
1855
    /// The index of `deps` if there is one, else the newest, which the
1856
    /// caller may bring up to date.
18572064×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1858
        use std::io::Read;
18592064×
        let _t = crate::timing::phase("load: state index");
18602064×
        let exact = self.state_index_path(deps);
18612064×
        let reading = crate::timing::phase("load:   of which reading the file");
18622064×
        let mut f = match fs::File::open(&exact) {
1863281×
            Ok(f) => {
1864
                // Used now: the newest, so the last to be dropped.
1865281×
                let _ = fs::File::options()
1866281×
                    .write(true)
1867281×
                    .open(&exact)
1868281×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1869281×
                f
1870
            }
18711783×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1872
        };
18731661×
        let total = f.metadata().ok()?.len();
18741661×
        let mut word = [0u8; 4];
18751661×
        f.read_exact(&mut word).ok()?;
18761661×
        let n = u32::from_le_bytes(word) as usize;
18771661×
        let mut head = vec![0u8; 32 * n + 64 + 8];
18781661×
        f.read_exact(&mut head).ok()?;
18791661×
        let heads: Vec<ChangeHash> = head[..32 * n]
18801661×
            .chunks_exact(32)
18811661×
            .map(|c| ObjectRef(c.try_into().unwrap()))
18821661×
            .collect();
18831661×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
18841661×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
18851661×
        let at = (4 + head.len()) as u64;
18861661×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
18870×
            return None;
18881661×
        }
1889
        // The front only: the files' histories after it are read, each
1890
        // checked by its own hash, when a command builds that file.
18911661×
        let mut front = vec![0u8; front_len as usize];
18921661×
        f.read_exact(&mut front).ok()?;
18931661×
        drop(reading);
18941661×
        let checking = crate::timing::phase("load:   of which checking the file");
18951661×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
18961661×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
18973322×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
18981661×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
18990×
            return None;
19001661×
        }
19011661×
        drop(checking);
19021661×
        let histories = crate::state::Histories::File(
19031661×
            std::sync::Arc::new(f),
19041661×
            at + front_len,
19051661×
            total - at - front_len,
19061661×
        );
19071661×
        Some((State::read_index_front(&front, histories).ok()?, heads))
19082064×
    }
1909
1910
    /// The changes of this workspace's state index (the closure of its
1911
    /// heads), read without the rest of the index.
1912
    #[allow(clippy::type_complexity)]
1913177×
    pub(crate) fn read_state_index_changes(
1914177×
        &self,
1915177×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1916
        use std::io::Read;
1917177×
        let _t = crate::timing::phase("load: state index changes");
1918177×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1919160×
        let mut word = [0u8; 4];
1920160×
        f.read_exact(&mut word).ok()?;
1921160×
        let n = u32::from_le_bytes(word) as usize;
1922
        // Heads, the two sums, the front's length, then the changes block.
1923160×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1924160×
        f.read_exact(&mut head).ok()?;
1925160×
        let heads: Vec<ChangeHash> = head[..32 * n]
1926160×
            .chunks_exact(32)
1927160×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1928160×
            .collect();
1929160×
        let sum = &head[32 * n..32 * n + 32];
1930160×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1931160×
        let mut changes = vec![0u8; 4 + len];
1932160×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1933160×
        f.read_exact(&mut changes[4..]).ok()?;
1934160×
        let checking = crate::timing::phase("load:   of which checking");
1935160×
        let mut h = blake3::Hasher::new();
1936160×
        h.update_rayon(&changes);
1937160×
        if h.finalize().as_bytes() != sum {
19380×
            return None;
1939160×
        }
1940160×
        drop(checking);
1941160×
        let _decoding = crate::timing::phase("load:   of which decoding");
1942160×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
1943177×
    }
1944
1945
    /// Save `st`, the history-only state of `deps`, as this workspace's
1946
    /// state index; quietly nothing when it cannot be (it is only a cache).
1947411×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1948411×
        let _t = crate::timing::phase("write: state index");
1949411×
        let encoding = crate::timing::phase("write:   of which encoding");
1950411×
        let Some(body) = st.write_index() else {
19510×
            return;
1952
        };
1953411×
        drop(encoding);
1954
        #[cfg(test)]
1955222×
        assert_eq!(
1956222×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1957222×
            Some(body.clone()),
1958
            "a state index reads back as written"
1959
        );
1960411×
        let mut heads = st.maximal(deps);
1961411×
        heads.sort();
1962411×
        let mut w = crate::flat::Writer::default();
1963411×
        w.count(heads.len());
1964411×
        for h in &heads {
196518×
            w.object(h);
196618×
        }
1967
        // The body is the front's length, the front, then the files'
1968
        // histories, which carry their own hashes: the sums cover the
1969
        // front's changes block and the rest of the front.
1970411×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
1971411×
        let front = &body[8..8 + front_len];
1972411×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
1973822×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1974411×
        w.fixed(&sum(&front[..split]));
1975411×
        w.fixed(&sum(&front[split..]));
1976411×
        w.fixed(&body);
1977411×
        let path = self.state_index_path(&heads);
1978411×
        let _ = fs::create_dir_all(self.oxy.join("index"));
1979411×
        let _ = write_cache(&path, &w.0);
1980
        // The last two used: the index of a state moved away from stays for
1981
        // a move back. Older ones (and the unnamed one of before) go.
1982411×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
19831×
            let _ = fs::remove_file(old);
19841×
        }
1985411×
        let _ = fs::remove_file(
1986411×
            self.oxy
1987411×
                .join("index")
1988411×
                .join(format!("state-{}", self.workspace.to_hex())),
1989411×
        );
1990411×
    }
1991
19926×
    fn locks_dir(&self) -> PathBuf {
19936×
        self.oxy.join("locks")
19946×
    }
1995
1996
    /// Whether `path` is locked locally for editing (spec §18, advisory).
19973×
    pub fn is_locked(&self, path: &str) -> bool {
19983×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
19993×
    }
2000
2001
    /// Take the advisory local lock on a `lockable` file and make it writable.
20022×
    pub fn lock_path(&self, path: &str) -> Result<()> {
20032×
        let attrs = self.disk_attributes();
20042×
        if !attrs.lookup(path).lockable {
20051×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
20061×
        }
20071×
        fs::create_dir_all(self.locks_dir())?;
20081×
        write_atomic(
20091×
            &self.locks_dir().join(path.replace('/', "%2F")),
20101×
            std::process::id().to_string().as_bytes(),
20110×
        )?;
20121×
        set_readonly(&self.root.join(path), false)?;
20131×
        Ok(())
20142×
    }
2015
2016
    /// Release the local lock and make the file read-only again.
20171×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
20181×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
20191×
        if self.root.join(path).exists() {
20201×
            set_readonly(&self.root.join(path), true)?;
20210×
        }
20221×
        Ok(())
20231×
    }
2024
2025
    /// Whether a repository path is inside the sparse filter (spec §17).
202628728×
    pub fn in_scope(&self, path: &str) -> bool {
202728728×
        self.config.sparse_paths.is_empty()
202882×
            || self
202982×
                .config
203082×
                .sparse_paths
203182×
                .iter()
203299×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
203328728×
    }
2034
20351×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
20361×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
20371×
    }
2038
2039
    /// Walk the working copy; with a manifest, a file whose size and mtime
2040
    /// match it is not read: an opaque file yields its known blob, and a
2041
    /// text file whose recorded graph key equals its base graph's key in
2042
    /// `keys` (path → key) is marked unchanged; other text files are read
2043
    /// but keep their known hash. Files modified within two seconds of the
2044
    /// manifest are never trusted (a racy stat).
2045
    ///
2046
    /// `.oxyattributes` files are always read, since their content is
2047
    /// needed; and when any of them is not known unchanged (added, removed,
2048
    /// edited, or changed in the base), no text file is taken as unchanged,
2049
    /// because attributes decide how a file compares with the base.
2050
    ///
2051
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2052
    /// (the base state's files) that exists on disk is included even when
2053
    /// an ignore rule matches it, as in Git.
20541320×
    fn walk_working_copy_with(
20551320×
        &self,
20561320×
        cache: Option<&prompt::Manifest>,
20571320×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
20581320×
        keys: Option<&KeyOf>,
20591320×
    ) -> Result<BTreeMap<String, FsEntry>> {
2060
        let mut out: BTreeMap<String, FsEntry>;
20611320×
        let sparse = &self.config.sparse_paths;
206211288×
        let in_scope = |p: &str| {
206311288×
            sparse.is_empty()
20647×
                || sparse
20657×
                    .iter()
20667×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
206711288×
        };
20681320×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2069
        let walk::Listing {
20701320×
            files,
20711320×
            symlinks,
20721320×
            nested,
20731320×
            dirs,
20741320×
        } = match self.listing_cache.take() {
2075176×
            Some(l) => l,
2076
            // Ignore rules apply to untracked paths only, so the base's
2077
            // files are not matched against them (an added file is: a rule
2078
            // written after it was snapshotted leaves it out again).
207911300×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2080
        };
2081
        // A new file larger than the limit is left out and named, not taken
2082
        // in unseen (oxygen#98): a build's output or a downloaded image
2083
        // would otherwise be stored by the next status, kept by the
2084
        // operation log. Files tracked, or already in the working copy, stay.
20851320×
        let limit = self.config.max_new_file;
20861320×
        let mut skipped = Vec::new();
20871320×
        let files: Vec<_> = files
20881320×
            .into_iter()
208914273×
            .filter(|(rel, _, meta)| {
209014273×
                let new = !tracked.contains_key(rel)
20913127×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
209214273×
                if limit > 0 && new && meta.size > limit {
20933×
                    skipped.push((rel.clone(), meta.size));
20943×
                    return false;
209514270×
                }
209614270×
                true
209714273×
            })
20981320×
            .collect();
20991320×
        *self.skipped_large.borrow_mut() = skipped;
21001320×
        let keys = keys.filter(|k| {
210114258×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
21021317×
            let attrs_unchanged =
21031317×
                files
21041317×
                    .iter()
210514239×
                    .filter(|(r, _, _)| is_attributes(r))
21061317×
                    .all(|(rel, _, meta)| {
21079×
                        stat_cached(rel, meta, cache)
21089×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
21099×
                    });
21101317×
            let none_removed = tracked
21111317×
                .keys()
211211243×
                .filter(|r| is_attributes(r))
21131317×
                .all(|r| on_disk.contains(r.as_str()));
21141317×
            attrs_unchanged && none_removed
21151317×
        });
21161320×
        *self.walked_dirs.borrow_mut() =
21171320×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
21181320×
        drop(walk_phase);
21191320×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2120
        // Reading files is most of a walk's cost; do it in parallel.
2121
        {
2122
            use rayon::prelude::*;
21231320×
            let mut read: Vec<(String, FsEntry)> = files
21241320×
                .par_iter()
212514270×
                .map(|(rel, path, meta)| {
2126
                    // A key is worked out only for a file the manifest
2127
                    // knows with the same stat and a key of its own.
212814270×
                    let key = keys
212914270×
                        .filter(|_| !is_attributes(rel))
213014270×
                        .filter(|_| {
213114230×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
213214230×
                        })
213314270×
                        .and_then(|k| k(rel));
213414270×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
213514270×
                })
21361320×
                .collect::<Result<Vec<_>>>()?;
213714268×
            for (rel, e) in read.iter_mut() {
2138
                // A cached blob the store lost (gc, a partial clone): read the file after all.
213914268×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
21400×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
21410×
                    e.blob = None;
214214268×
                }
2143
            }
2144
            // The listing is in path order, so the map is built without
2145
            // searching.
21461319×
            out = read.into_iter().collect();
21471319×
            for (rel, target) in symlinks {
21482×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
21492×
            }
2150
        }
21511319×
        drop(_read_phase);
21521319×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2153
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2154
        // already tracked as subrepo nodes, they contribute their pin;
2155
        // unregistered ones are left alone.
21561319×
        let modules = self.modules_on_disk();
21571319×
        let removed = self.removed_subrepos();
21581319×
        for rel in &removed {
21593×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
21601×
                self.clear_removed_subrepo(rel);
21612×
            }
2162
        }
21631319×
        let mut untracked_nested = Vec::new();
21641319×
        for dir in nested {
216531×
            let rel = self.rel_path(&dir);
216631×
            if !self.in_scope(&rel) || removed.contains(&rel) {
21673×
                continue;
216828×
            }
216928×
            let registered = modules.entries.get(&rel);
217028×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2171
            {
21721×
                untracked_nested.push(rel);
21731×
                continue;
217427×
            }
217527×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
217627×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2177
        }
21781319×
        untracked_nested.sort();
21791319×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2180
        // Tracked paths the ignore rules hid.
21811319×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
218288×
            if !self.in_scope(rel) {
218310×
                continue;
218478×
            }
218578×
            let path = self.root.join(rel);
218678×
            if *kind == NodeKind::Subrepo {
21874×
                if removed.contains(rel) {
21882×
                    continue;
21892×
                }
21902×
                let present =
21912×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
21922×
                if present {
21930×
                    let pin = subrepos::read_pin(
21940×
                        &path,
21950×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
21960×
                    )?;
21970×
                    out.insert(
21980×
                        rel.clone(),
21990×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2200
                    );
22012×
                } else if let Some(b) = blob {
22022×
                    // Not cloned (or emptied): the pin stays as recorded, as a
22032×
                    // Git gitlink does when its directory is absent.
22042×
                    out.insert(
22052×
                        rel.clone(),
22062×
                        FsEntry {
22072×
                            blob: Some(*b),
22082×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
22092×
                        },
22102×
                    );
22112×
                }
22122×
                continue;
221374×
            }
221474×
            let Ok(meta) = fs::symlink_metadata(&path) else {
221574×
                continue;
2216
            };
22170×
            let ft = meta.file_type();
22180×
            if ft.is_symlink() {
22190×
                let target = fs::read_link(&path)?;
22200×
                out.insert(
22210×
                    rel.clone(),
22220×
                    FsEntry::new(
22230×
                        NodeKind::Symlink,
2224
                        false,
22250×
                        target.to_string_lossy().as_bytes().to_vec(),
2226
                    ),
2227
                );
22280×
            } else if ft.is_file() {
22290×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
22300×
                out.insert(rel.clone(), e);
22310×
            }
2232
        }
22331319×
        Ok(out)
22341320×
    }
2235
2236
    /// The entry for one regular file, read or served from the stat cache.
22370×
    fn file_entry(
22380×
        &self,
22390×
        rel: &str,
22400×
        path: &Path,
22410×
        meta: &walk::Stat,
22420×
        cache: Option<&prompt::Manifest>,
22430×
    ) -> Result<FsEntry> {
22440×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
22450×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
22460×
            e.content = std::sync::Arc::new(fs::read(path)?);
22470×
            e.blob = None;
22480×
        }
22490×
        Ok(e)
22500×
    }
2251
2252
    /// The non-directory paths of a snapshot with their kinds, for the
2253
    /// walker's `tracked` set.
22542×
    pub(crate) fn tracked_kinds(
22552×
        snapshot: &Snapshot,
22562×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
22572×
        snapshot
22582×
            .files
22592×
            .iter()
226012×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
22618×
            .map(|(p, f)| {
22628×
                let blob = match &f.content {
22634×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
22644×
                    _ => None,
2265
                };
22668×
                (p.clone(), (f.kind, blob))
22678×
            })
22682×
            .collect()
22692×
    }
2270
2271
    /// A path under the root as a `/`-separated relative string.
227270×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
227370×
        path.strip_prefix(&self.root)
227470×
            .unwrap_or(path)
227570×
            .components()
2276134×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
227770×
            .collect::<Vec<_>>()
227870×
            .join("/")
227970×
    }
2280
}
2281
2282
impl Repo {
2283
    /// Changes reachable from the bookmark and the working copy, newest first.
228495×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
228595×
        let heads = self.bookmark_heads()?;
228695×
        if self.bare {
22871×
            return self.log_state(&heads);
228894×
        }
228994×
        let (wc_hash, wc) = self.working_copy()?;
229094×
        let mut all = heads.clone();
229194×
        all.push(wc_hash);
229294×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
229394×
        let mut entries: Vec<LogEntry> = Vec::new();
2294
        // A shallow clone knows changes beyond its boundary from a
2295
        // checkpoint's metadata only: its log comes from the state.
229694×
        let metas = if self.is_shallow() {
22971×
            self.load_state_history(&all)?
22981×
                .changes()
22999×
                .map(|(h, m)| (*h, m.clone()))
23001×
                .collect()
2301
        } else {
2302
            // The working copy's change is in hand, and is never in the
2303
            // state index: its metadata is not looked up again.
230493×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
230593×
            below.extend(wc.deps.iter().copied());
230693×
            let _t = crate::timing::phase("log: metadata");
230793×
            let mut metas = self.metas_of(&below)?;
2308325×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
230993×
                // First, where the log puts it, so the order may hold.
231093×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
231193×
            }
231293×
            metas
2313
        };
231494×
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2315427×
            hash: h,
2316427×
            change: meta,
2317427×
            is_working_copy: h == wc_hash,
2318427×
            is_head: head_set.contains(&h),
2319427×
        }));
232094×
        let _sorting = crate::timing::phase("log: sort");
2321
        // The hash makes the order total, so an unstable sort gives the same.
2322
        // From the state index the order already holds (oxygen#94).
2323821×
        let order = |a: &LogEntry, b: &LogEntry| {
2324821×
            b.is_working_copy
2325821×
                .cmp(&a.is_working_copy)
2326821×
                .then(crate::state::log_order(
2327821×
                    (&a.hash, &a.change.hlc),
2328821×
                    (&b.hash, &b.change.hlc),
2329
                ))
2330821×
        };
2331224×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
233252×
            entries.sort_unstable_by(order);
233352×
        }
233494×
        Ok(entries)
233595×
    }
2336
2337
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2338
    /// count, for paginated views.
23390×
    pub fn log_window(
23400×
        &self,
23410×
        heads: &[ChangeHash],
23420×
        offset: usize,
23430×
        limit: usize,
23440×
    ) -> Result<(Vec<LogEntry>, usize)> {
23450×
        let all = self.log_state(heads)?;
23460×
        let total = all.len();
23470×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
23480×
    }
2349
2350
    /// The log of the state with these heads, newest first, with no working
2351
    /// copy involved (for hosted repositories and any explicit state).
235210×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2353
        // The log needs change metadata only: neither graphs nor the tree.
235410×
        if self.is_shallow() {
23550×
            return Ok(self.log_of(&self.load_state_history(heads)?));
235610×
        }
235710×
        let metas = self.metas_of(heads)?;
235810×
        let depended: BTreeSet<ChangeHash> = metas
235910×
            .iter()
236030×
            .flat_map(|(_, m)| m.deps.iter().copied())
236110×
            .collect();
236210×
        let mut entries: Vec<LogEntry> = metas
236310×
            .into_iter()
236410×
            .map(|(h, meta)| LogEntry {
236530×
                hash: h,
236630×
                is_head: !depended.contains(&h),
236730×
                change: meta,
2368
                is_working_copy: false,
236930×
            })
237010×
            .collect();
237137×
        let order = |a: &LogEntry, b: &LogEntry| {
237237×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
237337×
        };
237411×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
23754×
            entries.sort_unstable_by(order);
23766×
        }
237710×
        Ok(entries)
237810×
    }
2379
2380
    /// Every change of the state with these heads and its metadata, read
2381
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2382
    /// a shallow clone's boundary is left out.
2383177×
    pub fn metas_of(
2384177×
        &self,
2385177×
        heads: &[ChangeHash],
2386177×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2387177×
        let boundary = self.boundary();
2388
        // The state index holds the metadata of its heads' closure: a
2389
        // change found there is not read from the store (a change object
2390
        // can be as large as the tree it adds).
2391177×
        let read = self.read_state_index_changes();
2392
        // Every one of `heads` in the index, and every head of the index
2393
        // among them: their closure is the index's changes, all of them
2394
        // (it is closed), and no walk is needed to find it.
2395177×
        if let Some((index_heads, all)) = &read {
2396160×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2397160×
            let in_index = || {
2398160×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2399160×
                    index_heads.iter().collect();
2400
                // Usually the heads asked are the index's: no set of all.
2401160×
                heads.iter().all(|h| index_heads.contains(h)) || {
2402160×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2403160×
                        all.iter().map(|(h, _)| h).collect();
2404160×
                    heads.iter().all(|h| all.contains(h))
2405
                }
2406160×
            };
2407160×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
24080×
                let (_, all) = read.expect("matched above");
2409
                #[cfg(test)]
2410
                {
2411
                    // The walk the shortcut saves finds the same changes.
24120×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
24130×
                    let mut stack = heads.to_vec();
24140×
                    while let Some(h) = stack.pop() {
24150×
                        if seen.insert(h) {
24160×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
24170×
                        }
2418
                    }
24190×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2420
                }
24210×
                return Ok(all);
2422160×
            }
242317×
        }
2424177×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2425177×
            read.map(|(_, all)| all.into_iter().collect());
2426177×
        let _walk = crate::timing::phase("metadata: walk");
2427177×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2428177×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2429177×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2430177×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
24311277×
        while let Some(h) = stack.pop() {
24321100×
            if !seen.insert(h) {
2433461×
                continue;
2434639×
            }
2435
            // Taken out of the index's map, each once: not copied.
2436639×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2437
                #[cfg(test)]
24380×
                assert_eq!(
2439
                    meta,
24400×
                    self.store.get_change_meta(&h)?,
2441
                    "the state index holds a change's metadata"
2442
                );
24430×
                stack.extend(meta.deps.iter().copied());
24440×
                out.push((h, meta));
24450×
                continue;
2446639×
            }
2447639×
            let started = std::time::Instant::now();
2448639×
            let meta = match self.store.get_change_meta(&h) {
2449639×
                Ok(m) => m,
24500×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
24510×
                Err(e) => return Err(e.into()),
2452
            };
2453639×
            stored += 1;
2454639×
            from_store += started.elapsed();
2455639×
            stack.extend(meta.deps.iter().copied());
2456639×
            out.push((h, meta));
2457
        }
2458177×
        if stored > 0 && crate::timing::enabled() {
24590×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2460177×
        }
2461177×
        Ok(out)
2462177×
    }
2463
2464
    /// The log of a state already loaded, newest first.
2465
    /// The history of lines `first..=last` (1-based) of `path` in the
2466
    /// state `heads` make (spec §27): every change that inserted or
2467
    /// deleted one of their atoms, or an atom deleted from between them,
2468
    /// newest first. Exact, as atoms keep their identity across edits.
24696×
    pub fn line_history(
24706×
        &self,
24716×
        heads: &[ChangeHash],
24726×
        path: &str,
24736×
        first: usize,
24746×
        last: usize,
24756×
    ) -> Result<Vec<LogEntry>> {
24766×
        if first == 0 || last < first {
24771×
            return fail(format!(
2478
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2479
            ));
24805×
        }
24815×
        let mut state = self.load_state_history(heads)?;
24825×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
24831×
            return fail(format!("{path} is not in that state"));
2484
        };
24854×
        self.load_graphs_of(&mut state, &[node])?;
24864×
        let live = state.live_lines(&node);
24874×
        if last > live.len() {
24881×
            return fail(format!(
2489
                "{path} has {} lines; asked for {first},{last}",
24901×
                live.len()
2491
            ));
24923×
        }
24933×
        let Some(g) = state.file(&node) else {
24940×
            return fail(format!("{path} is not a text file"));
2495
        };
24963×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
24973×
        let touched = g.touching(&atoms);
24983×
        Ok(self
24993×
            .log_of(&state)
25003×
            .into_iter()
250113×
            .filter(|e| touched.contains(&e.hash))
25023×
            .collect())
25036×
    }
2504
25058×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
25068×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
25078×
        let mut entries: Vec<LogEntry> = state
25088×
            .changes()
25098×
            .map(|(h, meta)| LogEntry {
251031×
                hash: *h,
251131×
                change: meta.clone(),
2512
                is_working_copy: false,
251331×
                is_head: head_set.contains(h),
251431×
            })
25158×
            .collect();
251635×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
25178×
        entries
25188×
    }
2519
2520
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2521
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2522
    /// (`resolve_change`).
252367×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
252467×
        let view = self.view()?;
252567×
        if let Some(st) = view.bookmarks.get(spec) {
252639×
            return Ok(self.store.get_state(st)?.heads);
252728×
        }
252828×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
25292×
            return Ok(self.store.get_state(&st)?.heads);
253026×
        }
253126×
        if let Some(heads) = self.tag_heads(spec)? {
25322×
            return Ok(heads);
253324×
        }
253424×
        Ok(vec![self.resolve_change(spec)?])
253567×
    }
2536
2537
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2538
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
253936×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
254036×
        if spec == "@" {
25410×
            return Ok(self.working_copy()?.0);
254236×
        }
254336×
        let view = self.view()?;
254436×
        let named = match view.bookmarks.get(spec) {
25451×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
254635×
            None => match remote_bookmark(&view, spec) {
25471×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
254834×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2549
            },
2550
        };
255136×
        if let Some((kind, heads)) = named {
25523×
            return match heads.len() {
25533×
                1 => Ok(heads[0]),
25540×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2555
            };
255633×
        }
255733×
        if spec.is_empty() || spec == "#" {
25580×
            return fail("empty change specifier");
255933×
        }
256033×
        let entries = self.log()?;
2561
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2562
        // cannot be a ChangeId, which has 32 (oxygen#103).
256333×
        let full_hash =
2564128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
256533×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
256627×
            entries
256727×
                .iter()
2568109×
                .filter(|e| e.hash.starts_with_hex(hp))
256927×
                .collect()
2570
        } else {
25716×
            entries
25726×
                .iter()
257321×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
25746×
                .collect()
2575
        };
257633×
        match matches.len() {
257728×
            1 => Ok(matches[0].hash),
25785×
            0 => match self.resolve_in_remotes(spec)? {
25791×
                Some(h) => Ok(h),
25804×
                None => fail(format!("no change matches {spec:?}")),
2581
            },
2582
            _ => {
25830×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
25840×
                if ids.len() == 1 {
25850×
                    fail(format!(
2586
                        "change {spec} is divergent: {} variants",
25870×
                        matches.len()
2588
                    ))
2589
                } else {
25900×
                    fail(format!("{spec:?} is ambiguous"))
2591
                }
2592
            }
2593
        }
259436×
    }
2595
2596
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2597
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2598
    /// `None` when none matches, or more than one.
25995×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
26005×
        let view = self.view()?;
26015×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
26025×
        for bookmarks in view.remotes.values() {
26033×
            for st in bookmarks.values() {
26043×
                let heads = self.store.get_state(st)?.heads;
26057×
                for e in self.log_state(&heads)? {
26067×
                    let hit = match spec.strip_prefix('#') {
26072×
                        Some(hp) => e.hash.starts_with_hex(hp),
26085×
                        None => e.change.change_id.starts_with_hex(spec),
2609
                    };
26107×
                    if hit {
26111×
                        found.insert(e.hash);
26126×
                    }
2613
                }
2614
            }
2615
        }
26165×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
26175×
    }
2618
2619
    /// Where a change is when no local bookmark or the working copy holds
2620
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2621
    /// it is held locally, or nowhere.
26223×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
26236×
        if self.log()?.iter().any(|e| e.hash == *hash) {
26242×
            return Ok(None);
26251×
        }
26261×
        let view = self.view()?;
26271×
        for (remote, bookmarks) in &view.remotes {
26281×
            for (name, st) in bookmarks {
26291×
                let heads = self.store.get_state(st)?.heads;
26301×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
26311×
                    return Ok(Some(format!("{remote}/{name}")));
26320×
                }
2633
            }
2634
        }
26350×
        Ok(None)
26363×
    }
2637
2638
    /// Human-readable description of what a change does, with line content.
26393×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
26403×
        let change = self.store.get_change(hash)?;
26413×
        let (base, base_snapshot) = self.change_base(&change)?;
26423×
        Ok(render_change(&change, &base, &base_snapshot))
26433×
    }
2644
2645
    /// The base state of `change` (its dependencies) and its rendering, as
2646
    /// much as showing the change needs: the whole tree, and the graphs and
2647
    /// contents of the files the change edits. Other text files are left
2648
    /// unrendered ([`Snapshot::unrendered`]).
26496×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
26506×
        let base = self.load_state_history(&change.deps)?;
26516×
        self.render_base_for(change, base)
26526×
    }
2653
2654
    /// The base for showing `change` alone: the graphs of the files it
2655
    /// edits built, and the base's tree with no file rendered, which is
2656
    /// all [`render_change`](snapshot::render_change) and
2657
    /// [`diff_files_of`](snapshot::diff_files_of) read.
26583×
    pub(crate) fn tree_base_for(
26593×
        &self,
26603×
        change: &Change,
26613×
        mut base: State,
26623×
    ) -> Result<(State, Snapshot)> {
26633×
        let _t = crate::timing::phase("diff: the base's tree");
26643×
        let edited: std::collections::HashSet<NodeId> =
26658×
            change.edits.iter().map(|e| e.node()).collect();
26663×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
26673×
        self.load_graphs_of(&mut base, &nodes)?;
26683×
        let snapshot = Snapshot {
26693×
            tree: base.tree().view(),
26703×
            files: BTreeMap::new(),
26713×
            unrendered: BTreeSet::new(),
26723×
        };
26733×
        Ok((base, snapshot))
26743×
    }
2675
2676
    /// [`Repo::change_base`] with the base already loaded (the working
2677
    /// copy's comes from the state index).
2678226×
    pub(crate) fn render_base_for(
2679226×
        &self,
2680226×
        change: &Change,
2681226×
        mut base: State,
2682226×
    ) -> Result<(State, Snapshot)> {
2683226×
        let _t = crate::timing::phase("diff: render the base");
2684226×
        let edited: std::collections::HashSet<NodeId> =
2685455×
            change.edits.iter().map(|e| e.node()).collect();
2686226×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2687226×
        self.load_graphs_of(&mut base, &nodes)?;
2688226×
        let snapshot = {
2689226×
            let _t = crate::timing::phase("diff:   of which materialize");
2690226×
            base.materialize_nodes(&edited)
2691
        };
2692226×
        Ok((base, snapshot))
2693226×
    }
2694
}
2695
26960×
fn remove_any(path: &Path) -> std::io::Result<()> {
26970×
    let m = fs::symlink_metadata(path)?;
26980×
    if m.is_dir() {
26990×
        fs::remove_dir_all(path)
2700
    } else {
27010×
        fs::remove_file(path)
2702
    }
27030×
}
2704
27055×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
27065×
    let mut perms = fs::metadata(path)?.permissions();
27075×
    perms.set_readonly(readonly);
27085×
    fs::set_permissions(path, perms)
27095×
}
2710
2711
#[cfg(unix)]
27125892×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2713
    use std::os::unix::fs::PermissionsExt;
27145892×
    let mut perms = fs::metadata(path)?.permissions();
27155892×
    let mode = perms.mode();
27165892×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
27175892×
    if want != mode {
27184×
        perms.set_mode(want);
27194×
        fs::set_permissions(path, perms)?;
27205888×
    }
27215892×
    Ok(())
27225892×
}
2723
#[cfg(not(unix))]
2724
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2725
    Ok(())
2726
}
2727
2728
#[cfg(unix)]
272918581×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2730
    use std::os::unix::fs::PermissionsExt;
273118581×
    m.permissions().mode() & 0o111 != 0
273218581×
}
2733
#[cfg(not(unix))]
2734
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2735
    false
2736
}
2737
273817138×
fn op_ref(k: OpKey) -> OpRef {
273917138×
    OpRef {
274017138×
        change: k.0,
274117138×
        index: k.1,
274217138×
    }
274317138×
}
2744
27456057×
fn split_path(path: &str) -> (&str, &str) {
27466057×
    match path.rfind('/') {
27475059×
        Some(i) => (&path[..i], &path[i + 1..]),
2748998×
        None => ("", path),
2749
    }
27506057×
}
2751
2752
/// Whether `rel` is an attributes file (spec §7.6).
275376215×
fn is_attributes(rel: &str) -> bool {
275476215×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
275576215×
}
2756
2757
/// The manifest entry for `rel` when its size and mtime match it outside
2758
/// the racy window.
275928509×
fn stat_cached<'m>(
276028509×
    rel: &str,
276128509×
    meta: &walk::Stat,
276228509×
    cache: Option<&'m prompt::Manifest>,
276328509×
) -> Option<&'m prompt::ManifestEntry> {
276428509×
    let m = cache?;
276523561×
    let e = m.entries.get(rel)?;
276622190×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
276722190×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
276828509×
}
2769
2770
/// Read one working-copy file, or serve it from the stat cache (spec
2771
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2772
/// an opaque file is not read at all (its stored blob stands in), and a
2773
/// text file the manifest recorded equal to a base graph whose key is
2774
/// `key`, the key the base has now, is not read either: equal keys mean
2775
/// equal renderings, so it still equals the base. Touches no repository
2776
/// state, so the walk runs it in parallel; the caller checks that a cached
2777
/// blob is still in the store.
277814270×
fn read_file_entry(
277914270×
    rel: &str,
278014270×
    path: &Path,
278114270×
    meta: &walk::Stat,
278214270×
    cache: Option<&prompt::Manifest>,
278314270×
    key: Option<[u8; 32]>,
278414270×
) -> Result<FsEntry> {
278514270×
    let exec = meta.exec;
278614270×
    let stat = Some((meta.size, meta.mtime_ns));
278714270×
    let mut e = match stat_cached(rel, meta, cache) {
27884249×
        Some(e) if e.blob.is_some() => FsEntry {
27891×
            blob: e.blob,
27901×
            content_hash: Some(e.hash),
27911×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27921×
        },
27934248×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
27944243×
            content_hash: Some(e.hash),
27954243×
            unchanged: true,
27964243×
            graph_key: e.graph,
27974243×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27984243×
        },
27995×
        Some(e) => FsEntry {
28005×
            content_hash: Some(e.hash),
28015×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2802
        },
280310021×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2804
    };
2805
    // The stat the manifest records: taken before the read, so a file that
2806
    // changes meanwhile is read again next time.
280714269×
    e.stat = stat;
280814269×
    Ok(e)
280914270×
}
2810
2811
/// Two maps side by side in key order: each key of either, with its value
2812
/// in each. Linear, with no lookups, for maps of a whole tree.
28132623×
pub(crate) fn join<'a, A, B>(
28142623×
    a: &'a BTreeMap<String, A>,
28152623×
    b: &'a BTreeMap<String, B>,
28162623×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
28172623×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
281842060×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
28192623×
        (None, None) => None,
28202941×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
28215829×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
282230667×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2823344×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2824309×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2825
            std::cmp::Ordering::Equal => {
282630014×
                let (k, va) = a.next()?;
282730014×
                let (_, vb) = b.next()?;
282830014×
                Some((k, Some(va), Some(vb)))
2829
            }
2830
        },
283142060×
    })
28322623×
}
2833
2834
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2835
/// lookups.
28361320×
pub(crate) fn missing_from<'a, A, B>(
28371320×
    a: &'a BTreeMap<String, A>,
28381320×
    b: &BTreeMap<String, B>,
28391320×
) -> Vec<(&'a String, &'a A)> {
28401320×
    let mut keys = b.keys().peekable();
28411320×
    a.iter()
284211253×
        .filter(|(k, _)| {
284321800×
            while keys.next_if(|kb| *kb < *k).is_some() {}
284411253×
            keys.peek() != Some(k)
284511253×
        })
28461320×
        .collect()
28471320×
}