OXYGENHUB

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

1834 of 2066 lines run, 429 of 696 functions · run #321 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.
752475×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762475×
    let Some(url) = &config.storage_url else {
772470×
        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×
    )?)
1002475×
}
101
102164×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103164×
    Err(RepoError::Msg(s.into()))
104164×
}
105
106
mod bookmarks;
107
mod checkout;
108
mod checkpoint;
109
mod config;
110
mod doctor;
111
mod fsck;
112
mod gc;
113
mod git;
114
mod history;
115
mod hooks;
116
mod hosted;
117
mod identity;
118
mod inspect;
119
mod keyless;
120
mod ops;
121
mod policy;
122
mod prompt;
123
mod receipts;
124
mod revset;
125
mod snapshot;
126
pub mod strata;
127
mod subrepos;
128
mod sync;
129
mod tags;
130
#[cfg(test)]
131
mod tests;
132
mod touched;
133
mod transparency;
134
mod walk;
135
mod workspace;
136
137
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
138
pub use checkout::CheckoutReport;
139
pub use config::{parse_size, read_config_file, Config};
140
pub use doctor::{Check, DoctorReport, Health};
141
pub use fsck::{FsckReport, Problem, Severity};
142
pub use gc::GcReport;
143
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
144
pub use hooks::{json_array, json_str, HookOutcome};
145
pub use hosted::FileEdit;
146
pub use identity::{Rotation, SignatureStatus};
147
pub use inspect::{BisectStep, BlameLine, Description};
148
pub use keyless::home_key;
149
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
150
pub use policy::PolicyUpdate;
151
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
152
pub use receipts::ReceiptInfo;
153
pub use revset::{Revset, REVSET_BUDGET};
154
pub use snapshot::{
155
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
156
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
157
    Selection, SnapshotResult,
158
};
159
pub use subrepos::{SubrepoInfo, SubrepoSync};
160
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT};
161
pub use tags::TagInfo;
162
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
163
164
/// The file name under which per-bookmark or per-tag data is kept: `/`
165
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
166
/// than a directory that would clash with it.
1674105×
pub(crate) fn name_file(name: &str) -> String {
1684105×
    name.replace('%', "%25").replace('/', "%2F")
1694105×
}
170
171
/// The name a [`name_file`] file name stands for.
17243×
pub(crate) fn file_name_to_name(file: &str) -> String {
17343×
    file.replace("%2F", "/").replace("%25", "%")
17443×
}
175
1767221×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1777221×
    Ok(crate::durable::write_atomic(path, data)?)
1787221×
}
179
180
/// Replace a cache file: whole or not at all, but without waiting for the
181
/// disk. A cache checks its own bytes when read, so one a crash leaves
182
/// short or stale is rebuilt rather than trusted.
183
/// How many changes a state index may fall behind its working copy before
184
/// it is written again; until then each load replays them.
185
const INDEX_REPLAY_LIMIT: usize = 16;
186
/// The changes whose encodings are kept for building graphs: a batch of
187
/// files often takes inline text from a few changes in turn.
188
const CHANGE_CACHE_COUNT: usize = 4;
189
const CHANGE_CACHE_BYTES: usize = 512 << 20;
190
/// How many state indexes a workspace keeps.
191
const STATE_INDEXES_KEPT: usize = 2;
192
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
193
1942870×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1952870×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1962870×
    fs::write(&tmp, data)?;
1972870×
    fs::rename(&tmp, path)?;
1982870×
    Ok(())
1992870×
}
200
201
pub struct LogEntry {
202
    pub hash: ChangeHash,
203
    /// Metadata from the state; the full change may be absent in a shallow repository.
204
    pub change: crate::state::ChangeMeta,
205
    pub is_working_copy: bool,
206
    pub is_head: bool,
207
}
208
209
/// A text file's base graph key, by path, as a walk asks for it.
210
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
211
212
/// A file as found on disk or in an imported tree.
213
#[derive(Clone)]
214
pub(crate) struct FsEntry {
215
    pub kind: NodeKind,
216
    pub exec: bool,
217
    /// File content, or a symlink's target. Empty when `blob` is set.
218
    /// Shared, so a new file's insert holds it without a copy.
219
    pub content: std::sync::Arc<Vec<u8>>,
220
    /// The stored blob of an opaque file whose size and mtime are unchanged
221
    /// since the last manifest (spec §12.3 stat cache); the content was not
222
    /// read.
223
    pub blob: Option<ObjectRef>,
224
    /// BLAKE3 of the content, carried over from the manifest when the stat
225
    /// is unchanged, so the manifest can be rewritten without rehashing.
226
    pub content_hash: Option<[u8; 32]>,
227
    /// A text file known equal to the base's rendering without reading it:
228
    /// its stat matches the manifest and the manifest recorded it equal to
229
    /// a base file graph with the same key (spec §12.3). `content` is empty.
230
    pub unchanged: bool,
231
    /// The base graph key this file equals, for the next manifest.
232
    pub graph_key: Option<[u8; 32]>,
233
    /// Size and mtime already known to be current (a checkout leaving the
234
    /// file as it was), so the manifest need not stat it again.
235
    pub stat: Option<(u64, u128)>,
236
}
237
238
impl FsEntry {
23922716×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
24022716×
        FsEntry {
24122716×
            kind,
24222716×
            exec,
24322716×
            content: std::sync::Arc::new(content),
24422716×
            blob: None,
24522716×
            content_hash: None,
24622716×
            unchanged: false,
24722716×
            graph_key: None,
24822716×
            stat: None,
24922716×
        }
25022716×
    }
251
}
252
253
pub struct Repo {
254
    /// The key a host accepts certified updates with (spec §14.7): when
255
    /// set, accepting a reference update signed by a short-lived key also
256
    /// records the host's acceptance and its time.
257
    pub(crate) acceptor: Option<std::sync::Arc<(Identity, crate::identity::SecretKey)>>,
258
    /// With `author.signer = keyless`, the fresh key the hub last
259
    /// certified and when its certificate ends (spec §14.7): kept in memory
260
    /// only, for one command.
261
    pub(crate) keyless_key: std::cell::RefCell<Option<(KeyId, crate::identity::SecretKey, u64)>>,
262
    /// Oxygen-pinned subrepos skipped by the running Git export.
263
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
264
    /// The manifest as last read, with the file identity it was read from,
265
    /// so one command parses it once (see `read_manifest`).
266
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
267
    /// A listing of the working copy left by a failed clean check, for the
268
    /// snapshot that follows it to reuse; taken by the next walk and
269
    /// dropped whenever the manifest is written.
270
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
271
    /// The nested repositories the last walk left out, being neither
272
    /// registered nor tracked subrepos (oxygen#43).
273
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
274
    /// New untracked files the last walk left out for their size, with
275
    /// their sizes (oxygen#98).
276
    pub(crate) skipped_large: std::cell::RefCell<Vec<(String, u64)>>,
277
    root: PathBuf,
278
    oxy: PathBuf,
279
    store: Store,
280
    workspace: WorkspaceId,
281
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
282
    bare: bool,
283
    keys_dir: PathBuf,
284
    user_config: PathBuf,
285
    pub config: Config,
286
    /// What the working copy's file system can represent (spec §7.7).
287
    platform: crate::portable::Platform,
288
    /// The encodings of the changes last read for their inline inserts,
289
    /// oldest first.
290
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
291
    /// `--at-op`: read the repository as it was after this operation;
292
    /// recording an operation is refused.
293
    at_op: Option<ObjectRef>,
294
    /// The directories (with their times) and nested repositories of the
295
    /// last walk, for the manifest written from it.
296
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
297
    /// The directories a manifest check listed, for its restamp only.
298
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
299
}
300
301
/// A walk's directories with their times, and its nested repositories.
302
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
303
304
/// Marker file of a bare repository, inside `.oxy/`.
305
const BARE_MARKER: &str = "bare";
306
/// Marker of a hosted repository that has no id yet: the first push binds
307
/// it to the pusher's id (spec §16.1).
308
const UNBOUND_MARKER: &str = "unbound";
309
310
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
311
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
3127669×
pub fn default_home() -> PathBuf {
3137669×
    if let Ok(h) = std::env::var("OXY_HOME") {
3147663×
        return PathBuf::from(h);
3156×
    }
3166×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3170×
        return PathBuf::from(x).join("oxy");
3186×
    }
319
    // Windows has no HOME as a rule: the roaming profile's application
320
    // data, as Windows programs keep theirs.
321
    #[cfg(windows)]
322
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
323
        return PathBuf::from(d).join("oxy");
324
    }
3256×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3266×
    PathBuf::from(home).join(".config").join("oxy")
3277669×
}
328
3292476×
pub fn default_keys_dir() -> PathBuf {
3302476×
    default_home().join("keys")
3312476×
}
332
3334950×
pub fn default_user_config() -> PathBuf {
3344950×
    default_home().join("config.toml")
3354950×
}
336
337
/// Where `create_identity` records the author.
338
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
339
pub enum IdentityScope {
340
    /// The user file: every repository of this user signs with it.
341
    User,
342
    /// This repository only.
343
    Repo,
344
}
345
346
impl Repo {
347
    // ------------------------------------------------------------ lifecycle
348
349227×
    pub fn init(root: &Path) -> Result<Repo> {
350227×
        let mut id = [0u8; 16];
351227×
        rand::rngs::OsRng.fill_bytes(&mut id);
352227×
        Self::init_with_id(root, id)
353227×
    }
354
355
    /// Initialize a repository with a given repository ID (clones share the
356
    /// ID of their origin, spec §14.4).
357477×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
358477×
        Self::init_on(root, id, None)
359477×
    }
360
361
    /// A new repository with a fresh id, bare or not, on `storage` or in
362
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
36312×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
36412×
        let mut id = [0u8; 16];
36512×
        rand::rngs::OsRng.fill_bytes(&mut id);
36612×
        if bare {
3670×
            Self::init_bare_on(root, id, storage)
368
        } else {
36912×
            Self::init_on(root, id, storage)
370
        }
37112×
    }
372
373
    /// Initialize a repository whose objects and operation head are kept
374
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
375492×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
376492×
        fs::create_dir_all(root)?;
377492×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
378492×
        let oxy = root.join(OXY_DIR);
379492×
        if oxy.exists() {
3801×
            return fail(format!("{} is already an oxy repository", root.display()));
381491×
        }
382491×
        fs::create_dir_all(oxy.join("ops"))?;
383491×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
384491×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
385491×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
386491×
        if let Some(url) = storage {
3873×
            config.set("storage.url", url)?;
388488×
        }
389491×
        config.save(&oxy.join("config"))?;
390491×
        let workspace = WorkspaceId::random();
391491×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
392491×
        let store = open_objects(&oxy, &config)?;
393490×
        let repo = Repo {
394490×
            acceptor: None,
395490×
            keyless_key: Default::default(),
396490×
            last_change: Default::default(),
397490×
            at_op: None,
398490×
            walked_dirs: Default::default(),
399490×
            listed_dirs: Default::default(),
400490×
            git_export_skipped: Default::default(),
401490×
            manifest_cache: Default::default(),
402490×
            listing_cache: Default::default(),
403490×
            untracked_nested: Default::default(),
404490×
            skipped_large: Default::default(),
405490×
            root,
406490×
            oxy,
407490×
            store,
408490×
            workspace,
409490×
            bare: false,
410490×
            keys_dir: default_keys_dir(),
411490×
            platform: crate::portable::Platform::current(),
412490×
            user_config: default_user_config(),
413490×
            config,
414490×
        };
415490×
        repo.register_workspace(&workspace, &repo.root)?;
416
417490×
        let wc = repo.new_working_copy(vec![], "");
418490×
        let wc_hash = repo.store.put_change(&wc)?;
419490×
        let mut view = View::default();
420490×
        view.bookmarks.insert(
421490×
            repo.config.bookmark.clone(),
422490×
            repo.store.put_state(&StateObject::new(vec![]))?,
423
        );
424490×
        view.workspaces.insert(workspace, wc_hash);
425490×
        repo.record_op(&[], "oxy init", view)?;
426488×
        Ok(repo)
427492×
    }
428
429
    /// Create a bare repository: an object store, operation log and
430
    /// references with no workspace and no working copy, for hosting
431
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4325×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4335×
        let mut id = [0u8; 16];
4345×
        rand::rngs::OsRng.fill_bytes(&mut id);
4355×
        Self::init_bare_with_id(root, id)
4365×
    }
437
43840×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
43940×
        Self::init_bare_on(root, id, None)
44040×
    }
441
442
    /// [`Repo::init_on`] for a bare repository.
44340×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
44440×
        fs::create_dir_all(root)?;
44540×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
44640×
        let oxy = root.join(OXY_DIR);
44740×
        if oxy.exists() {
4480×
            return fail(format!("{} is already an oxy repository", root.display()));
44940×
        }
45040×
        fs::create_dir_all(oxy.join("ops"))?;
45140×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
45240×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
45340×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
45440×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
45540×
        if let Some(url) = storage {
4560×
            config.set("storage.url", url)?;
45740×
        }
45840×
        config.save(&oxy.join("config"))?;
45940×
        let store = open_objects(&oxy, &config)?;
46040×
        let repo = Repo {
46140×
            acceptor: None,
46240×
            keyless_key: Default::default(),
46340×
            last_change: Default::default(),
46440×
            at_op: None,
46540×
            walked_dirs: Default::default(),
46640×
            listed_dirs: Default::default(),
46740×
            git_export_skipped: Default::default(),
46840×
            manifest_cache: Default::default(),
46940×
            listing_cache: Default::default(),
47040×
            untracked_nested: Default::default(),
47140×
            skipped_large: Default::default(),
47240×
            root,
47340×
            oxy,
47440×
            store,
47540×
            workspace: WorkspaceId::ZERO,
47640×
            bare: true,
47740×
            keys_dir: default_keys_dir(),
47840×
            platform: crate::portable::Platform::current(),
47940×
            user_config: default_user_config(),
48040×
            config,
48140×
        };
48240×
        let mut view = View::default();
48340×
        view.bookmarks.insert(
48440×
            repo.config.bookmark.clone(),
48540×
            repo.store.put_state(&StateObject::new(vec![]))?,
486
        );
48740×
        repo.record_op(&[], "oxy init --bare", view)?;
48840×
        Ok(repo)
48940×
    }
490
491
    /// A bare repository with no id yet. Its `id()` is all zero until the
492
    /// first push binds it (`bind_id`), so an existing repository can be
493
    /// pushed to a freshly created hosted one and keep its identity.
49414×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
49514×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
49614×
        fs::remove_file(repo.oxy.join("id"))?;
49714×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
49814×
        Ok(repo)
49914×
    }
500
5013582×
    pub fn is_unbound(&self) -> bool {
5023582×
        self.oxy.join(UNBOUND_MARKER).is_file()
5033582×
    }
504
505
    /// Give an unbound repository its id.
50613×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
50713×
        if !self.is_unbound() {
5080×
            return fail("this repository already has an id");
50913×
        }
51013×
        if id == [0; 16] {
5110×
            return fail("a repository id cannot be all zero");
51213×
        }
51313×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
51413×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
51513×
        Ok(())
51613×
    }
517
518
    /// Whether this repository has no working copy (`init_bare`).
51976×
    pub fn is_bare(&self) -> bool {
52076×
        self.bare
52176×
    }
522
523
    /// Open the repository containing `start` (searching upwards).
5241944×
    pub fn open(start: &Path) -> Result<Repo> {
5251944×
        let start = start.canonicalize()?;
5261944×
        let mut dir: Option<&Path> = Some(&start);
5271944×
        while let Some(d) = dir {
5281944×
            let oxy = d.join(OXY_DIR);
5291944×
            if oxy.is_file() {
530
                // A secondary workspace (spec §12.2): the file points at the repository.
5319×
                let text = fs::read_to_string(&oxy)?;
5329×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5330×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
534
                };
5359×
                let format = fs::read_to_string(shared.join("format"))?;
5369×
                if format != FORMAT_LINE {
5370×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5389×
                }
5399×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5409×
                let store = open_objects(&shared, &config)?;
5419×
                let mut repo = Repo {
5429×
                    acceptor: None,
5439×
                    keyless_key: Default::default(),
5449×
                    last_change: Default::default(),
5459×
                    at_op: None,
5469×
                    walked_dirs: Default::default(),
5479×
                    listed_dirs: Default::default(),
5489×
                    git_export_skipped: Default::default(),
5499×
                    manifest_cache: Default::default(),
5509×
                    listing_cache: Default::default(),
5519×
                    untracked_nested: Default::default(),
5529×
                    skipped_large: Default::default(),
5539×
                    root: d.to_path_buf(),
5549×
                    oxy: shared,
5559×
                    store,
5569×
                    workspace,
5579×
                    bare: false,
5589×
                    keys_dir: default_keys_dir(),
5599×
                    platform: crate::portable::Platform::current(),
5609×
                    user_config: default_user_config(),
5619×
                    config,
5629×
                };
5639×
                repo.apply_workspace_bookmark();
5649×
                return Ok(repo);
5651935×
            }
5661935×
            if oxy.is_dir() {
5671935×
                let format = fs::read_to_string(oxy.join("format"))?;
5681935×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5691935×
                let bare = oxy.join(BARE_MARKER).is_file();
5701935×
                let workspace = if bare {
571148×
                    WorkspaceId::ZERO
572
                } else {
5731787×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5741787×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
575
                };
5761935×
                let store = open_objects(&oxy, &config)?;
5771935×
                let mut repo = Repo {
5781935×
                    acceptor: None,
5791935×
                    keyless_key: Default::default(),
5801935×
                    last_change: Default::default(),
5811935×
                    at_op: None,
5821935×
                    walked_dirs: Default::default(),
5831935×
                    listed_dirs: Default::default(),
5841935×
                    git_export_skipped: Default::default(),
5851935×
                    manifest_cache: Default::default(),
5861935×
                    listing_cache: Default::default(),
5871935×
                    untracked_nested: Default::default(),
5881935×
                    skipped_large: Default::default(),
5891935×
                    root: d.to_path_buf(),
5901935×
                    oxy,
5911935×
                    store,
5921935×
                    workspace,
5931935×
                    bare,
5941935×
                    keys_dir: default_keys_dir(),
5951935×
                    platform: crate::portable::Platform::current(),
5961935×
                    user_config: default_user_config(),
5971935×
                    config,
5981935×
                };
5991935×
                if !bare {
6001787×
                    repo.apply_workspace_bookmark();
6011787×
                }
6021935×
                if format == FORMAT1_LINE {
6031×
                    repo.migrate_format1()?;
6041934×
                } else if format != FORMAT_LINE {
6050×
                    return fail(format!("unsupported repository format: {}", format.trim()));
6061934×
                }
6071935×
                return Ok(repo);
6080×
            }
6090×
            dir = d.parent();
610
        }
6110×
        fail(format!(
612
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
6130×
            start.display()
614
        ))
6151944×
    }
616
617
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
618
    /// into format 2, where each bookmark names a `state` object.
6191×
    fn migrate_format1(&self) -> Result<()> {
6201×
        let (head, version) = self.read_head()?;
621
        // Collect the chain root-first.
6221×
        let mut chain: Vec<Format1Op> = Vec::new();
6231×
        let mut cur = Some(head);
6243×
        while let Some(r) = cur {
6252×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
6262×
            cur = op.parents.first().copied();
6272×
            chain.push(op);
628
        }
6291×
        chain.reverse();
6301×
        let mut new_parent: Option<ObjectRef> = None;
6312×
        for old in chain {
6322×
            let mut view = View::default();
6332×
            for (name, heads) in &old.view.bookmarks {
6342×
                view.bookmarks.insert(
6352×
                    name.clone(),
6362×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
637
                );
638
            }
6392×
            view.workspaces = old.view.workspaces.clone();
6402×
            let op = Op {
6412×
                parents: new_parent.into_iter().collect(),
6422×
                hlc: old.hlc,
6432×
                command: old.command,
6442×
                view,
6452×
                workspace: None,
6462×
                undoes: None,
6472×
            };
6482×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
649
        }
6501×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6510×
            return fail("the operation log changed while it was rewritten; run the command again");
6521×
        }
6531×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6541×
        Ok(())
6551×
    }
656
657
    /// Pack automatically once many loose objects have accumulated.
658664×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
659664×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6600×
            self.store.pack_loose()?;
6610×
            self.store.merge_packs()?;
662664×
        }
663664×
        Ok(())
664664×
    }
665
666
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6673291×
    pub fn id(&self) -> Result<[u8; 16]> {
6683291×
        if self.is_unbound() {
66919×
            return Ok([0; 16]);
6703272×
        }
6713272×
        let path = self.oxy.join("id");
6723272×
        match fs::read_to_string(&path) {
6733272×
            Ok(h) => hex::decode(h.trim())
6743272×
                .ok()
6753272×
                .and_then(|v| v.try_into().ok())
6763272×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6770×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6780×
                let mut id = [0u8; 16];
6790×
                rand::rngs::OsRng.fill_bytes(&mut id);
6800×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6810×
                Ok(id)
682
            }
6830×
            Err(e) => Err(e.into()),
684
        }
6853291×
    }
686
68762×
    pub fn root(&self) -> &Path {
68862×
        &self.root
68962×
    }
690528×
    pub fn store(&self) -> &Store {
691528×
        &self.store
692528×
    }
69311×
    pub fn workspace(&self) -> WorkspaceId {
69411×
        self.workspace
69511×
    }
696
697
    /// Use a different user directory for keys and the user config file
698
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
699
    /// Act as if the working copy were on another platform's file system
700
    /// (tests of Windows and macOS behaviour on any host).
701
    /// Accept certified updates as `identity` (a host's key), recording when
702
    /// (spec §14.7).
7031×
    pub fn with_acceptor(mut self, identity: Identity, sk: crate::identity::SecretKey) -> Repo {
7041×
        self.acceptor = Some(std::sync::Arc::new((identity, sk)));
7051×
        self
7061×
    }
707
7082×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
7092×
        self.platform = platform;
7102×
        self
7112×
    }
712
7130×
    pub fn platform(&self) -> crate::portable::Platform {
7140×
        self.platform
7150×
    }
716
717177×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
718177×
        let dir = dir.into();
719177×
        self.keys_dir = dir.join("keys");
720177×
        self.user_config = dir.join("config.toml");
721177×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
722177×
            self.config = c;
723177×
        }
724177×
        self.apply_workspace_bookmark();
725177×
        self
726177×
    }
727
728
    /// The workspace's current bookmark (spec §10.1) overrides the
729
    /// configured default when `oxy bookmark switch` has recorded one.
7301973×
    fn apply_workspace_bookmark(&mut self) {
7311973×
        if let Ok(b) = fs::read_to_string(
7321973×
            self.oxy
7331973×
                .join("workspaces")
7341973×
                .join(self.workspace.to_hex())
7351973×
                .join("bookmark"),
7361973×
        ) {
73735×
            let b = b.trim();
73835×
            if !b.is_empty() {
73935×
                self.config.bookmark = b.to_string();
74035×
            }
7411938×
        }
7421973×
    }
743
7442×
    pub fn user_config_path(&self) -> &Path {
7452×
        &self.user_config
7462×
    }
747
748
    /// Set a key in the user file and refresh the effective configuration.
74922×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
75022×
        Config::set_user(&self.user_config, key, value)?;
75121×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
75221×
        Ok(())
75322×
    }
754
755371×
    pub fn save_config(&self) -> Result<()> {
756371×
        self.config.save(&self.oxy.join("config"))
757371×
    }
758
7594338×
    fn author(&self) -> KeyId {
7604338×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7614338×
    }
762
}
763
764
impl Repo {
7651657×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7661657×
        let mut c = Change {
7671657×
            version: crate::objects::CHANGE_VERSION,
7681657×
            change_id: ChangeId::random(),
7691657×
            deps,
7701657×
            author: self.author(),
7711657×
            hlc: Hlc::now(),
7721657×
            message: message.into(),
7731657×
            tree_ops: vec![],
7741657×
            edits: vec![],
7751657×
            kind: ChangeKind::WorkingCopy,
7761657×
        };
7771657×
        c.normalize();
7781657×
        c
7791657×
    }
780
781
    // ------------------------------------------------------------ operation log
782
78314011×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
78414011×
        if let Some(r) = self.at_op {
7855×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
78614006×
        }
78714006×
        let r = self.head_ref()?;
78814004×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
78914004×
        Ok((r, op))
79014011×
    }
791
7929713×
    pub fn view(&self) -> Result<View> {
7939713×
        Ok(self.head_op()?.1.view)
7949713×
    }
795
7963424×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
7973424×
        self.record_op_undoing(parents, command, view, None)
7983424×
    }
799
800
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
8013427×
    fn record_op_undoing(
8023427×
        &self,
8033427×
        parents: &[ObjectRef],
8043427×
        command: &str,
8053427×
        view: View,
8063427×
        undoes: Option<ObjectRef>,
8073427×
    ) -> Result<ObjectRef> {
8083427×
        if self.at_op.is_some() {
8091×
            return fail(
810
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
811
            );
8123426×
        }
8133426×
        let op = Op {
8143426×
            parents: parents.to_vec(),
8153426×
            hlc: Hlc::now(),
8163426×
            command: command.into(),
8173426×
            view,
8183426×
            workspace: Some(self.workspace),
8193426×
            undoes,
8203426×
        };
8213426×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
822
        // The head is the commit point: everything it names must be on disk first.
8233424×
        let flushing = crate::timing::phase("op: flush the store");
8243424×
        self.store.flush()?;
8253422×
        drop(flushing);
826
        // Compare and swap (spec §12.1): when another process recorded an
827
        // operation since this one read the head, the two are merged
828
        // instead of one overwriting the other. On this disk the head moves
829
        // under a short lock; on any other store by its record's version,
830
        // and a record that moved meanwhile is read again and merged again.
8313422×
        let _lock = if self.store.is_local() {
8323414×
            Some(self.lock_ops()?)
833
        } else {
8348×
            None
835
        };
8363422×
        let Some(parent) = parents.first() else {
837
            // The first operation (init): there is no head yet.
838530×
            if !self.swap_head(&r, None)? {
8392×
                return fail(format!(
840
                    "{} already holds a repository's operation log",
8412×
                    self.store.backend().describe()
842
                ));
843528×
            }
844528×
            return Ok(r);
845
        };
8462892×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8472892×
        for _ in 0..HEAD_TRIES {
8482892×
            let (current, version) = self.read_head()?;
8492892×
            let to = if current == *parent {
8502883×
                r
851
            } else {
8529×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
8538×
                let merged = Op {
8549×
                    parents: vec![current, r],
8559×
                    hlc: Hlc::now(),
8569×
                    command: format!("{command} (merged with a concurrent operation)"),
8579×
                    view: self.merge_views(&base, &op.view, &theirs)?,
8588×
                    workspace: Some(self.workspace),
8598×
                    undoes: None,
860
                };
8618×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
8628×
                self.store.flush()?;
8638×
                m
864
            };
8652891×
            if self.swap_head(&to, version.as_ref())? {
8662885×
                return Ok(to);
8670×
            }
868
        }
8690×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8703427×
    }
871
872
    /// The operation head's lock, held only while the head pointer moves.
8733424×
    fn lock_ops(&self) -> Result<FileLock> {
8743424×
        fs::create_dir_all(self.oxy.join("ops"))?;
8753424×
        FileLock::acquire(
8763424×
            self.oxy.join("ops").join("lock"),
8773424×
            "another oxy process holds the operation log",
878
        )
8793424×
    }
880
88114008×
    fn head_ref(&self) -> Result<ObjectRef> {
88214008×
        Ok(self.read_head()?.0)
88314008×
    }
884
885
    /// The operation head, and on a store its record's version for
886
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
887
    /// any other store (a bucket, or memory in tests) it is the store's
888
    /// [`HEAD_RECORD`] reference record (oxygen#68).
88916989×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
89016989×
        if self.store.is_local() {
89116970×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
89216970×
            let r = ObjectRef::from_hex(hex.trim())
89316970×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
89416967×
            return Ok((r, None));
89519×
        }
89619×
        let backend = self.store.backend();
89719×
        match backend.read_ref(HEAD_RECORD) {
89819×
            Ok(Some((bytes, version))) => {
89919×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
9000×
                    || {
9010×
                        RepoError::Msg(format!(
9020×
                            "the operation head in {} is corrupt",
9030×
                            backend.describe()
9040×
                        ))
9050×
                    },
9060×
                )?;
90719×
                Ok((r, Some(version)))
908
            }
9090×
            Ok(None) => fail(format!(
910
                "{} holds no operation log (no {HEAD_RECORD} record)",
9110×
                backend.describe()
912
            )),
9130×
            Err(e) => fail(format!("read the operation head: {e}")),
914
        }
91516989×
    }
916
917
    /// Move the operation head to `to` from the `expected` version
918
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
919
    /// disk the caller holds the operations lock and the head always
920
    /// moves; on a store it moves only if the record is unchanged, and
921
    /// `false` says another process moved it first.
9223434×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
9233434×
        if self.store.is_local() {
9243424×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
9253418×
            return Ok(true);
92610×
        }
92710×
        match self
92810×
            .store
92910×
            .backend()
93010×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
931
        {
9327×
            Ok(_) => Ok(true),
9333×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
9340×
            Err(e) => fail(format!("move the operation head: {e}")),
935
        }
9363434×
    }
937
938
    /// Three-way merge of two views that both started from `base` (spec
939
    /// §12.1). A reference only one side changed takes that side's value.
940
    /// When both changed it differently: a bookmark keeps both sides'
941
    /// heads (it may then have several), a change beats a deletion, a
942
    /// workspace changed by both is an error (only one of them matches the
943
    /// files on disk), and otherwise this process's value wins for remote
944
    /// references and the policy, the first value for a tag (tags never
945
    /// move).
9469×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
94730×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
94830×
            b: &BTreeMap<K, V>,
94930×
            o: &BTreeMap<K, V>,
95030×
            t: &BTreeMap<K, V>,
95130×
            mut both: impl FnMut(&V, &V) -> Result<V>,
95230×
        ) -> Result<BTreeMap<K, V>> {
95330×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
95430×
            let mut out = BTreeMap::new();
95531×
            for k in keys {
95631×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
95731×
                let v = if ov == tv || tv == bv {
95815×
                    ov.cloned()
95916×
                } else if ov == bv {
96010×
                    tv.cloned()
961
                } else {
9626×
                    match (ov, tv) {
9636×
                        (Some(x), Some(y)) => Some(both(x, y)?),
9640×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
9650×
                        (None, None) => None,
966
                    }
967
                };
96830×
                if let Some(v) = v {
96930×
                    out.insert(k.clone(), v);
97030×
                }
971
            }
97229×
            Ok(out)
97330×
        }
9749×
        let bookmarks = pick(
9759×
            &base.bookmarks,
9769×
            &ours.bookmarks,
9779×
            &theirs.bookmarks,
9785×
            |x, y| {
9795×
                let mut heads = self.store.get_state(x)?.heads;
9805×
                heads.extend(self.store.get_state(y)?.heads);
9815×
                let heads = self.load_state(&heads)?.maximal(&heads);
9825×
                Ok(self.store.put_state(&StateObject::new(heads))?)
9835×
            },
9840×
        )?;
985
        // Two operations that both replaced one workspace's working copy
986
        // cannot both be right: the files on disk match only one of them.
987
        // The working-copy lock keeps this from happening; should it happen
988
        // anyway, this operation is not recorded.
9899×
        let workspaces = pick(
9909×
            &base.workspaces,
9919×
            &ours.workspaces,
9929×
            &theirs.workspaces,
9931×
            |_, _| {
9941×
                fail(
995
                    "another oxy process changed this working copy at the same time; \
996
                     this command was not recorded: check `oxy status` and run it again",
997
                )
9981×
            },
9991×
        )?;
10008×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
10018×
        let empty = BTreeMap::new();
10028×
        let names: BTreeSet<&String> = base
10038×
            .remotes
10048×
            .keys()
10058×
            .chain(ours.remotes.keys())
10068×
            .chain(theirs.remotes.keys())
10078×
            .collect();
10088×
        let mut remotes = BTreeMap::new();
10098×
        for n in names {
10104×
            let m = pick(
10114×
                base.remotes.get(n).unwrap_or(&empty),
10124×
                ours.remotes.get(n).unwrap_or(&empty),
10134×
                theirs.remotes.get(n).unwrap_or(&empty),
10140×
                |x, _| Ok(*x),
10150×
            )?;
10164×
            if !m.is_empty() {
10174×
                remotes.insert(n.clone(), m);
10184×
            }
1019
        }
10208×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
10218×
            ours.policy
10220×
        } else if ours.policy == base.policy {
10230×
            theirs.policy
1024
        } else {
10250×
            ours.policy.or(theirs.policy)
1026
        };
10278×
        self.store.flush()?;
10288×
        Ok(View {
10298×
            bookmarks,
10308×
            workspaces,
10318×
            remotes,
10328×
            policy,
10338×
            tags,
10348×
        })
10359×
    }
1036
103748×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
103848×
        let mut out = Vec::new();
103948×
        let (mut r, mut op) = self.head_op()?;
1040
        loop {
1041261×
            let next = op.parents.first().copied();
1042261×
            out.push((r, op));
1043261×
            match next {
1044213×
                Some(p) => {
1045213×
                    r = p;
1046213×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1047
                }
104848×
                None => break,
1049
            }
1050
        }
105148×
        Ok(out)
105248×
    }
1053
1054
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1055
    ///
1056
    /// The command undone is the newest one this workspace ran: operations
1057
    /// that only recorded a working-copy snapshot are skipped (the files are
1058
    /// still on disk and the next snapshot recreates them), as are pushes
1059
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1060
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1061
    /// operations are never undone, and a command an earlier undo already
1062
    /// reverted is passed over, so undoing again goes further back.
1063
    ///
1064
    /// When nothing newer came from another workspace, the operation head
1065
    /// moves back to before the command. Otherwise the command is reverted
1066
    /// in place: every reference it changed goes back to its value before
1067
    /// it, recorded as a new operation that names it, and anything another
1068
    /// workspace changed since is kept. A reference both the command and a
1069
    /// later operation of another workspace changed is not guessed at: the
1070
    /// undo is refused, naming it.
1071
    ///
1072
    /// When the working copy is clean and was clean after the command's
1073
    /// predecessor, its files follow too, since nothing on disk can be
1074
    /// lost; otherwise they stay as they are (an undone commit's edits come
1075
    /// back as uncommitted work).
107616×
    pub fn undo(&self) -> Result<Undone> {
107716×
        let _wc = self.lock_working_copy()?;
107816×
        let clean_now =
107916×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
108016×
        let (head_ref, head) = self.head_op()?;
108116×
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
108240×
        let load = |r: &ObjectRef| -> Result<Op> {
108340×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
108440×
        };
108516×
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
108616×
        let mut pending_checkout: Option<Op> = None;
108716×
        let mut others = 0usize;
108816×
        let (mut r, mut op) = (head_ref, head.clone());
108915×
        let (target_ref, target, parent) = loop {
109041×
            let parent = match op.parents.first() {
109140×
                Some(p) => Some((*p, load(p)?)),
10921×
                None => None,
1093
            };
109441×
            if skip.contains(&r) {
10951×
                pending_checkout = None;
109640×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
109710×
                // A push cannot be taken back: undoing it would only make
109810×
                // this repository forget what the remote holds.
109930×
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
110010×
                others += 1;
110120×
            } else if let Some(u) = op.undoes {
11021×
                skip.insert(u);
11031×
                pending_checkout = None;
110419×
            } else if op.command.ends_with(" (checkout)") {
11053×
                pending_checkout = Some(op.clone());
11063×
            } else {
110716×
                match parent {
110815×
                    Some((_, p)) => break (r, op, p),
11091×
                    None => return fail("nothing to undo in this workspace"),
1110
                }
1111
            }
111225×
            match parent {
111325×
                Some((pr, p)) => (r, op) = (pr, p),
11140×
                None => return fail("nothing to undo in this workspace"),
1115
            }
1116
        };
111715×
        let before = parent.view;
111815×
        let after = pending_checkout
111915×
            .map(|o| o.view)
112015×
            .unwrap_or_else(|| target.view.clone());
112115×
        let changes = self.view_changes(&before, &after)?;
112215×
        let pushed = self.pushed_by(&before, &after, &head.view)?;
112315×
        let restored_wc = before.workspaces.get(&self.workspace).copied();
112415×
        if others == 0 {
1125
            // Only this workspace's operations since: move the head back.
112610×
            let _lock = if self.store.is_local() {
112710×
                Some(self.lock_ops()?)
1128
            } else {
11290×
                None
1130
            };
113110×
            let parent_ref = *target.parents.first().expect("the target has a parent");
113210×
            let (now, version) = self.read_head()?;
113310×
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
11340×
                return fail("another oxy command ran while undoing; run undo again");
113510×
            }
1136
        } else {
11375×
            let view = self.revert_view(&head.view, &before, &after)?;
11383×
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1139
        }
114013×
        self.drop_manifest();
114113×
        if let Some(then) = restored_wc {
114213×
            if clean_now && Some(then) != wc_now {
1143
                // Past `core.snapshot-retention` the working copy may be
1144
                // gone: the files then stay as they are.
114510×
                let Ok(wc) = self.store.get_change(&then) else {
11460×
                    return Ok(Undone {
11470×
                        command: target.command,
11480×
                        changes,
11490×
                        others_kept: others,
11500×
                        pushed,
11510×
                    });
1152
                };
115310×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
11548×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1155
                    // The files differ from the restored working copy by
1156
                    // exactly what the undone command did: nothing else is
1157
                    // on disk, as the working copy was clean.
11588×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
11592×
                }
11603×
            }
11610×
        }
116213×
        Ok(Undone {
116313×
            command: target.command,
116413×
            changes,
116513×
            others_kept: others,
116613×
            pushed,
116713×
        })
116816×
    }
1169
1170
    /// Whether operation `op` was a push: it changed only what this
1171
    /// repository knows of remotes.
117231×
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
117331×
        let Some(p) = parent else {
11741×
            return false;
1175
        };
117630×
        op.command.starts_with("oxy push")
11771×
            && op.view.bookmarks == p.view.bookmarks
11781×
            && op.view.tags == p.view.tags
11791×
            && op.view.workspaces == p.view.workspaces
11801×
            && op.view.policy == p.view.policy
118131×
    }
1182
1183
    /// Whether operation `op` (whose predecessor is `parent`) was this
1184
    /// workspace's. Operations record their workspace (oxygen#99); for older
1185
    /// ones it is read from the view: one that changed only other
1186
    /// workspaces' working copies was theirs, anything else counts as ours.
118730×
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
118830×
        if let Some(w) = op.workspace {
118930×
            return w == self.workspace;
11900×
        }
11910×
        let Some(p) = parent else {
11920×
            return true;
1193
        };
11940×
        let ids: BTreeSet<&WorkspaceId> = op
11950×
            .view
11960×
            .workspaces
11970×
            .keys()
11980×
            .chain(p.view.workspaces.keys())
11990×
            .collect();
12000×
        let moved: Vec<&WorkspaceId> = ids
12010×
            .into_iter()
12020×
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
12030×
            .collect();
12040×
        moved.is_empty() || moved.contains(&&self.workspace)
120530×
    }
1206
1207
    /// `current` with what changed from `before` to `after` put back, this
1208
    /// workspace's working copy included; refused when a later operation
1209
    /// changed one of the same references again.
12105×
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
121110×
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
121210×
            cur: &mut BTreeMap<K, V>,
121310×
            before: &BTreeMap<K, V>,
121410×
            after: &BTreeMap<K, V>,
121510×
            name: impl Fn(&K) -> String,
121610×
            clashes: &mut Vec<String>,
121710×
        ) {
121810×
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
121910×
            for k in keys {
12205×
                let (b, a) = (before.get(k), after.get(k));
12215×
                if a == b {
12224×
                    continue;
12231×
                }
12241×
                if cur.get(k) != a {
12251×
                    clashes.push(name(k));
12261×
                    continue;
12270×
                }
12280×
                match b {
12290×
                    Some(v) => cur.insert(k.clone(), v.clone()),
12300×
                    None => cur.remove(k),
1231
                };
1232
            }
123310×
        }
12345×
        let mut out = current.clone();
12355×
        let mut clashes = Vec::new();
1236
        // A bookmark another workspace moved since is put back head by
1237
        // head: the heads the command added go, the heads it replaced
1238
        // return, and the other workspace's heads stay. Only when a later
1239
        // change was built on one the command added is that not possible.
12405×
        let names: BTreeSet<&String> = before
12415×
            .bookmarks
12425×
            .keys()
12435×
            .chain(after.bookmarks.keys())
12445×
            .collect();
12458×
        for name in names {
12468×
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
12478×
            let cur = current.bookmarks.get(name);
12488×
            if a == b {
12494×
                continue;
12504×
            }
12514×
            if cur == a {
12522×
                match b {
12532×
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
12540×
                    None => out.bookmarks.remove(name),
1255
                };
12562×
                continue;
12572×
            }
12582×
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
12590×
                clashes.push(format!("bookmark {name}"));
12600×
                continue;
1261
            };
12622×
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
12632×
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
12642×
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
12652×
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
12662×
            if !added.iter().all(|h| now.contains(h)) {
12671×
                clashes.push(format!(
1268
                    "bookmark {name} (a later change builds on this one)"
1269
                ));
12701×
                continue;
12711×
            }
12721×
            let mut heads: Vec<ChangeHash> = now
12731×
                .iter()
12743×
                .filter(|h| !added.contains(h))
12751×
                .chain(was.difference(&became))
12761×
                .copied()
12771×
                .collect();
12781×
            heads.sort();
12791×
            heads.dedup();
12801×
            let heads = self.load_state(&heads)?.maximal(&heads);
12811×
            out.bookmarks.insert(
12821×
                name.clone(),
12831×
                self.store.put_state(&StateObject::new(heads))?,
1284
            );
1285
        }
1286
12875×
        back(
12885×
            &mut out.tags,
12895×
            &before.tags,
12905×
            &after.tags,
12910×
            |k| format!("tag {k}"),
12925×
            &mut clashes,
1293
        );
12945×
        let mine = self.workspace;
129515×
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
129615×
            v.workspaces
129715×
                .iter()
129829×
                .filter(|(k, _)| **k != mine)
129915×
                .map(|(k, v)| (*k, *v))
130015×
                .collect()
130115×
        };
13025×
        let mut theirs = others(&out);
13035×
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
13041×
            Some(p) => format!("the workspace at {}", p.display()),
13050×
            None => format!("workspace {}", id.to_hex()),
13061×
        };
13075×
        back(
13085×
            &mut theirs,
13095×
            &others(before),
13105×
            &others(after),
13115×
            workspace_name,
13125×
            &mut clashes,
1313
        );
13145×
        let empty = BTreeMap::new();
13155×
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
13165×
        for n in names {
13170×
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
13180×
            back(
13190×
                &mut cur,
13200×
                before.remotes.get(n).unwrap_or(&empty),
13210×
                after.remotes.get(n).unwrap_or(&empty),
13220×
                |k| format!("{n}/{k}"),
13230×
                &mut clashes,
1324
            );
13250×
            if cur.is_empty() {
13260×
                out.remotes.remove(n);
13270×
            } else {
13280×
                out.remotes.insert(n.clone(), cur);
13290×
            }
1330
        }
13315×
        if before.policy != after.policy {
13320×
            if out.policy == after.policy {
13330×
                out.policy = before.policy;
13340×
            } else {
13350×
                clashes.push("the policy".into());
13360×
            }
13375×
        }
13385×
        if !clashes.is_empty() {
13392×
            return fail(format!(
1340
                "undo would also take back what another workspace has done since to {}; \
1341
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
13422×
                clashes.join(", ")
1343
            ));
13443×
        }
13453×
        out.workspaces = theirs;
13463×
        match before.workspaces.get(&mine) {
13473×
            Some(wc) => out.workspaces.insert(mine, *wc),
13480×
            None => out.workspaces.remove(&mine),
1349
        };
13503×
        Ok(out)
13515×
    }
1352
1353
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1354
    /// in `now` already holds: undoing them locally leaves them there.
135515×
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
135615×
        let mut out = Vec::new();
135718×
        for (name, st) in &after.bookmarks {
135818×
            if before.bookmarks.get(name) == Some(st) {
13594×
                continue;
136014×
            }
136114×
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
136214×
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
13630×
                None => BTreeSet::new(),
1364
            };
136514×
            let added: Vec<ChangeHash> = self
136614×
                .store
136714×
                .get_state(st)?
1368
                .heads
136914×
                .into_iter()
137020×
                .filter(|h| !had.contains(h))
137114×
                .collect();
137214×
            if added.is_empty() {
13731×
                continue;
137413×
            }
137513×
            for (remote, bookmarks) in &now.remotes {
13761×
                if let Some(rs) = bookmarks.get(name) {
13771×
                    let theirs = self.store.get_state(rs)?.heads;
13781×
                    if added.iter().any(|h| theirs.contains(h)) {
13791×
                        out.push((name.clone(), remote.clone()));
13801×
                    }
13810×
                }
1382
            }
1383
        }
138415×
        Ok(out)
138515×
    }
1386
1387
    /// The last operation that was not a snapshot.
13882×
    pub fn last_command(&self) -> Result<Op> {
13892×
        let (_, mut op) = self.head_op()?;
13904×
        while op.is_snapshot() {
13912×
            let Some(parent) = op.parents.first() else {
13920×
                break;
1393
            };
13942×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1395
        }
13962×
        Ok(op)
13972×
    }
1398
1399
    // ------------------------------------------------------------ states
1400
1401
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1402199×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1403199×
        if let Some(st) = self.load_state_checkpointed(heads)? {
14044×
            return Ok(st);
1405194×
        }
1406194×
        self.load_state_full(heads)
1407199×
    }
1408
1409
    /// The state of `heads` for its history (changes, tree, metadata) with
1410
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1411
    /// and friends. Build the graphs a command needs with
1412
    /// [`Repo::load_graphs_of`].
14131725×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
14141725×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
141531×
            return Ok(st);
14161694×
        }
14171694×
        self.load_state_replayed(heads, State::new_history_only())
14181725×
    }
1419
1420
    /// Build these file graphs in a history-only state.
14211820×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
14221820×
        state
14231820×
            .load_graphs(
14241820×
                nodes,
142554×
                |refs| {
142654×
                    self.read_blobs(refs).map_err(|e| {
14273×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14283×
                    })
142954×
                },
14302098×
                |h| self.change_bytes(h),
1431
            )
14321820×
            .map_err(|e| self.index_damage(e))
14331820×
    }
1434
1435
    /// An error building graphs, and when it is a state index found
1436
    /// damaged (a file's history that does not match its hash), the
1437
    /// workspace's state indexes removed: they are rebuilt from history by
1438
    /// the next command.
14394×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
14404×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
14413×
            return e.into();
1442
        };
14432×
        for path in self.state_indexes() {
14442×
            let _ = fs::remove_file(path);
14452×
        }
14461×
        RepoError::Msg(format!(
14471×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
14481×
        ))
14494×
    }
1450
1451
    /// The graphs of `nodes` of a history-only state, built beside it (see
1452
    /// [`State::build_graphs_detached`]).
145377×
    pub fn build_graphs_detached(
145477×
        &self,
145577×
        state: &State,
145677×
        nodes: &[crate::ids::NodeId],
145777×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
145877×
        Ok(state
145977×
            .build_graphs_detached(
146077×
                nodes,
14610×
                |refs| {
14620×
                    self.read_blobs(refs).map_err(|e| {
14630×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14640×
                    })
14650×
                },
146683×
                |h| self.change_bytes(h),
1467
            )
146877×
            .map_err(|e| self.index_damage(e))?
146977×
            .into_iter()
147077×
            .collect())
147177×
    }
1472
1473
    /// The contents of texts [`State::single_text`] gave: blobs read in
1474
    /// one go, inline ones from their changes.
1475360×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1476
        use crate::objects::TextRef;
1477360×
        let refs: Vec<ObjectRef> = texts
1478360×
            .iter()
14795548×
            .filter_map(|t| match t {
14801×
                TextRef::Blob(r, _, _) => Some(*r),
14815547×
                TextRef::Inline { .. } => None,
14825548×
            })
1483360×
            .collect();
1484360×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1485360×
        let mut out = Vec::with_capacity(texts.len());
14865548×
        for t in texts {
14875548×
            let lines = match t {
14881×
                TextRef::Blob(_, count, form) => {
14891×
                    let content = blobs
14901×
                        .next()
14911×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
14921×
                    crate::objects::text_lines(&content, *count, *form)?
1493
                }
14945547×
                TextRef::Inline { change, start, end } => {
14955547×
                    let bytes = self.change_bytes(change)?;
14965547×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
14970×
                        RepoError::Msg("an inline insert lies outside its change".into())
14980×
                    })?;
14995547×
                    crate::objects::inline_lines(range)?
1500
                }
1501
            };
15025548×
            out.push(lines.bytes().to_vec());
1503
        }
1504360×
        Ok(out)
1505360×
    }
1506
1507
    /// Build every graph a history-only state still lacks, making it full.
15081853×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
15091853×
        state
15101853×
            .load_all_graphs(
151116×
                |refs| {
151216×
                    self.read_blobs(refs).map_err(|e| {
15130×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15140×
                    })
151516×
                },
15163874×
                |h| self.change_bytes(h),
1517
            )
15181853×
            .map_err(|e| self.index_damage(e))
15191853×
    }
1520
1521
    /// A change's encoding, for building graphs of its inline inserts. The
1522
    /// last few read are kept: a checkout building graphs a batch at a
1523
    /// time reads the same large changes for every batch, often in turn.
152411602×
    fn change_bytes(
152511602×
        &self,
152611602×
        h: &ChangeHash,
152711602×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
152811602×
        let mut cache = self.last_change.borrow_mut();
152920018×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
15309060×
            let hit = cache.remove(i);
15319060×
            let b = hit.1.clone();
15329060×
            cache.push(hit);
15339060×
            return Ok(b);
15342542×
        }
15352542×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
15360×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
15370×
        })?);
15382542×
        cache.push((*h, b.clone()));
1539
        // The last few, within a memory budget; the newest always stays.
15404093×
        while cache.len() > CHANGE_CACHE_COUNT
15412542×
            || (cache.len() > 1
15427630×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15431551×
        {
15441551×
            cache.remove(0);
15451551×
        }
15462542×
        Ok(b)
154711602×
    }
1548
1549
    /// Load the dependency closure of `heads` change by change.
1550248×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1551248×
        self.load_state_replayed(heads, State::new())
1552248×
    }
1553
15543322×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
15553322×
        let history = state.is_history_only();
15563322×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
15573322×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1558
        {
15593322×
            let _t = crate::timing::phase("load: read and add changes");
15603322×
            let (mut read, mut add, mut fetch) = (
15613322×
                std::time::Duration::ZERO,
15623322×
                std::time::Duration::ZERO,
15633322×
                std::time::Duration::ZERO,
15643322×
            );
156513360×
            while let Some(h) = stack.pop() {
1566
                // A change the state holds brings its history with it.
156710041×
                if !seen.insert(h) || state.contains(&h) {
15682369×
                    continue;
15697672×
                }
15707672×
                let t0 = std::time::Instant::now();
1571
                // A history-only state reads text only for the graphs it
1572
                // builds; either way the hash is the one asked for.
15737672×
                let (c, texts) = if history {
15746410×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
15756409×
                    fetch += t0.elapsed();
15766409×
                    Change::decode_skeleton(&bytes, h)
15776409×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1578
                } else {
15791262×
                    (self.store.get_change(&h)?, Vec::new())
1580
                };
15817669×
                read += t0.elapsed();
15827669×
                stack.extend(c.deps.iter().copied());
15837669×
                let t1 = std::time::Instant::now();
15847669×
                state.add_known(h, c, texts);
15857669×
                add += t1.elapsed();
1586
            }
15873319×
            crate::timing::record("load:   of which reading", read);
15883319×
            crate::timing::record("load:     of which fetching", fetch);
15893319×
            crate::timing::record("load:   of which applying", add);
1590
        }
15913319×
        let _t = crate::timing::phase("load: validate");
15923319×
        state.validate()?;
15933319×
        Ok(state)
15943322×
    }
1595
15962371×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
15972371×
        if self.bare {
15982×
            return fail("this is a bare repository: it has no working copy");
15992369×
        }
16002369×
        let view = self.view()?;
16012369×
        let h = *view
16022369×
            .workspaces
16032369×
            .get(&self.workspace)
16042369×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
16052368×
        Ok((h, self.store.get_change(&h)?))
16062371×
    }
1607
1608
    /// Heads of a bookmark's state (spec §10.1).
16091803×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
16101803×
        match view.bookmarks.get(bookmark) {
16111803×
            Some(st) => Ok(self.store.get_state(st)?.heads),
16120×
            None => Ok(vec![]),
1613
        }
16141803×
    }
1615
1616509×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1617509×
        self.heads_of(&self.view()?, &self.config.bookmark)
1618509×
    }
1619
1620
    // ------------------------------------------------------------ blobs
1621
1622399×
    fn blob_for(content: &[u8]) -> Blob {
1623399×
        Blob::of(content)
1624399×
    }
1625
1626246×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1627246×
        Self::blob_for(content).hash()
1628246×
    }
1629
1630151×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1631194×
        for c in crate::chunk::chunks(content) {
1632194×
            self.store.put_chunk(c)?;
1633
        }
1634151×
        Ok(self
1635151×
            .store
1636151×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1637151×
    }
1638
1639
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1640
    /// all their chunks, are read in parallel; a blob the store lacks goes
1641
    /// through [`Repo::read_blob`], which may fetch it lazily.
1642434×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1643434×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1644434×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
164580×
            blobs.push(match got {
164675×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
16470×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
16485×
                Err(crate::store::StoreError::NotFound(_)) => None,
16490×
                Err(e) => return Err(e.into()),
1650
            });
1651
        }
1652434×
        let chunk_refs: Vec<ObjectRef> = blobs
1653434×
            .iter()
1654434×
            .flatten()
1655434×
            .flat_map(|b| b.chunks.iter().copied())
1656434×
            .collect();
1657434×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1658434×
        let mut out = Vec::with_capacity(refs.len());
1659434×
        for (r, blob) in refs.iter().zip(blobs) {
166080×
            match blob {
16615×
                None => out.push(self.read_blob(r)?),
166275×
                Some(b) => {
166375×
                    let mut content = Vec::with_capacity(b.length as usize);
1664114×
                    for c in &b.chunks {
1665114×
                        match chunks.next() {
1666114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
16670×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
16680×
                            Some(Err(e)) => return Err(e.into()),
16690×
                            None => return fail("chunk list ended early"),
1670
                        }
1671
                    }
167275×
                    out.push(content);
1673
                }
1674
            }
1675
        }
1676429×
        Ok(out)
1677434×
    }
1678
1679
    /// Read a blob's content, fetching it from the remote that withheld it
1680
    /// when it is lazily absent (spec §13.5).
1681113×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1682113×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
16834×
            self.fetch_lazy_blob(r)?;
1684109×
        }
1685113×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1686108×
        let mut out = Vec::with_capacity(blob.length as usize);
1687135×
        for c in &blob.chunks {
1688135×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1689
        }
1690108×
        Ok(out)
1691113×
    }
1692
1693
    // ------------------------------------------------------------ working copy
1694
1695
    /// Attributes from the `.oxyattributes` files in the working directory.
16962×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1697
        // Nested repositories and ignored paths are left out, as in a walk.
16988×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
16992×
        let files: Vec<(String, Vec<u8>)> = listing
17002×
            .files
17012×
            .into_iter()
17022×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
17032×
            .collect();
17042×
        crate::attributes::Attributes::from_files(
17052×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1706
        )
17072×
    }
1708
1709
    /// Folders holding a repository of their own that the last look at the
1710
    /// working copy left out, not being subrepos (oxygen#43).
171129×
    pub fn untracked_nested(&self) -> Vec<String> {
171229×
        self.untracked_nested.borrow().clone()
171329×
    }
1714
1715
    /// New untracked files the last snapshot left out for being larger than
1716
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
171733×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
171833×
        self.skipped_large.borrow().clone()
171933×
    }
1720
1721
    /// Attributes from a materialized state's `.oxyattributes` files.
17223×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
17236×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
17246×
            match &f.content {
17256×
                FileContent::Text { bytes, .. }
17266×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1727
                {
17280×
                    Some((p.as_str(), bytes.as_slice()))
1729
                }
17306×
                _ => None,
1731
            }
17326×
        }))
17333×
    }
1734
1735
    /// Store a blob, raw when the path is `nocompress`.
1736132×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1737132×
        if !nocompress {
1738130×
            return self.store_blob(content);
17392×
        }
17402×
        for c in crate::chunk::chunks(content) {
17412×
            self.store.put_chunk_nocompress(c)?;
1742
        }
17432×
        Ok(self
17442×
            .store
17452×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1746132×
    }
1747
1748
    /// This workspace's state index (oxygen#41): its working copy's base,
1749
    /// saved so a snapshot reads it rather than replaying history.
1750
    /// The state index of the state with these heads: this workspace keeps
1751
    /// the last few it used, named by their heads, so moving between two
1752
    /// states finds both.
17532460×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
17542460×
        let mut heads = heads.to_vec();
17552460×
        heads.sort();
17562460×
        let mut h = blake3::Hasher::new();
17572488×
        for c in &heads {
17582488×
            h.update(&c.0);
17592488×
        }
17602460×
        self.oxy.join("index").join(format!(
17612460×
            "{}{}",
17622460×
            self.state_index_prefix(),
17632460×
            &h.finalize().to_hex()[..16]
17642460×
        ))
17652460×
    }
1766
17674825×
    fn state_index_prefix(&self) -> String {
17684825×
        format!("state-{}-", self.workspace.to_hex())
17694825×
    }
1770
1771
    /// This workspace's state indexes, newest first.
17722365×
    fn state_indexes(&self) -> Vec<PathBuf> {
17732365×
        let prefix = self.state_index_prefix();
17742365×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
17752365×
            .into_iter()
17762365×
            .flatten()
17772365×
            .flatten()
17782365×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
17792365×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
17802365×
            .collect();
17812365×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
17822365×
        found.into_iter().map(|(_, p)| p).collect()
17832365×
    }
1784
1785
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1786
    /// from this workspace's state index when it holds that history: every
1787
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1788
    /// is loaded from history and indexed for next time.
17892053×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
17902053×
        if let Some((st, heads)) = self.read_state_index(deps) {
17911654×
            let mut have = st.maximal(deps);
17921654×
            have.sort();
17931654×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1794
                // Re-encoding reads every history: one found damaged is
1795
                // left to the build that reads it, which reports it.
1796
                #[cfg(test)]
1797161×
                if let Some(mine) = st.write_index() {
1798160×
                    assert_eq!(
1799160×
                        Some(mine),
1800160×
                        self.load_state_history(deps)?.write_index(),
1801
                        "a state index holds the state history gives"
1802
                    );
18031×
                }
1804274×
                return Ok(st);
18051380×
            }
1806
            // An index a few changes behind (a commit, a pull since): add
1807
            // what it lacks, as long as all it holds is history of `deps`.
1808
            // Anything amiss (a change beyond a shallow boundary) takes the
1809
            // long way instead.
18101380×
            let (indexed, started) = (st.len(), std::time::Instant::now());
18111380×
            if let Ok(st) = self.load_state_replayed(deps, st) {
18121379×
                let mut all = deps.to_vec();
18131379×
                all.extend(heads.iter().copied());
18141379×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
18151379×
                within.sort();
18161379×
                want.sort();
18171379×
                if within == want {
1818
                    #[cfg(test)]
1819705×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1820
                    // Writing the index costs far more than replaying a
1821
                    // few small changes: it is rewritten once it falls
1822
                    // behind, or when replaying took long (large changes).
18231377×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
18241377×
                        || started.elapsed() > INDEX_REPLAY_TIME
18254×
                    {
18264×
                        self.write_state_index(deps, &st);
18271373×
                    }
18281377×
                    return Ok(st);
18292×
                }
18301×
            }
1831399×
        }
1832402×
        let st = self.load_state_history(deps)?;
1833402×
        self.write_state_index(deps, &st);
1834402×
        Ok(st)
18352053×
    }
1836
1837
    /// Two history-only states hold the same changes and render the same
1838
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1839
    /// the checkpoint's graphs as the bases of its files' histories.
1840
    #[cfg(test)]
1841705×
    fn assert_same_state(&self, a: &State, b: &State) {
18421410×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1843705×
        assert_eq!(ids(a), ids(b), "the same changes");
18441410×
        let files = |s: &State| {
18451410×
            let mut s = s.clone();
18461410×
            self.load_all_graphs(&mut s).unwrap();
18471410×
            s.materialize().files
18481410×
        };
1849705×
        assert_eq!(files(a), files(b), "the same files");
1850705×
    }
1851
1852
    /// The state index file: its heads, a hash of its changes block and one
1853
    /// of the rest, then the body [`State::write_index`] gives, whose first
1854
    /// block is the changes. Hashed in two parts so the log can read and
1855
    /// check the changes alone.
1856
    /// The index of `deps` if there is one, else the newest, which the
1857
    /// caller may bring up to date.
18582053×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1859
        use std::io::Read;
18602053×
        let _t = crate::timing::phase("load: state index");
18612053×
        let exact = self.state_index_path(deps);
18622053×
        let reading = crate::timing::phase("load:   of which reading the file");
18632053×
        let mut f = match fs::File::open(&exact) {
1864274×
            Ok(f) => {
1865
                // Used now: the newest, so the last to be dropped.
1866274×
                let _ = fs::File::options()
1867274×
                    .write(true)
1868274×
                    .open(&exact)
1869274×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1870274×
                f
1871
            }
18721779×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1873
        };
18741654×
        let total = f.metadata().ok()?.len();
18751654×
        let mut word = [0u8; 4];
18761654×
        f.read_exact(&mut word).ok()?;
18771654×
        let n = u32::from_le_bytes(word) as usize;
18781654×
        let mut head = vec![0u8; 32 * n + 64 + 8];
18791654×
        f.read_exact(&mut head).ok()?;
18801654×
        let heads: Vec<ChangeHash> = head[..32 * n]
18811654×
            .chunks_exact(32)
18821654×
            .map(|c| ObjectRef(c.try_into().unwrap()))
18831654×
            .collect();
18841654×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
18851654×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
18861654×
        let at = (4 + head.len()) as u64;
18871654×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
18880×
            return None;
18891654×
        }
1890
        // The front only: the files' histories after it are read, each
1891
        // checked by its own hash, when a command builds that file.
18921654×
        let mut front = vec![0u8; front_len as usize];
18931654×
        f.read_exact(&mut front).ok()?;
18941654×
        drop(reading);
18951654×
        let checking = crate::timing::phase("load:   of which checking the file");
18961654×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
18971654×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
18983308×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
18991654×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
19000×
            return None;
19011654×
        }
19021654×
        drop(checking);
19031654×
        let histories = crate::state::Histories::File(
19041654×
            std::sync::Arc::new(f),
19051654×
            at + front_len,
19061654×
            total - at - front_len,
19071654×
        );
19081654×
        Some((State::read_index_front(&front, histories).ok()?, heads))
19092053×
    }
1910
1911
    /// The changes of this workspace's state index (the closure of its
1912
    /// heads), read without the rest of the index.
1913
    #[allow(clippy::type_complexity)]
1914177×
    pub(crate) fn read_state_index_changes(
1915177×
        &self,
1916177×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1917
        use std::io::Read;
1918177×
        let _t = crate::timing::phase("load: state index changes");
1919177×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1920160×
        let mut word = [0u8; 4];
1921160×
        f.read_exact(&mut word).ok()?;
1922160×
        let n = u32::from_le_bytes(word) as usize;
1923
        // Heads, the two sums, the front's length, then the changes block.
1924160×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1925160×
        f.read_exact(&mut head).ok()?;
1926160×
        let heads: Vec<ChangeHash> = head[..32 * n]
1927160×
            .chunks_exact(32)
1928160×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1929160×
            .collect();
1930160×
        let sum = &head[32 * n..32 * n + 32];
1931160×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1932160×
        let mut changes = vec![0u8; 4 + len];
1933160×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1934160×
        f.read_exact(&mut changes[4..]).ok()?;
1935160×
        let checking = crate::timing::phase("load:   of which checking");
1936160×
        let mut h = blake3::Hasher::new();
1937160×
        h.update_rayon(&changes);
1938160×
        if h.finalize().as_bytes() != sum {
19390×
            return None;
1940160×
        }
1941160×
        drop(checking);
1942160×
        let _decoding = crate::timing::phase("load:   of which decoding");
1943160×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
1944177×
    }
1945
1946
    /// Save `st`, the history-only state of `deps`, as this workspace's
1947
    /// state index; quietly nothing when it cannot be (it is only a cache).
1948407×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1949407×
        let _t = crate::timing::phase("write: state index");
1950407×
        let encoding = crate::timing::phase("write:   of which encoding");
1951407×
        let Some(body) = st.write_index() else {
19520×
            return;
1953
        };
1954407×
        drop(encoding);
1955
        #[cfg(test)]
1956222×
        assert_eq!(
1957222×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1958222×
            Some(body.clone()),
1959
            "a state index reads back as written"
1960
        );
1961407×
        let mut heads = st.maximal(deps);
1962407×
        heads.sort();
1963407×
        let mut w = crate::flat::Writer::default();
1964407×
        w.count(heads.len());
1965407×
        for h in &heads {
196618×
            w.object(h);
196718×
        }
1968
        // The body is the front's length, the front, then the files'
1969
        // histories, which carry their own hashes: the sums cover the
1970
        // front's changes block and the rest of the front.
1971407×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
1972407×
        let front = &body[8..8 + front_len];
1973407×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
1974814×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1975407×
        w.fixed(&sum(&front[..split]));
1976407×
        w.fixed(&sum(&front[split..]));
1977407×
        w.fixed(&body);
1978407×
        let path = self.state_index_path(&heads);
1979407×
        let _ = fs::create_dir_all(self.oxy.join("index"));
1980407×
        let _ = write_cache(&path, &w.0);
1981
        // The last two used: the index of a state moved away from stays for
1982
        // a move back. Older ones (and the unnamed one of before) go.
1983407×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
19841×
            let _ = fs::remove_file(old);
19851×
        }
1986407×
        let _ = fs::remove_file(
1987407×
            self.oxy
1988407×
                .join("index")
1989407×
                .join(format!("state-{}", self.workspace.to_hex())),
1990407×
        );
1991407×
    }
1992
19936×
    fn locks_dir(&self) -> PathBuf {
19946×
        self.oxy.join("locks")
19956×
    }
1996
1997
    /// Whether `path` is locked locally for editing (spec §18, advisory).
19983×
    pub fn is_locked(&self, path: &str) -> bool {
19993×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
20003×
    }
2001
2002
    /// Take the advisory local lock on a `lockable` file and make it writable.
20032×
    pub fn lock_path(&self, path: &str) -> Result<()> {
20042×
        let attrs = self.disk_attributes();
20052×
        if !attrs.lookup(path).lockable {
20061×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
20071×
        }
20081×
        fs::create_dir_all(self.locks_dir())?;
20091×
        write_atomic(
20101×
            &self.locks_dir().join(path.replace('/', "%2F")),
20111×
            std::process::id().to_string().as_bytes(),
20120×
        )?;
20131×
        set_readonly(&self.root.join(path), false)?;
20141×
        Ok(())
20152×
    }
2016
2017
    /// Release the local lock and make the file read-only again.
20181×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
20191×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
20201×
        if self.root.join(path).exists() {
20211×
            set_readonly(&self.root.join(path), true)?;
20220×
        }
20231×
        Ok(())
20241×
    }
2025
2026
    /// Whether a repository path is inside the sparse filter (spec §17).
202724471×
    pub fn in_scope(&self, path: &str) -> bool {
202824471×
        self.config.sparse_paths.is_empty()
202982×
            || self
203082×
                .config
203182×
                .sparse_paths
203282×
                .iter()
203399×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
203424471×
    }
2035
20361×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
20371×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
20381×
    }
2039
2040
    /// Walk the working copy; with a manifest, a file whose size and mtime
2041
    /// match it is not read: an opaque file yields its known blob, and a
2042
    /// text file whose recorded graph key equals its base graph's key in
2043
    /// `keys` (path → key) is marked unchanged; other text files are read
2044
    /// but keep their known hash. Files modified within two seconds of the
2045
    /// manifest are never trusted (a racy stat).
2046
    ///
2047
    /// `.oxyattributes` files are always read, since their content is
2048
    /// needed; and when any of them is not known unchanged (added, removed,
2049
    /// edited, or changed in the base), no text file is taken as unchanged,
2050
    /// because attributes decide how a file compares with the base.
2051
    ///
2052
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2053
    /// (the base state's files) that exists on disk is included even when
2054
    /// an ignore rule matches it, as in Git.
20551310×
    fn walk_working_copy_with(
20561310×
        &self,
20571310×
        cache: Option<&prompt::Manifest>,
20581310×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
20591310×
        keys: Option<&KeyOf>,
20601310×
    ) -> Result<BTreeMap<String, FsEntry>> {
2061
        let mut out: BTreeMap<String, FsEntry>;
20621310×
        let sparse = &self.config.sparse_paths;
20639197×
        let in_scope = |p: &str| {
20649197×
            sparse.is_empty()
20657×
                || sparse
20667×
                    .iter()
20677×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
20689197×
        };
20691310×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2070
        let walk::Listing {
20711310×
            files,
20721310×
            symlinks,
20731310×
            nested,
20741310×
            dirs,
20751310×
        } = match self.listing_cache.take() {
2076176×
            Some(l) => l,
2077
            // Ignore rules apply to untracked paths only, so the base's
2078
            // files are not matched against them (an added file is: a rule
2079
            // written after it was snapshotted leaves it out again).
20809209×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2081
        };
2082
        // A new file larger than the limit is left out and named, not taken
2083
        // in unseen (oxygen#98): a build's output or a downloaded image
2084
        // would otherwise be stored by the next status, kept by the
2085
        // operation log. Files tracked, or already in the working copy, stay.
20861310×
        let limit = self.config.max_new_file;
20871310×
        let mut skipped = Vec::new();
20881310×
        let files: Vec<_> = files
20891310×
            .into_iter()
209012182×
            .filter(|(rel, _, meta)| {
209112182×
                let new = !tracked.contains_key(rel)
20923125×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
209312182×
                if limit > 0 && new && meta.size > limit {
20943×
                    skipped.push((rel.clone(), meta.size));
20953×
                    return false;
209612179×
                }
209712179×
                true
209812182×
            })
20991310×
            .collect();
21001310×
        *self.skipped_large.borrow_mut() = skipped;
21011310×
        let keys = keys.filter(|k| {
210212167×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
21031307×
            let attrs_unchanged =
21041307×
                files
21051307×
                    .iter()
210612148×
                    .filter(|(r, _, _)| is_attributes(r))
21071307×
                    .all(|(rel, _, meta)| {
21089×
                        stat_cached(rel, meta, cache)
21099×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
21109×
                    });
21111307×
            let none_removed = tracked
21121307×
                .keys()
21139142×
                .filter(|r| is_attributes(r))
21141307×
                .all(|r| on_disk.contains(r.as_str()));
21151307×
            attrs_unchanged && none_removed
21161307×
        });
21171310×
        *self.walked_dirs.borrow_mut() =
21181310×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
21191310×
        drop(walk_phase);
21201310×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2121
        // Reading files is most of a walk's cost; do it in parallel.
2122
        {
2123
            use rayon::prelude::*;
21241310×
            let mut read: Vec<(String, FsEntry)> = files
21251310×
                .par_iter()
212612179×
                .map(|(rel, path, meta)| {
2127
                    // A key is worked out only for a file the manifest
2128
                    // knows with the same stat and a key of its own.
212912179×
                    let key = keys
213012179×
                        .filter(|_| !is_attributes(rel))
213112179×
                        .filter(|_| {
213212139×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
213312139×
                        })
213412179×
                        .and_then(|k| k(rel));
213512179×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
213612179×
                })
21371310×
                .collect::<Result<Vec<_>>>()?;
213812177×
            for (rel, e) in read.iter_mut() {
2139
                // A cached blob the store lost (gc, a partial clone): read the file after all.
214012177×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
21410×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
21420×
                    e.blob = None;
214312177×
                }
2144
            }
2145
            // The listing is in path order, so the map is built without
2146
            // searching.
21471309×
            out = read.into_iter().collect();
21481309×
            for (rel, target) in symlinks {
21492×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
21502×
            }
2151
        }
21521309×
        drop(_read_phase);
21531309×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2154
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2155
        // already tracked as subrepo nodes, they contribute their pin;
2156
        // unregistered ones are left alone.
21571309×
        let modules = self.modules_on_disk();
21581309×
        let removed = self.removed_subrepos();
21591309×
        for rel in &removed {
21603×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
21611×
                self.clear_removed_subrepo(rel);
21622×
            }
2163
        }
21641309×
        let mut untracked_nested = Vec::new();
21651309×
        for dir in nested {
216631×
            let rel = self.rel_path(&dir);
216731×
            if !self.in_scope(&rel) || removed.contains(&rel) {
21683×
                continue;
216928×
            }
217028×
            let registered = modules.entries.get(&rel);
217128×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2172
            {
21731×
                untracked_nested.push(rel);
21741×
                continue;
217527×
            }
217627×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
217727×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2178
        }
21791309×
        untracked_nested.sort();
21801309×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2181
        // Tracked paths the ignore rules hid.
21821309×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
218376×
            if !self.in_scope(rel) {
218410×
                continue;
218566×
            }
218666×
            let path = self.root.join(rel);
218766×
            if *kind == NodeKind::Subrepo {
21884×
                if removed.contains(rel) {
21892×
                    continue;
21902×
                }
21912×
                let present =
21922×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
21932×
                if present {
21940×
                    let pin = subrepos::read_pin(
21950×
                        &path,
21960×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
21970×
                    )?;
21980×
                    out.insert(
21990×
                        rel.clone(),
22000×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2201
                    );
22022×
                } else if let Some(b) = blob {
22032×
                    // Not cloned (or emptied): the pin stays as recorded, as a
22042×
                    // Git gitlink does when its directory is absent.
22052×
                    out.insert(
22062×
                        rel.clone(),
22072×
                        FsEntry {
22082×
                            blob: Some(*b),
22092×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
22102×
                        },
22112×
                    );
22122×
                }
22132×
                continue;
221462×
            }
221562×
            let Ok(meta) = fs::symlink_metadata(&path) else {
221662×
                continue;
2217
            };
22180×
            let ft = meta.file_type();
22190×
            if ft.is_symlink() {
22200×
                let target = fs::read_link(&path)?;
22210×
                out.insert(
22220×
                    rel.clone(),
22230×
                    FsEntry::new(
22240×
                        NodeKind::Symlink,
2225
                        false,
22260×
                        target.to_string_lossy().as_bytes().to_vec(),
2227
                    ),
2228
                );
22290×
            } else if ft.is_file() {
22300×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
22310×
                out.insert(rel.clone(), e);
22320×
            }
2233
        }
22341309×
        Ok(out)
22351310×
    }
2236
2237
    /// The entry for one regular file, read or served from the stat cache.
22380×
    fn file_entry(
22390×
        &self,
22400×
        rel: &str,
22410×
        path: &Path,
22420×
        meta: &walk::Stat,
22430×
        cache: Option<&prompt::Manifest>,
22440×
    ) -> Result<FsEntry> {
22450×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
22460×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
22470×
            e.content = std::sync::Arc::new(fs::read(path)?);
22480×
            e.blob = None;
22490×
        }
22500×
        Ok(e)
22510×
    }
2252
2253
    /// The non-directory paths of a snapshot with their kinds, for the
2254
    /// walker's `tracked` set.
22552×
    pub(crate) fn tracked_kinds(
22562×
        snapshot: &Snapshot,
22572×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
22582×
        snapshot
22592×
            .files
22602×
            .iter()
226112×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
22628×
            .map(|(p, f)| {
22638×
                let blob = match &f.content {
22644×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
22654×
                    _ => None,
2266
                };
22678×
                (p.clone(), (f.kind, blob))
22688×
            })
22692×
            .collect()
22702×
    }
2271
2272
    /// A path under the root as a `/`-separated relative string.
227370×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
227470×
        path.strip_prefix(&self.root)
227570×
            .unwrap_or(path)
227670×
            .components()
2277134×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
227870×
            .collect::<Vec<_>>()
227970×
            .join("/")
228070×
    }
2281
}
2282
2283
impl Repo {
2284
    /// Changes reachable from the bookmark and the working copy, newest first.
228595×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
228695×
        let heads = self.bookmark_heads()?;
228795×
        if self.bare {
22881×
            return self.log_state(&heads);
228994×
        }
229094×
        let (wc_hash, wc) = self.working_copy()?;
229194×
        let mut all = heads.clone();
229294×
        all.push(wc_hash);
229394×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
229494×
        let mut entries: Vec<LogEntry> = Vec::new();
2295
        // A shallow clone knows changes beyond its boundary from a
2296
        // checkpoint's metadata only: its log comes from the state.
229794×
        let metas = if self.is_shallow() {
22981×
            self.load_state_history(&all)?
22991×
                .changes()
23009×
                .map(|(h, m)| (*h, m.clone()))
23011×
                .collect()
2302
        } else {
2303
            // The working copy's change is in hand, and is never in the
2304
            // state index: its metadata is not looked up again.
230593×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
230693×
            below.extend(wc.deps.iter().copied());
230793×
            let _t = crate::timing::phase("log: metadata");
230893×
            let mut metas = self.metas_of(&below)?;
2309325×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
231093×
                // First, where the log puts it, so the order may hold.
231193×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
231293×
            }
231393×
            metas
2314
        };
231594×
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2316427×
            hash: h,
2317427×
            change: meta,
2318427×
            is_working_copy: h == wc_hash,
2319427×
            is_head: head_set.contains(&h),
2320427×
        }));
232194×
        let _sorting = crate::timing::phase("log: sort");
2322
        // The hash makes the order total, so an unstable sort gives the same.
2323
        // From the state index the order already holds (oxygen#94).
2324771×
        let order = |a: &LogEntry, b: &LogEntry| {
2325771×
            b.is_working_copy
2326771×
                .cmp(&a.is_working_copy)
2327771×
                .then(crate::state::log_order(
2328771×
                    (&a.hash, &a.change.hlc),
2329771×
                    (&b.hash, &b.change.hlc),
2330
                ))
2331771×
        };
2332200×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
233344×
            entries.sort_unstable_by(order);
233450×
        }
233594×
        Ok(entries)
233695×
    }
2337
2338
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2339
    /// count, for paginated views.
23400×
    pub fn log_window(
23410×
        &self,
23420×
        heads: &[ChangeHash],
23430×
        offset: usize,
23440×
        limit: usize,
23450×
    ) -> Result<(Vec<LogEntry>, usize)> {
23460×
        let all = self.log_state(heads)?;
23470×
        let total = all.len();
23480×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
23490×
    }
2350
2351
    /// The log of the state with these heads, newest first, with no working
2352
    /// copy involved (for hosted repositories and any explicit state).
235310×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2354
        // The log needs change metadata only: neither graphs nor the tree.
235510×
        if self.is_shallow() {
23560×
            return Ok(self.log_of(&self.load_state_history(heads)?));
235710×
        }
235810×
        let metas = self.metas_of(heads)?;
235910×
        let depended: BTreeSet<ChangeHash> = metas
236010×
            .iter()
236130×
            .flat_map(|(_, m)| m.deps.iter().copied())
236210×
            .collect();
236310×
        let mut entries: Vec<LogEntry> = metas
236410×
            .into_iter()
236510×
            .map(|(h, meta)| LogEntry {
236630×
                hash: h,
236730×
                is_head: !depended.contains(&h),
236830×
                change: meta,
2369
                is_working_copy: false,
237030×
            })
237110×
            .collect();
237237×
        let order = |a: &LogEntry, b: &LogEntry| {
237337×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
237437×
        };
237520×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
23763×
            entries.sort_unstable_by(order);
23777×
        }
237810×
        Ok(entries)
237910×
    }
2380
2381
    /// Every change of the state with these heads and its metadata, read
2382
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2383
    /// a shallow clone's boundary is left out.
2384177×
    pub fn metas_of(
2385177×
        &self,
2386177×
        heads: &[ChangeHash],
2387177×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2388177×
        let boundary = self.boundary();
2389
        // The state index holds the metadata of its heads' closure: a
2390
        // change found there is not read from the store (a change object
2391
        // can be as large as the tree it adds).
2392177×
        let read = self.read_state_index_changes();
2393
        // Every one of `heads` in the index, and every head of the index
2394
        // among them: their closure is the index's changes, all of them
2395
        // (it is closed), and no walk is needed to find it.
2396177×
        if let Some((index_heads, all)) = &read {
2397160×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2398160×
            let in_index = || {
2399160×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2400160×
                    index_heads.iter().collect();
2401
                // Usually the heads asked are the index's: no set of all.
2402160×
                heads.iter().all(|h| index_heads.contains(h)) || {
2403160×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2404160×
                        all.iter().map(|(h, _)| h).collect();
2405160×
                    heads.iter().all(|h| all.contains(h))
2406
                }
2407160×
            };
2408160×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
24090×
                let (_, all) = read.expect("matched above");
2410
                #[cfg(test)]
2411
                {
2412
                    // The walk the shortcut saves finds the same changes.
24130×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
24140×
                    let mut stack = heads.to_vec();
24150×
                    while let Some(h) = stack.pop() {
24160×
                        if seen.insert(h) {
24170×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
24180×
                        }
2419
                    }
24200×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2421
                }
24220×
                return Ok(all);
2423160×
            }
242417×
        }
2425177×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2426177×
            read.map(|(_, all)| all.into_iter().collect());
2427177×
        let _walk = crate::timing::phase("metadata: walk");
2428177×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2429177×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2430177×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2431177×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
24321277×
        while let Some(h) = stack.pop() {
24331100×
            if !seen.insert(h) {
2434461×
                continue;
2435639×
            }
2436
            // Taken out of the index's map, each once: not copied.
2437639×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2438
                #[cfg(test)]
24390×
                assert_eq!(
2440
                    meta,
24410×
                    self.store.get_change_meta(&h)?,
2442
                    "the state index holds a change's metadata"
2443
                );
24440×
                stack.extend(meta.deps.iter().copied());
24450×
                out.push((h, meta));
24460×
                continue;
2447639×
            }
2448639×
            let started = std::time::Instant::now();
2449639×
            let meta = match self.store.get_change_meta(&h) {
2450639×
                Ok(m) => m,
24510×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
24520×
                Err(e) => return Err(e.into()),
2453
            };
2454639×
            stored += 1;
2455639×
            from_store += started.elapsed();
2456639×
            stack.extend(meta.deps.iter().copied());
2457639×
            out.push((h, meta));
2458
        }
2459177×
        if stored > 0 && crate::timing::enabled() {
24600×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2461177×
        }
2462177×
        Ok(out)
2463177×
    }
2464
2465
    /// The log of a state already loaded, newest first.
2466
    /// The history of lines `first..=last` (1-based) of `path` in the
2467
    /// state `heads` make (spec §27): every change that inserted or
2468
    /// deleted one of their atoms, or an atom deleted from between them,
2469
    /// newest first. Exact, as atoms keep their identity across edits.
24706×
    pub fn line_history(
24716×
        &self,
24726×
        heads: &[ChangeHash],
24736×
        path: &str,
24746×
        first: usize,
24756×
        last: usize,
24766×
    ) -> Result<Vec<LogEntry>> {
24776×
        if first == 0 || last < first {
24781×
            return fail(format!(
2479
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2480
            ));
24815×
        }
24825×
        let mut state = self.load_state_history(heads)?;
24835×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
24841×
            return fail(format!("{path} is not in that state"));
2485
        };
24864×
        self.load_graphs_of(&mut state, &[node])?;
24874×
        let live = state.live_lines(&node);
24884×
        if last > live.len() {
24891×
            return fail(format!(
2490
                "{path} has {} lines; asked for {first},{last}",
24911×
                live.len()
2492
            ));
24933×
        }
24943×
        let Some(g) = state.file(&node) else {
24950×
            return fail(format!("{path} is not a text file"));
2496
        };
24973×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
24983×
        let touched = g.touching(&atoms);
24993×
        Ok(self
25003×
            .log_of(&state)
25013×
            .into_iter()
250213×
            .filter(|e| touched.contains(&e.hash))
25033×
            .collect())
25046×
    }
2505
25068×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
25078×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
25088×
        let mut entries: Vec<LogEntry> = state
25098×
            .changes()
25108×
            .map(|(h, meta)| LogEntry {
251131×
                hash: *h,
251231×
                change: meta.clone(),
2513
                is_working_copy: false,
251431×
                is_head: head_set.contains(h),
251531×
            })
25168×
            .collect();
251734×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
25188×
        entries
25198×
    }
2520
2521
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2522
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2523
    /// (`resolve_change`).
252467×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
252567×
        let view = self.view()?;
252667×
        if let Some(st) = view.bookmarks.get(spec) {
252739×
            return Ok(self.store.get_state(st)?.heads);
252828×
        }
252928×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
25302×
            return Ok(self.store.get_state(&st)?.heads);
253126×
        }
253226×
        if let Some(heads) = self.tag_heads(spec)? {
25332×
            return Ok(heads);
253424×
        }
253524×
        Ok(vec![self.resolve_change(spec)?])
253667×
    }
2537
2538
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2539
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
254036×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
254136×
        if spec == "@" {
25420×
            return Ok(self.working_copy()?.0);
254336×
        }
254436×
        let view = self.view()?;
254536×
        let named = match view.bookmarks.get(spec) {
25461×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
254735×
            None => match remote_bookmark(&view, spec) {
25481×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
254934×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2550
            },
2551
        };
255236×
        if let Some((kind, heads)) = named {
25533×
            return match heads.len() {
25543×
                1 => Ok(heads[0]),
25550×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2556
            };
255733×
        }
255833×
        if spec.is_empty() || spec == "#" {
25590×
            return fail("empty change specifier");
256033×
        }
256133×
        let entries = self.log()?;
2562
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2563
        // cannot be a ChangeId, which has 32 (oxygen#103).
256433×
        let full_hash =
2565128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
256633×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
256727×
            entries
256827×
                .iter()
2569109×
                .filter(|e| e.hash.starts_with_hex(hp))
257027×
                .collect()
2571
        } else {
25726×
            entries
25736×
                .iter()
257421×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
25756×
                .collect()
2576
        };
257733×
        match matches.len() {
257828×
            1 => Ok(matches[0].hash),
25795×
            0 => match self.resolve_in_remotes(spec)? {
25801×
                Some(h) => Ok(h),
25814×
                None => fail(format!("no change matches {spec:?}")),
2582
            },
2583
            _ => {
25840×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
25850×
                if ids.len() == 1 {
25860×
                    fail(format!(
2587
                        "change {spec} is divergent: {} variants",
25880×
                        matches.len()
2589
                    ))
2590
                } else {
25910×
                    fail(format!("{spec:?} is ambiguous"))
2592
                }
2593
            }
2594
        }
259536×
    }
2596
2597
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2598
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2599
    /// `None` when none matches, or more than one.
26005×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
26015×
        let view = self.view()?;
26025×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
26035×
        for bookmarks in view.remotes.values() {
26043×
            for st in bookmarks.values() {
26053×
                let heads = self.store.get_state(st)?.heads;
26067×
                for e in self.log_state(&heads)? {
26077×
                    let hit = match spec.strip_prefix('#') {
26082×
                        Some(hp) => e.hash.starts_with_hex(hp),
26095×
                        None => e.change.change_id.starts_with_hex(spec),
2610
                    };
26117×
                    if hit {
26121×
                        found.insert(e.hash);
26136×
                    }
2614
                }
2615
            }
2616
        }
26175×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
26185×
    }
2619
2620
    /// Where a change is when no local bookmark or the working copy holds
2621
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2622
    /// it is held locally, or nowhere.
26233×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
26246×
        if self.log()?.iter().any(|e| e.hash == *hash) {
26252×
            return Ok(None);
26261×
        }
26271×
        let view = self.view()?;
26281×
        for (remote, bookmarks) in &view.remotes {
26291×
            for (name, st) in bookmarks {
26301×
                let heads = self.store.get_state(st)?.heads;
26311×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
26321×
                    return Ok(Some(format!("{remote}/{name}")));
26330×
                }
2634
            }
2635
        }
26360×
        Ok(None)
26373×
    }
2638
2639
    /// Human-readable description of what a change does, with line content.
26403×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
26413×
        let change = self.store.get_change(hash)?;
26423×
        let (base, base_snapshot) = self.change_base(&change)?;
26433×
        Ok(render_change(&change, &base, &base_snapshot))
26443×
    }
2645
2646
    /// The base state of `change` (its dependencies) and its rendering, as
2647
    /// much as showing the change needs: the whole tree, and the graphs and
2648
    /// contents of the files the change edits. Other text files are left
2649
    /// unrendered ([`Snapshot::unrendered`]).
26506×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
26516×
        let base = self.load_state_history(&change.deps)?;
26526×
        self.render_base_for(change, base)
26536×
    }
2654
2655
    /// The base for showing `change` alone: the graphs of the files it
2656
    /// edits built, and the base's tree with no file rendered, which is
2657
    /// all [`render_change`](snapshot::render_change) and
2658
    /// [`diff_files_of`](snapshot::diff_files_of) read.
26593×
    pub(crate) fn tree_base_for(
26603×
        &self,
26613×
        change: &Change,
26623×
        mut base: State,
26633×
    ) -> Result<(State, Snapshot)> {
26643×
        let _t = crate::timing::phase("diff: the base's tree");
26653×
        let edited: std::collections::HashSet<NodeId> =
26668×
            change.edits.iter().map(|e| e.node()).collect();
26673×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
26683×
        self.load_graphs_of(&mut base, &nodes)?;
26693×
        let snapshot = Snapshot {
26703×
            tree: base.tree().view(),
26713×
            files: BTreeMap::new(),
26723×
            unrendered: BTreeSet::new(),
26733×
        };
26743×
        Ok((base, snapshot))
26753×
    }
2676
2677
    /// [`Repo::change_base`] with the base already loaded (the working
2678
    /// copy's comes from the state index).
2679230×
    pub(crate) fn render_base_for(
2680230×
        &self,
2681230×
        change: &Change,
2682230×
        mut base: State,
2683230×
    ) -> Result<(State, Snapshot)> {
2684230×
        let _t = crate::timing::phase("diff: render the base");
2685230×
        let edited: std::collections::HashSet<NodeId> =
2686442×
            change.edits.iter().map(|e| e.node()).collect();
2687230×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2688230×
        self.load_graphs_of(&mut base, &nodes)?;
2689230×
        let snapshot = {
2690230×
            let _t = crate::timing::phase("diff:   of which materialize");
2691230×
            base.materialize_nodes(&edited)
2692
        };
2693230×
        Ok((base, snapshot))
2694230×
    }
2695
}
2696
26970×
fn remove_any(path: &Path) -> std::io::Result<()> {
26980×
    let m = fs::symlink_metadata(path)?;
26990×
    if m.is_dir() {
27000×
        fs::remove_dir_all(path)
2701
    } else {
27020×
        fs::remove_file(path)
2703
    }
27040×
}
2705
27065×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
27075×
    let mut perms = fs::metadata(path)?.permissions();
27085×
    perms.set_readonly(readonly);
27095×
    fs::set_permissions(path, perms)
27105×
}
2711
2712
#[cfg(unix)]
27135904×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2714
    use std::os::unix::fs::PermissionsExt;
27155904×
    let mut perms = fs::metadata(path)?.permissions();
27165904×
    let mode = perms.mode();
27175904×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
27185904×
    if want != mode {
27194×
        perms.set_mode(want);
27204×
        fs::set_permissions(path, perms)?;
27215900×
    }
27225904×
    Ok(())
27235904×
}
2724
#[cfg(not(unix))]
2725
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2726
    Ok(())
2727
}
2728
2729
#[cfg(unix)]
273016506×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2731
    use std::os::unix::fs::PermissionsExt;
273216506×
    m.permissions().mode() & 0o111 != 0
273316506×
}
2734
#[cfg(not(unix))]
2735
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2736
    false
2737
}
2738
273912933×
fn op_ref(k: OpKey) -> OpRef {
274012933×
    OpRef {
274112933×
        change: k.0,
274212933×
        index: k.1,
274312933×
    }
274412933×
}
2745
27466055×
fn split_path(path: &str) -> (&str, &str) {
27476055×
    match path.rfind('/') {
27485060×
        Some(i) => (&path[..i], &path[i + 1..]),
2749995×
        None => ("", path),
2750
    }
27516055×
}
2752
2753
/// Whether `rel` is an attributes file (spec §7.6).
275467900×
fn is_attributes(rel: &str) -> bool {
275567900×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
275667900×
}
2757
2758
/// The manifest entry for `rel` when its size and mtime match it outside
2759
/// the racy window.
276024327×
fn stat_cached<'m>(
276124327×
    rel: &str,
276224327×
    meta: &walk::Stat,
276324327×
    cache: Option<&'m prompt::Manifest>,
276424327×
) -> Option<&'m prompt::ManifestEntry> {
276524327×
    let m = cache?;
276619379×
    let e = m.entries.get(rel)?;
276718012×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
276818012×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
276924327×
}
2770
2771
/// Read one working-copy file, or serve it from the stat cache (spec
2772
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2773
/// an opaque file is not read at all (its stored blob stands in), and a
2774
/// text file the manifest recorded equal to a base graph whose key is
2775
/// `key`, the key the base has now, is not read either: equal keys mean
2776
/// equal renderings, so it still equals the base. Touches no repository
2777
/// state, so the walk runs it in parallel; the caller checks that a cached
2778
/// blob is still in the store.
277912179×
fn read_file_entry(
278012179×
    rel: &str,
278112179×
    path: &Path,
278212179×
    meta: &walk::Stat,
278312179×
    cache: Option<&prompt::Manifest>,
278412179×
    key: Option<[u8; 32]>,
278512179×
) -> Result<FsEntry> {
278612179×
    let exec = meta.exec;
278712179×
    let stat = Some((meta.size, meta.mtime_ns));
278812179×
    let mut e = match stat_cached(rel, meta, cache) {
27894247×
        Some(e) if e.blob.is_some() => FsEntry {
27901×
            blob: e.blob,
27911×
            content_hash: Some(e.hash),
27921×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27931×
        },
27944246×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
27954241×
            content_hash: Some(e.hash),
27964241×
            unchanged: true,
27974241×
            graph_key: e.graph,
27984241×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27994241×
        },
28005×
        Some(e) => FsEntry {
28015×
            content_hash: Some(e.hash),
28025×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2803
        },
28047932×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2805
    };
2806
    // The stat the manifest records: taken before the read, so a file that
2807
    // changes meanwhile is read again next time.
280812178×
    e.stat = stat;
280912178×
    Ok(e)
281012179×
}
2811
2812
/// Two maps side by side in key order: each key of either, with its value
2813
/// in each. Linear, with no lookups, for maps of a whole tree.
28142590×
pub(crate) fn join<'a, A, B>(
28152590×
    a: &'a BTreeMap<String, A>,
28162590×
    b: &'a BTreeMap<String, B>,
28172590×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
28182590×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
281935685×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
28202590×
        (None, None) => None,
28212941×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
28225829×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
282324325×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2824330×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2825302×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2826
            std::cmp::Ordering::Equal => {
282723693×
                let (k, va) = a.next()?;
282823693×
                let (_, vb) = b.next()?;
282923693×
                Some((k, Some(va), Some(vb)))
2830
            }
2831
        },
283235685×
    })
28332590×
}
2834
2835
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2836
/// lookups.
28371310×
pub(crate) fn missing_from<'a, A, B>(
28381310×
    a: &'a BTreeMap<String, A>,
28391310×
    b: &BTreeMap<String, B>,
28401310×
) -> Vec<(&'a String, &'a A)> {
28411310×
    let mut keys = b.keys().peekable();
28421310×
    a.iter()
28439152×
        .filter(|(k, _)| {
284417615×
            while keys.next_if(|kb| *kb < *k).is_some() {}
28459152×
            keys.peek() != Some(k)
28469152×
        })
28471310×
        .collect()
28481310×
}