OXYGENHUB

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

1776 of 2009 lines run, 407 of 668 functions · run #269 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.
752358×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762358×
    let Some(url) = &config.storage_url else {
772353×
        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×
    )?)
1002358×
}
101
102157×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103157×
    Err(RepoError::Msg(s.into()))
104157×
}
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 ops;
120
mod policy;
121
mod prompt;
122
mod receipts;
123
mod revset;
124
mod snapshot;
125
pub mod strata;
126
mod subrepos;
127
mod sync;
128
mod tags;
129
#[cfg(test)]
130
mod tests;
131
mod touched;
132
mod walk;
133
mod workspace;
134
135
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
136
pub use checkout::CheckoutReport;
137
pub use config::{parse_size, read_config_file, Config};
138
pub use doctor::{Check, DoctorReport, Health};
139
pub use fsck::{FsckReport, Problem, Severity};
140
pub use gc::GcReport;
141
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
142
pub use hooks::{json_array, json_str, HookOutcome};
143
pub use hosted::FileEdit;
144
pub use identity::{Rotation, SignatureStatus};
145
pub use inspect::{BisectStep, BlameLine, Description};
146
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
147
pub use policy::PolicyUpdate;
148
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
149
pub use receipts::ReceiptInfo;
150
pub use revset::{Revset, REVSET_BUDGET};
151
pub use snapshot::{
152
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
153
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
154
    Selection, SnapshotResult,
155
};
156
pub use subrepos::{SubrepoInfo, SubrepoSync};
157
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT};
158
pub use tags::TagInfo;
159
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
160
161
/// The file name under which per-bookmark or per-tag data is kept: `/`
162
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
163
/// than a directory that would clash with it.
1643884×
pub(crate) fn name_file(name: &str) -> String {
1653884×
    name.replace('%', "%25").replace('/', "%2F")
1663884×
}
167
168
/// The name a [`name_file`] file name stands for.
16943×
pub(crate) fn file_name_to_name(file: &str) -> String {
17043×
    file.replace("%2F", "/").replace("%25", "%")
17143×
}
172
1736713×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1746713×
    Ok(crate::durable::write_atomic(path, data)?)
1756713×
}
176
177
/// Replace a cache file: whole or not at all, but without waiting for the
178
/// disk. A cache checks its own bytes when read, so one a crash leaves
179
/// short or stale is rebuilt rather than trusted.
180
/// How many changes a state index may fall behind its working copy before
181
/// it is written again; until then each load replays them.
182
const INDEX_REPLAY_LIMIT: usize = 16;
183
/// The changes whose encodings are kept for building graphs: a batch of
184
/// files often takes inline text from a few changes in turn.
185
const CHANGE_CACHE_COUNT: usize = 4;
186
const CHANGE_CACHE_BYTES: usize = 512 << 20;
187
/// How many state indexes a workspace keeps.
188
const STATE_INDEXES_KEPT: usize = 2;
189
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
190
1912725×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1922725×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1932725×
    fs::write(&tmp, data)?;
1942725×
    fs::rename(&tmp, path)?;
1952725×
    Ok(())
1962725×
}
197
198
pub struct LogEntry {
199
    pub hash: ChangeHash,
200
    /// Metadata from the state; the full change may be absent in a shallow repository.
201
    pub change: crate::state::ChangeMeta,
202
    pub is_working_copy: bool,
203
    pub is_head: bool,
204
}
205
206
/// A text file's base graph key, by path, as a walk asks for it.
207
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
208
209
/// A file as found on disk or in an imported tree.
210
#[derive(Clone)]
211
pub(crate) struct FsEntry {
212
    pub kind: NodeKind,
213
    pub exec: bool,
214
    /// File content, or a symlink's target. Empty when `blob` is set.
215
    /// Shared, so a new file's insert holds it without a copy.
216
    pub content: std::sync::Arc<Vec<u8>>,
217
    /// The stored blob of an opaque file whose size and mtime are unchanged
218
    /// since the last manifest (spec §12.3 stat cache); the content was not
219
    /// read.
220
    pub blob: Option<ObjectRef>,
221
    /// BLAKE3 of the content, carried over from the manifest when the stat
222
    /// is unchanged, so the manifest can be rewritten without rehashing.
223
    pub content_hash: Option<[u8; 32]>,
224
    /// A text file known equal to the base's rendering without reading it:
225
    /// its stat matches the manifest and the manifest recorded it equal to
226
    /// a base file graph with the same key (spec §12.3). `content` is empty.
227
    pub unchanged: bool,
228
    /// The base graph key this file equals, for the next manifest.
229
    pub graph_key: Option<[u8; 32]>,
230
    /// Size and mtime already known to be current (a checkout leaving the
231
    /// file as it was), so the manifest need not stat it again.
232
    pub stat: Option<(u64, u128)>,
233
}
234
235
impl FsEntry {
23622543×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
23722543×
        FsEntry {
23822543×
            kind,
23922543×
            exec,
24022543×
            content: std::sync::Arc::new(content),
24122543×
            blob: None,
24222543×
            content_hash: None,
24322543×
            unchanged: false,
24422543×
            graph_key: None,
24522543×
            stat: None,
24622543×
        }
24722543×
    }
248
}
249
250
pub struct Repo {
251
    /// Oxygen-pinned subrepos skipped by the running Git export.
252
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
253
    /// The manifest as last read, with the file identity it was read from,
254
    /// so one command parses it once (see `read_manifest`).
255
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
256
    /// A listing of the working copy left by a failed clean check, for the
257
    /// snapshot that follows it to reuse; taken by the next walk and
258
    /// dropped whenever the manifest is written.
259
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
260
    /// The nested repositories the last walk left out, being neither
261
    /// registered nor tracked subrepos (oxygen#43).
262
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
263
    root: PathBuf,
264
    oxy: PathBuf,
265
    store: Store,
266
    workspace: WorkspaceId,
267
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
268
    bare: bool,
269
    keys_dir: PathBuf,
270
    user_config: PathBuf,
271
    pub config: Config,
272
    /// What the working copy's file system can represent (spec §7.7).
273
    platform: crate::portable::Platform,
274
    /// The encodings of the changes last read for their inline inserts,
275
    /// oldest first.
276
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
277
    /// `--at-op`: read the repository as it was after this operation;
278
    /// recording an operation is refused.
279
    at_op: Option<ObjectRef>,
280
    /// The directories (with their times) and nested repositories of the
281
    /// last walk, for the manifest written from it.
282
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
283
    /// The directories a manifest check listed, for its restamp only.
284
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
285
}
286
287
/// A walk's directories with their times, and its nested repositories.
288
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
289
290
/// Marker file of a bare repository, inside `.oxy/`.
291
const BARE_MARKER: &str = "bare";
292
/// Marker of a hosted repository that has no id yet: the first push binds
293
/// it to the pusher's id (spec §16.1).
294
const UNBOUND_MARKER: &str = "unbound";
295
296
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
297
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
2987304×
pub fn default_home() -> PathBuf {
2997304×
    if let Ok(h) = std::env::var("OXY_HOME") {
3007301×
        return PathBuf::from(h);
3013×
    }
3023×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3030×
        return PathBuf::from(x).join("oxy");
3043×
    }
305
    // Windows has no HOME as a rule: the roaming profile's application
306
    // data, as Windows programs keep theirs.
307
    #[cfg(windows)]
308
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
309
        return PathBuf::from(d).join("oxy");
310
    }
3113×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3123×
    PathBuf::from(home).join(".config").join("oxy")
3137304×
}
314
3152358×
pub fn default_keys_dir() -> PathBuf {
3162358×
    default_home().join("keys")
3172358×
}
318
3194716×
pub fn default_user_config() -> PathBuf {
3204716×
    default_home().join("config.toml")
3214716×
}
322
323
/// Where `create_identity` records the author.
324
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
325
pub enum IdentityScope {
326
    /// The user file: every repository of this user signs with it.
327
    User,
328
    /// This repository only.
329
    Repo,
330
}
331
332
impl Repo {
333
    // ------------------------------------------------------------ lifecycle
334
335213×
    pub fn init(root: &Path) -> Result<Repo> {
336213×
        let mut id = [0u8; 16];
337213×
        rand::rngs::OsRng.fill_bytes(&mut id);
338213×
        Self::init_with_id(root, id)
339213×
    }
340
341
    /// Initialize a repository with a given repository ID (clones share the
342
    /// ID of their origin, spec §14.4).
343449×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
344449×
        Self::init_on(root, id, None)
345449×
    }
346
347
    /// A new repository with a fresh id, bare or not, on `storage` or in
348
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
34912×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
35012×
        let mut id = [0u8; 16];
35112×
        rand::rngs::OsRng.fill_bytes(&mut id);
35212×
        if bare {
3530×
            Self::init_bare_on(root, id, storage)
354
        } else {
35512×
            Self::init_on(root, id, storage)
356
        }
35712×
    }
358
359
    /// Initialize a repository whose objects and operation head are kept
360
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
361464×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
362464×
        fs::create_dir_all(root)?;
363464×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
364464×
        let oxy = root.join(OXY_DIR);
365464×
        if oxy.exists() {
3661×
            return fail(format!("{} is already an oxy repository", root.display()));
367463×
        }
368463×
        fs::create_dir_all(oxy.join("ops"))?;
369463×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
370463×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
371463×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
372463×
        if let Some(url) = storage {
3733×
            config.set("storage.url", url)?;
374460×
        }
375463×
        config.save(&oxy.join("config"))?;
376463×
        let workspace = WorkspaceId::random();
377463×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
378463×
        let store = open_objects(&oxy, &config)?;
379462×
        let repo = Repo {
380462×
            last_change: Default::default(),
381462×
            at_op: None,
382462×
            walked_dirs: Default::default(),
383462×
            listed_dirs: Default::default(),
384462×
            git_export_skipped: Default::default(),
385462×
            manifest_cache: Default::default(),
386462×
            listing_cache: Default::default(),
387462×
            untracked_nested: Default::default(),
388462×
            root,
389462×
            oxy,
390462×
            store,
391462×
            workspace,
392462×
            bare: false,
393462×
            keys_dir: default_keys_dir(),
394462×
            platform: crate::portable::Platform::current(),
395462×
            user_config: default_user_config(),
396462×
            config,
397462×
        };
398462×
        repo.register_workspace(&workspace, &repo.root)?;
399
400462×
        let wc = repo.new_working_copy(vec![], "");
401462×
        let wc_hash = repo.store.put_change(&wc)?;
402462×
        let mut view = View::default();
403462×
        view.bookmarks.insert(
404462×
            repo.config.bookmark.clone(),
405462×
            repo.store.put_state(&StateObject::new(vec![]))?,
406
        );
407462×
        view.workspaces.insert(workspace, wc_hash);
408462×
        repo.record_op(&[], "oxy init", view)?;
409460×
        Ok(repo)
410464×
    }
411
412
    /// Create a bare repository: an object store, operation log and
413
    /// references with no workspace and no working copy, for hosting
414
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4155×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4165×
        let mut id = [0u8; 16];
4175×
        rand::rngs::OsRng.fill_bytes(&mut id);
4185×
        Self::init_bare_with_id(root, id)
4195×
    }
420
42139×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
42239×
        Self::init_bare_on(root, id, None)
42339×
    }
424
425
    /// [`Repo::init_on`] for a bare repository.
42639×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
42739×
        fs::create_dir_all(root)?;
42839×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
42939×
        let oxy = root.join(OXY_DIR);
43039×
        if oxy.exists() {
4310×
            return fail(format!("{} is already an oxy repository", root.display()));
43239×
        }
43339×
        fs::create_dir_all(oxy.join("ops"))?;
43439×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
43539×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
43639×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
43739×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
43839×
        if let Some(url) = storage {
4390×
            config.set("storage.url", url)?;
44039×
        }
44139×
        config.save(&oxy.join("config"))?;
44239×
        let store = open_objects(&oxy, &config)?;
44339×
        let repo = Repo {
44439×
            last_change: Default::default(),
44539×
            at_op: None,
44639×
            walked_dirs: Default::default(),
44739×
            listed_dirs: Default::default(),
44839×
            git_export_skipped: Default::default(),
44939×
            manifest_cache: Default::default(),
45039×
            listing_cache: Default::default(),
45139×
            untracked_nested: Default::default(),
45239×
            root,
45339×
            oxy,
45439×
            store,
45539×
            workspace: WorkspaceId::ZERO,
45639×
            bare: true,
45739×
            keys_dir: default_keys_dir(),
45839×
            platform: crate::portable::Platform::current(),
45939×
            user_config: default_user_config(),
46039×
            config,
46139×
        };
46239×
        let mut view = View::default();
46339×
        view.bookmarks.insert(
46439×
            repo.config.bookmark.clone(),
46539×
            repo.store.put_state(&StateObject::new(vec![]))?,
466
        );
46739×
        repo.record_op(&[], "oxy init --bare", view)?;
46839×
        Ok(repo)
46939×
    }
470
471
    /// A bare repository with no id yet. Its `id()` is all zero until the
472
    /// first push binds it (`bind_id`), so an existing repository can be
473
    /// pushed to a freshly created hosted one and keep its identity.
47413×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
47513×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
47613×
        fs::remove_file(repo.oxy.join("id"))?;
47713×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
47813×
        Ok(repo)
47913×
    }
480
4813352×
    pub fn is_unbound(&self) -> bool {
4823352×
        self.oxy.join(UNBOUND_MARKER).is_file()
4833352×
    }
484
485
    /// Give an unbound repository its id.
48612×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
48712×
        if !self.is_unbound() {
4880×
            return fail("this repository already has an id");
48912×
        }
49012×
        if id == [0; 16] {
4910×
            return fail("a repository id cannot be all zero");
49212×
        }
49312×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
49412×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
49512×
        Ok(())
49612×
    }
497
498
    /// Whether this repository has no working copy (`init_bare`).
49975×
    pub fn is_bare(&self) -> bool {
50075×
        self.bare
50175×
    }
502
503
    /// Open the repository containing `start` (searching upwards).
5041856×
    pub fn open(start: &Path) -> Result<Repo> {
5051856×
        let start = start.canonicalize()?;
5061856×
        let mut dir: Option<&Path> = Some(&start);
5071856×
        while let Some(d) = dir {
5081856×
            let oxy = d.join(OXY_DIR);
5091856×
            if oxy.is_file() {
510
                // A secondary workspace (spec §12.2): the file points at the repository.
5119×
                let text = fs::read_to_string(&oxy)?;
5129×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5130×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
514
                };
5159×
                let format = fs::read_to_string(shared.join("format"))?;
5169×
                if format != FORMAT_LINE {
5170×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5189×
                }
5199×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5209×
                let store = open_objects(&shared, &config)?;
5219×
                let mut repo = Repo {
5229×
                    last_change: Default::default(),
5239×
                    at_op: None,
5249×
                    walked_dirs: Default::default(),
5259×
                    listed_dirs: Default::default(),
5269×
                    git_export_skipped: Default::default(),
5279×
                    manifest_cache: Default::default(),
5289×
                    listing_cache: Default::default(),
5299×
                    untracked_nested: Default::default(),
5309×
                    root: d.to_path_buf(),
5319×
                    oxy: shared,
5329×
                    store,
5339×
                    workspace,
5349×
                    bare: false,
5359×
                    keys_dir: default_keys_dir(),
5369×
                    platform: crate::portable::Platform::current(),
5379×
                    user_config: default_user_config(),
5389×
                    config,
5399×
                };
5409×
                repo.apply_workspace_bookmark();
5419×
                return Ok(repo);
5421847×
            }
5431847×
            if oxy.is_dir() {
5441847×
                let format = fs::read_to_string(oxy.join("format"))?;
5451847×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5461847×
                let bare = oxy.join(BARE_MARKER).is_file();
5471847×
                let workspace = if bare {
548144×
                    WorkspaceId::ZERO
549
                } else {
5501703×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5511703×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
552
                };
5531847×
                let store = open_objects(&oxy, &config)?;
5541847×
                let mut repo = Repo {
5551847×
                    last_change: Default::default(),
5561847×
                    at_op: None,
5571847×
                    walked_dirs: Default::default(),
5581847×
                    listed_dirs: Default::default(),
5591847×
                    git_export_skipped: Default::default(),
5601847×
                    manifest_cache: Default::default(),
5611847×
                    listing_cache: Default::default(),
5621847×
                    untracked_nested: Default::default(),
5631847×
                    root: d.to_path_buf(),
5641847×
                    oxy,
5651847×
                    store,
5661847×
                    workspace,
5671847×
                    bare,
5681847×
                    keys_dir: default_keys_dir(),
5691847×
                    platform: crate::portable::Platform::current(),
5701847×
                    user_config: default_user_config(),
5711847×
                    config,
5721847×
                };
5731847×
                if !bare {
5741703×
                    repo.apply_workspace_bookmark();
5751703×
                }
5761847×
                if format == FORMAT1_LINE {
5771×
                    repo.migrate_format1()?;
5781846×
                } else if format != FORMAT_LINE {
5790×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5801846×
                }
5811847×
                return Ok(repo);
5820×
            }
5830×
            dir = d.parent();
584
        }
5850×
        fail(format!(
586
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
5870×
            start.display()
588
        ))
5891856×
    }
590
591
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
592
    /// into format 2, where each bookmark names a `state` object.
5931×
    fn migrate_format1(&self) -> Result<()> {
5941×
        let (head, version) = self.read_head()?;
595
        // Collect the chain root-first.
5961×
        let mut chain: Vec<Format1Op> = Vec::new();
5971×
        let mut cur = Some(head);
5983×
        while let Some(r) = cur {
5992×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
6002×
            cur = op.parents.first().copied();
6012×
            chain.push(op);
602
        }
6031×
        chain.reverse();
6041×
        let mut new_parent: Option<ObjectRef> = None;
6052×
        for old in chain {
6062×
            let mut view = View::default();
6072×
            for (name, heads) in &old.view.bookmarks {
6082×
                view.bookmarks.insert(
6092×
                    name.clone(),
6102×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
611
                );
612
            }
6132×
            view.workspaces = old.view.workspaces.clone();
6142×
            let op = Op {
6152×
                parents: new_parent.into_iter().collect(),
6162×
                hlc: old.hlc,
6172×
                command: old.command,
6182×
                view,
6192×
                workspace: None,
6202×
                undoes: None,
6212×
            };
6222×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
623
        }
6241×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6250×
            return fail("the operation log changed while it was rewritten; run the command again");
6261×
        }
6271×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6281×
        Ok(())
6291×
    }
630
631
    /// Pack automatically once many loose objects have accumulated.
632627×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
633627×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6340×
            self.store.pack_loose()?;
6350×
            self.store.merge_packs()?;
636627×
        }
637627×
        Ok(())
638627×
    }
639
640
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6413076×
    pub fn id(&self) -> Result<[u8; 16]> {
6423076×
        if self.is_unbound() {
64318×
            return Ok([0; 16]);
6443058×
        }
6453058×
        let path = self.oxy.join("id");
6463058×
        match fs::read_to_string(&path) {
6473058×
            Ok(h) => hex::decode(h.trim())
6483058×
                .ok()
6493058×
                .and_then(|v| v.try_into().ok())
6503058×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6510×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6520×
                let mut id = [0u8; 16];
6530×
                rand::rngs::OsRng.fill_bytes(&mut id);
6540×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6550×
                Ok(id)
656
            }
6570×
            Err(e) => Err(e.into()),
658
        }
6593076×
    }
660
66162×
    pub fn root(&self) -> &Path {
66262×
        &self.root
66362×
    }
664481×
    pub fn store(&self) -> &Store {
665481×
        &self.store
666481×
    }
66710×
    pub fn workspace(&self) -> WorkspaceId {
66810×
        self.workspace
66910×
    }
670
671
    /// Use a different user directory for keys and the user config file
672
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
673
    /// Act as if the working copy were on another platform's file system
674
    /// (tests of Windows and macOS behaviour on any host).
6752×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
6762×
        self.platform = platform;
6772×
        self
6782×
    }
679
6800×
    pub fn platform(&self) -> crate::portable::Platform {
6810×
        self.platform
6820×
    }
683
684159×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
685159×
        let dir = dir.into();
686159×
        self.keys_dir = dir.join("keys");
687159×
        self.user_config = dir.join("config.toml");
688159×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
689159×
            self.config = c;
690159×
        }
691159×
        self.apply_workspace_bookmark();
692159×
        self
693159×
    }
694
695
    /// The workspace's current bookmark (spec §10.1) overrides the
696
    /// configured default when `oxy bookmark switch` has recorded one.
6971871×
    fn apply_workspace_bookmark(&mut self) {
6981871×
        if let Ok(b) = fs::read_to_string(
6991871×
            self.oxy
7001871×
                .join("workspaces")
7011871×
                .join(self.workspace.to_hex())
7021871×
                .join("bookmark"),
7031871×
        ) {
70435×
            let b = b.trim();
70535×
            if !b.is_empty() {
70635×
                self.config.bookmark = b.to_string();
70735×
            }
7081836×
        }
7091871×
    }
710
7111×
    pub fn user_config_path(&self) -> &Path {
7121×
        &self.user_config
7131×
    }
714
715
    /// Set a key in the user file and refresh the effective configuration.
71612×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
71712×
        Config::set_user(&self.user_config, key, value)?;
71811×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
71911×
        Ok(())
72012×
    }
721
722352×
    pub fn save_config(&self) -> Result<()> {
723352×
        self.config.save(&self.oxy.join("config"))
724352×
    }
725
7264114×
    fn author(&self) -> KeyId {
7274114×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7284114×
    }
729
}
730
731
impl Repo {
7321573×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7331573×
        let mut c = Change {
7341573×
            version: crate::objects::CHANGE_VERSION,
7351573×
            change_id: ChangeId::random(),
7361573×
            deps,
7371573×
            author: self.author(),
7381573×
            hlc: Hlc::now(),
7391573×
            message: message.into(),
7401573×
            tree_ops: vec![],
7411573×
            edits: vec![],
7421573×
            kind: ChangeKind::WorkingCopy,
7431573×
        };
7441573×
        c.normalize();
7451573×
        c
7461573×
    }
747
748
    // ------------------------------------------------------------ operation log
749
75013300×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
75113300×
        if let Some(r) = self.at_op {
7525×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
75313295×
        }
75413295×
        let r = self.head_ref()?;
75513293×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
75613293×
        Ok((r, op))
75713300×
    }
758
7599225×
    pub fn view(&self) -> Result<View> {
7609225×
        Ok(self.head_op()?.1.view)
7619225×
    }
762
7633233×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
7643233×
        self.record_op_undoing(parents, command, view, None)
7653233×
    }
766
767
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
7683236×
    fn record_op_undoing(
7693236×
        &self,
7703236×
        parents: &[ObjectRef],
7713236×
        command: &str,
7723236×
        view: View,
7733236×
        undoes: Option<ObjectRef>,
7743236×
    ) -> Result<ObjectRef> {
7753236×
        if self.at_op.is_some() {
7761×
            return fail(
777
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
778
            );
7793235×
        }
7803235×
        let op = Op {
7813235×
            parents: parents.to_vec(),
7823235×
            hlc: Hlc::now(),
7833235×
            command: command.into(),
7843235×
            view,
7853235×
            workspace: Some(self.workspace),
7863235×
            undoes,
7873235×
        };
7883235×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
789
        // The head is the commit point: everything it names must be on disk first.
7903233×
        let flushing = crate::timing::phase("op: flush the store");
7913233×
        self.store.flush()?;
7923231×
        drop(flushing);
793
        // Compare and swap (spec §12.1): when another process recorded an
794
        // operation since this one read the head, the two are merged
795
        // instead of one overwriting the other. On this disk the head moves
796
        // under a short lock; on any other store by its record's version,
797
        // and a record that moved meanwhile is read again and merged again.
7983231×
        let _lock = if self.store.is_local() {
7993223×
            Some(self.lock_ops()?)
800
        } else {
8018×
            None
802
        };
8033231×
        let Some(parent) = parents.first() else {
804
            // The first operation (init): there is no head yet.
805501×
            if !self.swap_head(&r, None)? {
8062×
                return fail(format!(
807
                    "{} already holds a repository's operation log",
8082×
                    self.store.backend().describe()
809
                ));
810499×
            }
811499×
            return Ok(r);
812
        };
8132730×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8142730×
        for _ in 0..HEAD_TRIES {
8152730×
            let (current, version) = self.read_head()?;
8162730×
            let to = if current == *parent {
8172720×
                r
818
            } else {
81910×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
8209×
                let merged = Op {
82110×
                    parents: vec![current, r],
82210×
                    hlc: Hlc::now(),
82310×
                    command: format!("{command} (merged with a concurrent operation)"),
82410×
                    view: self.merge_views(&base, &op.view, &theirs)?,
8259×
                    workspace: Some(self.workspace),
8269×
                    undoes: None,
827
                };
8289×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
8299×
                self.store.flush()?;
8309×
                m
831
            };
8322729×
            if self.swap_head(&to, version.as_ref())? {
8332723×
                return Ok(to);
8340×
            }
835
        }
8360×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8373236×
    }
838
839
    /// The operation head's lock, held only while the head pointer moves.
8403233×
    fn lock_ops(&self) -> Result<FileLock> {
8413233×
        fs::create_dir_all(self.oxy.join("ops"))?;
8423233×
        FileLock::acquire(
8433233×
            self.oxy.join("ops").join("lock"),
8443233×
            "another oxy process holds the operation log",
845
        )
8463233×
    }
847
84813297×
    fn head_ref(&self) -> Result<ObjectRef> {
84913297×
        Ok(self.read_head()?.0)
85013297×
    }
851
852
    /// The operation head, and on a store its record's version for
853
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
854
    /// any other store (a bucket, or memory in tests) it is the store's
855
    /// [`HEAD_RECORD`] reference record (oxygen#68).
85616115×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
85716115×
        if self.store.is_local() {
85816096×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
85916096×
            let r = ObjectRef::from_hex(hex.trim())
86016096×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
86116093×
            return Ok((r, None));
86219×
        }
86319×
        let backend = self.store.backend();
86419×
        match backend.read_ref(HEAD_RECORD) {
86519×
            Ok(Some((bytes, version))) => {
86619×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
8670×
                    || {
8680×
                        RepoError::Msg(format!(
8690×
                            "the operation head in {} is corrupt",
8700×
                            backend.describe()
8710×
                        ))
8720×
                    },
8730×
                )?;
87419×
                Ok((r, Some(version)))
875
            }
8760×
            Ok(None) => fail(format!(
877
                "{} holds no operation log (no {HEAD_RECORD} record)",
8780×
                backend.describe()
879
            )),
8800×
            Err(e) => fail(format!("read the operation head: {e}")),
881
        }
88216115×
    }
883
884
    /// Move the operation head to `to` from the `expected` version
885
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
886
    /// disk the caller holds the operations lock and the head always
887
    /// moves; on a store it moves only if the record is unchanged, and
888
    /// `false` says another process moved it first.
8893243×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
8903243×
        if self.store.is_local() {
8913233×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
8923227×
            return Ok(true);
89310×
        }
89410×
        match self
89510×
            .store
89610×
            .backend()
89710×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
898
        {
8997×
            Ok(_) => Ok(true),
9003×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
9010×
            Err(e) => fail(format!("move the operation head: {e}")),
902
        }
9033243×
    }
904
905
    /// Three-way merge of two views that both started from `base` (spec
906
    /// §12.1). A reference only one side changed takes that side's value.
907
    /// When both changed it differently: a bookmark keeps both sides'
908
    /// heads (it may then have several), a change beats a deletion, a
909
    /// workspace changed by both is an error (only one of them matches the
910
    /// files on disk), and otherwise this process's value wins for remote
911
    /// references and the policy, the first value for a tag (tags never
912
    /// move).
91310×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
91434×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
91534×
            b: &BTreeMap<K, V>,
91634×
            o: &BTreeMap<K, V>,
91734×
            t: &BTreeMap<K, V>,
91834×
            mut both: impl FnMut(&V, &V) -> Result<V>,
91934×
        ) -> Result<BTreeMap<K, V>> {
92034×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
92134×
            let mut out = BTreeMap::new();
92235×
            for k in keys {
92335×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
92435×
                let v = if ov == tv || tv == bv {
92517×
                    ov.cloned()
92618×
                } else if ov == bv {
92710×
                    tv.cloned()
928
                } else {
9298×
                    match (ov, tv) {
9308×
                        (Some(x), Some(y)) => Some(both(x, y)?),
9310×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
9320×
                        (None, None) => None,
933
                    }
934
                };
93534×
                if let Some(v) = v {
93634×
                    out.insert(k.clone(), v);
93734×
                }
938
            }
93933×
            Ok(out)
94034×
        }
94110×
        let bookmarks = pick(
94210×
            &base.bookmarks,
94310×
            &ours.bookmarks,
94410×
            &theirs.bookmarks,
9457×
            |x, y| {
9467×
                let mut heads = self.store.get_state(x)?.heads;
9477×
                heads.extend(self.store.get_state(y)?.heads);
9487×
                let heads = self.load_state(&heads)?.maximal(&heads);
9497×
                Ok(self.store.put_state(&StateObject::new(heads))?)
9507×
            },
9510×
        )?;
952
        // Two operations that both replaced one workspace's working copy
953
        // cannot both be right: the files on disk match only one of them.
954
        // The working-copy lock keeps this from happening; should it happen
955
        // anyway, this operation is not recorded.
95610×
        let workspaces = pick(
95710×
            &base.workspaces,
95810×
            &ours.workspaces,
95910×
            &theirs.workspaces,
9601×
            |_, _| {
9611×
                fail(
962
                    "another oxy process changed this working copy at the same time; \
963
                     this command was not recorded: check `oxy status` and run it again",
964
                )
9651×
            },
9661×
        )?;
9679×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
9689×
        let empty = BTreeMap::new();
9699×
        let names: BTreeSet<&String> = base
9709×
            .remotes
9719×
            .keys()
9729×
            .chain(ours.remotes.keys())
9739×
            .chain(theirs.remotes.keys())
9749×
            .collect();
9759×
        let mut remotes = BTreeMap::new();
9769×
        for n in names {
9775×
            let m = pick(
9785×
                base.remotes.get(n).unwrap_or(&empty),
9795×
                ours.remotes.get(n).unwrap_or(&empty),
9805×
                theirs.remotes.get(n).unwrap_or(&empty),
9810×
                |x, _| Ok(*x),
9820×
            )?;
9835×
            if !m.is_empty() {
9845×
                remotes.insert(n.clone(), m);
9855×
            }
986
        }
9879×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
9889×
            ours.policy
9890×
        } else if ours.policy == base.policy {
9900×
            theirs.policy
991
        } else {
9920×
            ours.policy.or(theirs.policy)
993
        };
9949×
        self.store.flush()?;
9959×
        Ok(View {
9969×
            bookmarks,
9979×
            workspaces,
9989×
            remotes,
9999×
            policy,
10009×
            tags,
10019×
        })
100210×
    }
1003
100444×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
100544×
        let mut out = Vec::new();
100644×
        let (mut r, mut op) = self.head_op()?;
1007
        loop {
1008245×
            let next = op.parents.first().copied();
1009245×
            out.push((r, op));
1010245×
            match next {
1011201×
                Some(p) => {
1012201×
                    r = p;
1013201×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1014
                }
101544×
                None => break,
1016
            }
1017
        }
101844×
        Ok(out)
101944×
    }
1020
1021
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1022
    ///
1023
    /// The command undone is the newest one this workspace ran: operations
1024
    /// that only recorded a working-copy snapshot are skipped (the files are
1025
    /// still on disk and the next snapshot recreates them), as are pushes
1026
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1027
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1028
    /// operations are never undone, and a command an earlier undo already
1029
    /// reverted is passed over, so undoing again goes further back.
1030
    ///
1031
    /// When nothing newer came from another workspace, the operation head
1032
    /// moves back to before the command. Otherwise the command is reverted
1033
    /// in place: every reference it changed goes back to its value before
1034
    /// it, recorded as a new operation that names it, and anything another
1035
    /// workspace changed since is kept. A reference both the command and a
1036
    /// later operation of another workspace changed is not guessed at: the
1037
    /// undo is refused, naming it.
1038
    ///
1039
    /// When the working copy is clean and was clean after the command's
1040
    /// predecessor, its files follow too, since nothing on disk can be
1041
    /// lost; otherwise they stay as they are (an undone commit's edits come
1042
    /// back as uncommitted work).
104316×
    pub fn undo(&self) -> Result<Undone> {
104416×
        let _wc = self.lock_working_copy()?;
104516×
        let clean_now =
104616×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
104716×
        let (head_ref, head) = self.head_op()?;
104816×
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
104940×
        let load = |r: &ObjectRef| -> Result<Op> {
105040×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
105140×
        };
105216×
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
105316×
        let mut pending_checkout: Option<Op> = None;
105416×
        let mut others = 0usize;
105516×
        let (mut r, mut op) = (head_ref, head.clone());
105615×
        let (target_ref, target, parent) = loop {
105741×
            let parent = match op.parents.first() {
105840×
                Some(p) => Some((*p, load(p)?)),
10591×
                None => None,
1060
            };
106141×
            if skip.contains(&r) {
10621×
                pending_checkout = None;
106340×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
106410×
                // A push cannot be taken back: undoing it would only make
106510×
                // this repository forget what the remote holds.
106630×
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
106710×
                others += 1;
106820×
            } else if let Some(u) = op.undoes {
10691×
                skip.insert(u);
10701×
                pending_checkout = None;
107119×
            } else if op.command.ends_with(" (checkout)") {
10723×
                pending_checkout = Some(op.clone());
10733×
            } else {
107416×
                match parent {
107515×
                    Some((_, p)) => break (r, op, p),
10761×
                    None => return fail("nothing to undo in this workspace"),
1077
                }
1078
            }
107925×
            match parent {
108025×
                Some((pr, p)) => (r, op) = (pr, p),
10810×
                None => return fail("nothing to undo in this workspace"),
1082
            }
1083
        };
108415×
        let before = parent.view;
108515×
        let after = pending_checkout
108615×
            .map(|o| o.view)
108715×
            .unwrap_or_else(|| target.view.clone());
108815×
        let changes = self.view_changes(&before, &after)?;
108915×
        let pushed = self.pushed_by(&before, &after, &head.view)?;
109015×
        let restored_wc = before.workspaces.get(&self.workspace).copied();
109115×
        if others == 0 {
1092
            // Only this workspace's operations since: move the head back.
109310×
            let _lock = if self.store.is_local() {
109410×
                Some(self.lock_ops()?)
1095
            } else {
10960×
                None
1097
            };
109810×
            let parent_ref = *target.parents.first().expect("the target has a parent");
109910×
            let (now, version) = self.read_head()?;
110010×
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
11010×
                return fail("another oxy command ran while undoing; run undo again");
110210×
            }
1103
        } else {
11045×
            let view = self.revert_view(&head.view, &before, &after)?;
11053×
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1106
        }
110713×
        self.drop_manifest();
110813×
        if let Some(then) = restored_wc {
110913×
            if clean_now && Some(then) != wc_now {
111010×
                let wc = self.store.get_change(&then)?;
111110×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
11128×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1113
                    // The files differ from the restored working copy by
1114
                    // exactly what the undone command did: nothing else is
1115
                    // on disk, as the working copy was clean.
11168×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
11172×
                }
11183×
            }
11190×
        }
112013×
        Ok(Undone {
112113×
            command: target.command,
112213×
            changes,
112313×
            others_kept: others,
112413×
            pushed,
112513×
        })
112616×
    }
1127
1128
    /// Whether operation `op` was a push: it changed only what this
1129
    /// repository knows of remotes.
113031×
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
113131×
        let Some(p) = parent else {
11321×
            return false;
1133
        };
113430×
        op.command.starts_with("oxy push")
11351×
            && op.view.bookmarks == p.view.bookmarks
11361×
            && op.view.tags == p.view.tags
11371×
            && op.view.workspaces == p.view.workspaces
11381×
            && op.view.policy == p.view.policy
113931×
    }
1140
1141
    /// Whether operation `op` (whose predecessor is `parent`) was this
1142
    /// workspace's. Operations record their workspace (oxygen#99); for older
1143
    /// ones it is read from the view: one that changed only other
1144
    /// workspaces' working copies was theirs, anything else counts as ours.
114530×
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
114630×
        if let Some(w) = op.workspace {
114730×
            return w == self.workspace;
11480×
        }
11490×
        let Some(p) = parent else {
11500×
            return true;
1151
        };
11520×
        let ids: BTreeSet<&WorkspaceId> = op
11530×
            .view
11540×
            .workspaces
11550×
            .keys()
11560×
            .chain(p.view.workspaces.keys())
11570×
            .collect();
11580×
        let moved: Vec<&WorkspaceId> = ids
11590×
            .into_iter()
11600×
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
11610×
            .collect();
11620×
        moved.is_empty() || moved.contains(&&self.workspace)
116330×
    }
1164
1165
    /// `current` with what changed from `before` to `after` put back, this
1166
    /// workspace's working copy included; refused when a later operation
1167
    /// changed one of the same references again.
11685×
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
116910×
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
117010×
            cur: &mut BTreeMap<K, V>,
117110×
            before: &BTreeMap<K, V>,
117210×
            after: &BTreeMap<K, V>,
117310×
            name: impl Fn(&K) -> String,
117410×
            clashes: &mut Vec<String>,
117510×
        ) {
117610×
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
117710×
            for k in keys {
11785×
                let (b, a) = (before.get(k), after.get(k));
11795×
                if a == b {
11804×
                    continue;
11811×
                }
11821×
                if cur.get(k) != a {
11831×
                    clashes.push(name(k));
11841×
                    continue;
11850×
                }
11860×
                match b {
11870×
                    Some(v) => cur.insert(k.clone(), v.clone()),
11880×
                    None => cur.remove(k),
1189
                };
1190
            }
119110×
        }
11925×
        let mut out = current.clone();
11935×
        let mut clashes = Vec::new();
1194
        // A bookmark another workspace moved since is put back head by
1195
        // head: the heads the command added go, the heads it replaced
1196
        // return, and the other workspace's heads stay. Only when a later
1197
        // change was built on one the command added is that not possible.
11985×
        let names: BTreeSet<&String> = before
11995×
            .bookmarks
12005×
            .keys()
12015×
            .chain(after.bookmarks.keys())
12025×
            .collect();
12038×
        for name in names {
12048×
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
12058×
            let cur = current.bookmarks.get(name);
12068×
            if a == b {
12074×
                continue;
12084×
            }
12094×
            if cur == a {
12102×
                match b {
12112×
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
12120×
                    None => out.bookmarks.remove(name),
1213
                };
12142×
                continue;
12152×
            }
12162×
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
12170×
                clashes.push(format!("bookmark {name}"));
12180×
                continue;
1219
            };
12202×
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
12212×
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
12222×
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
12232×
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
12242×
            if !added.iter().all(|h| now.contains(h)) {
12251×
                clashes.push(format!(
1226
                    "bookmark {name} (a later change builds on this one)"
1227
                ));
12281×
                continue;
12291×
            }
12301×
            let mut heads: Vec<ChangeHash> = now
12311×
                .iter()
12323×
                .filter(|h| !added.contains(h))
12331×
                .chain(was.difference(&became))
12341×
                .copied()
12351×
                .collect();
12361×
            heads.sort();
12371×
            heads.dedup();
12381×
            let heads = self.load_state(&heads)?.maximal(&heads);
12391×
            out.bookmarks.insert(
12401×
                name.clone(),
12411×
                self.store.put_state(&StateObject::new(heads))?,
1242
            );
1243
        }
1244
12455×
        back(
12465×
            &mut out.tags,
12475×
            &before.tags,
12485×
            &after.tags,
12490×
            |k| format!("tag {k}"),
12505×
            &mut clashes,
1251
        );
12525×
        let mine = self.workspace;
125315×
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
125415×
            v.workspaces
125515×
                .iter()
125629×
                .filter(|(k, _)| **k != mine)
125715×
                .map(|(k, v)| (*k, *v))
125815×
                .collect()
125915×
        };
12605×
        let mut theirs = others(&out);
12615×
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
12621×
            Some(p) => format!("the workspace at {}", p.display()),
12630×
            None => format!("workspace {}", id.to_hex()),
12641×
        };
12655×
        back(
12665×
            &mut theirs,
12675×
            &others(before),
12685×
            &others(after),
12695×
            workspace_name,
12705×
            &mut clashes,
1271
        );
12725×
        let empty = BTreeMap::new();
12735×
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
12745×
        for n in names {
12750×
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
12760×
            back(
12770×
                &mut cur,
12780×
                before.remotes.get(n).unwrap_or(&empty),
12790×
                after.remotes.get(n).unwrap_or(&empty),
12800×
                |k| format!("{n}/{k}"),
12810×
                &mut clashes,
1282
            );
12830×
            if cur.is_empty() {
12840×
                out.remotes.remove(n);
12850×
            } else {
12860×
                out.remotes.insert(n.clone(), cur);
12870×
            }
1288
        }
12895×
        if before.policy != after.policy {
12900×
            if out.policy == after.policy {
12910×
                out.policy = before.policy;
12920×
            } else {
12930×
                clashes.push("the policy".into());
12940×
            }
12955×
        }
12965×
        if !clashes.is_empty() {
12972×
            return fail(format!(
1298
                "undo would also take back what another workspace has done since to {}; \
1299
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
13002×
                clashes.join(", ")
1301
            ));
13023×
        }
13033×
        out.workspaces = theirs;
13043×
        match before.workspaces.get(&mine) {
13053×
            Some(wc) => out.workspaces.insert(mine, *wc),
13060×
            None => out.workspaces.remove(&mine),
1307
        };
13083×
        Ok(out)
13095×
    }
1310
1311
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1312
    /// in `now` already holds: undoing them locally leaves them there.
131315×
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
131415×
        let mut out = Vec::new();
131518×
        for (name, st) in &after.bookmarks {
131618×
            if before.bookmarks.get(name) == Some(st) {
13174×
                continue;
131814×
            }
131914×
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
132014×
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
13210×
                None => BTreeSet::new(),
1322
            };
132314×
            let added: Vec<ChangeHash> = self
132414×
                .store
132514×
                .get_state(st)?
1326
                .heads
132714×
                .into_iter()
132820×
                .filter(|h| !had.contains(h))
132914×
                .collect();
133014×
            if added.is_empty() {
13311×
                continue;
133213×
            }
133313×
            for (remote, bookmarks) in &now.remotes {
13341×
                if let Some(rs) = bookmarks.get(name) {
13351×
                    let theirs = self.store.get_state(rs)?.heads;
13361×
                    if added.iter().any(|h| theirs.contains(h)) {
13371×
                        out.push((name.clone(), remote.clone()));
13381×
                    }
13390×
                }
1340
            }
1341
        }
134215×
        Ok(out)
134315×
    }
1344
1345
    /// The last operation that was not a snapshot.
13462×
    pub fn last_command(&self) -> Result<Op> {
13472×
        let (_, mut op) = self.head_op()?;
13484×
        while op.is_snapshot() {
13492×
            let Some(parent) = op.parents.first() else {
13500×
                break;
1351
            };
13522×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1353
        }
13542×
        Ok(op)
13552×
    }
1356
1357
    // ------------------------------------------------------------ states
1358
1359
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1360197×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1361197×
        if let Some(st) = self.load_state_checkpointed(heads)? {
13624×
            return Ok(st);
1363192×
        }
1364192×
        self.load_state_full(heads)
1365197×
    }
1366
1367
    /// The state of `heads` for its history (changes, tree, metadata) with
1368
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1369
    /// and friends. Build the graphs a command needs with
1370
    /// [`Repo::load_graphs_of`].
13711643×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
13721643×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
137331×
            return Ok(st);
13741612×
        }
13751612×
        self.load_state_replayed(heads, State::new_history_only())
13761643×
    }
1377
1378
    /// Build these file graphs in a history-only state.
13791734×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
13801734×
        state
13811734×
            .load_graphs(
13821734×
                nodes,
138354×
                |refs| {
138454×
                    self.read_blobs(refs).map_err(|e| {
13853×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
13863×
                    })
138754×
                },
13881972×
                |h| self.change_bytes(h),
1389
            )
13901734×
            .map_err(|e| self.index_damage(e))
13911734×
    }
1392
1393
    /// An error building graphs, and when it is a state index found
1394
    /// damaged (a file's history that does not match its hash), the
1395
    /// workspace's state indexes removed: they are rebuilt from history by
1396
    /// the next command.
13974×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
13984×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
13993×
            return e.into();
1400
        };
14012×
        for path in self.state_indexes() {
14022×
            let _ = fs::remove_file(path);
14032×
        }
14041×
        RepoError::Msg(format!(
14051×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
14061×
        ))
14074×
    }
1408
1409
    /// The graphs of `nodes` of a history-only state, built beside it (see
1410
    /// [`State::build_graphs_detached`]).
141177×
    pub fn build_graphs_detached(
141277×
        &self,
141377×
        state: &State,
141477×
        nodes: &[crate::ids::NodeId],
141577×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
141677×
        Ok(state
141777×
            .build_graphs_detached(
141877×
                nodes,
14190×
                |refs| {
14200×
                    self.read_blobs(refs).map_err(|e| {
14210×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14220×
                    })
14230×
                },
142483×
                |h| self.change_bytes(h),
1425
            )
142677×
            .map_err(|e| self.index_damage(e))?
142777×
            .into_iter()
142877×
            .collect())
142977×
    }
1430
1431
    /// The contents of texts [`State::single_text`] gave: blobs read in
1432
    /// one go, inline ones from their changes.
1433347×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1434
        use crate::objects::TextRef;
1435347×
        let refs: Vec<ObjectRef> = texts
1436347×
            .iter()
14375545×
            .filter_map(|t| match t {
14381×
                TextRef::Blob(r, _, _) => Some(*r),
14395544×
                TextRef::Inline { .. } => None,
14405545×
            })
1441347×
            .collect();
1442347×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1443347×
        let mut out = Vec::with_capacity(texts.len());
14445545×
        for t in texts {
14455545×
            let lines = match t {
14461×
                TextRef::Blob(_, count, form) => {
14471×
                    let content = blobs
14481×
                        .next()
14491×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
14501×
                    crate::objects::text_lines(&content, *count, *form)?
1451
                }
14525544×
                TextRef::Inline { change, start, end } => {
14535544×
                    let bytes = self.change_bytes(change)?;
14545544×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
14550×
                        RepoError::Msg("an inline insert lies outside its change".into())
14560×
                    })?;
14575544×
                    crate::objects::inline_lines(range)?
1458
                }
1459
            };
14605545×
            out.push(lines.bytes().to_vec());
1461
        }
1462347×
        Ok(out)
1463347×
    }
1464
1465
    /// Build every graph a history-only state still lacks, making it full.
14661738×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
14671738×
        state
14681738×
            .load_all_graphs(
146914×
                |refs| {
147014×
                    self.read_blobs(refs).map_err(|e| {
14710×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14720×
                    })
147314×
                },
14743698×
                |h| self.change_bytes(h),
1475
            )
14761738×
            .map_err(|e| self.index_damage(e))
14771738×
    }
1478
1479
    /// A change's encoding, for building graphs of its inline inserts. The
1480
    /// last few read are kept: a checkout building graphs a batch at a
1481
    /// time reads the same large changes for every batch, often in turn.
148211297×
    fn change_bytes(
148311297×
        &self,
148411297×
        h: &ChangeHash,
148511297×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
148611297×
        let mut cache = self.last_change.borrow_mut();
148719606×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
14888813×
            let hit = cache.remove(i);
14898813×
            let b = hit.1.clone();
14908813×
            cache.push(hit);
14918813×
            return Ok(b);
14922484×
        }
14932484×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
14940×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
14950×
        })?);
14962484×
        cache.push((*h, b.clone()));
1497
        // The last few, within a memory budget; the newest always stays.
14984023×
        while cache.len() > CHANGE_CACHE_COUNT
14992484×
            || (cache.len() > 1
15007504×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15011539×
        {
15021539×
            cache.remove(0);
15031539×
        }
15042484×
        Ok(b)
150511297×
    }
1506
1507
    /// Load the dependency closure of `heads` change by change.
1508246×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1509246×
        self.load_state_replayed(heads, State::new())
1510246×
    }
1511
15123167×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
15133167×
        let history = state.is_history_only();
15143167×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
15153167×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1516
        {
15173167×
            let _t = crate::timing::phase("load: read and add changes");
15183167×
            let (mut read, mut add, mut fetch) = (
15193167×
                std::time::Duration::ZERO,
15203167×
                std::time::Duration::ZERO,
15213167×
                std::time::Duration::ZERO,
15223167×
            );
152312840×
            while let Some(h) = stack.pop() {
1524
                // A change the state holds brings its history with it.
15259676×
                if !seen.insert(h) || state.contains(&h) {
15262260×
                    continue;
15277416×
                }
15287416×
                let t0 = std::time::Instant::now();
1529
                // A history-only state reads text only for the graphs it
1530
                // builds; either way the hash is the one asked for.
15317416×
                let (c, texts) = if history {
15326136×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
15336135×
                    fetch += t0.elapsed();
15346135×
                    Change::decode_skeleton(&bytes, h)
15356135×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1536
                } else {
15371280×
                    (self.store.get_change(&h)?, Vec::new())
1538
                };
15397413×
                read += t0.elapsed();
15407413×
                stack.extend(c.deps.iter().copied());
15417413×
                let t1 = std::time::Instant::now();
15427413×
                state.add_known(h, c, texts);
15437413×
                add += t1.elapsed();
1544
            }
15453164×
            crate::timing::record("load:   of which reading", read);
15463164×
            crate::timing::record("load:     of which fetching", fetch);
15473164×
            crate::timing::record("load:   of which applying", add);
1548
        }
15493164×
        let _t = crate::timing::phase("load: validate");
15503164×
        state.validate()?;
15513164×
        Ok(state)
15523167×
    }
1553
15542258×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
15552258×
        if self.bare {
15562×
            return fail("this is a bare repository: it has no working copy");
15572256×
        }
15582256×
        let view = self.view()?;
15592256×
        let h = *view
15602256×
            .workspaces
15612256×
            .get(&self.workspace)
15622256×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
15632255×
        Ok((h, self.store.get_change(&h)?))
15642258×
    }
1565
1566
    /// Heads of a bookmark's state (spec §10.1).
15671739×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
15681739×
        match view.bookmarks.get(bookmark) {
15691739×
            Some(st) => Ok(self.store.get_state(st)?.heads),
15700×
            None => Ok(vec![]),
1571
        }
15721739×
    }
1573
1574501×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1575501×
        self.heads_of(&self.view()?, &self.config.bookmark)
1576501×
    }
1577
1578
    // ------------------------------------------------------------ blobs
1579
1580390×
    fn blob_for(content: &[u8]) -> Blob {
1581390×
        Blob::of(content)
1582390×
    }
1583
1584244×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1585244×
        Self::blob_for(content).hash()
1586244×
    }
1587
1588144×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1589187×
        for c in crate::chunk::chunks(content) {
1590187×
            self.store.put_chunk(c)?;
1591
        }
1592144×
        Ok(self
1593144×
            .store
1594144×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1595144×
    }
1596
1597
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1598
    /// all their chunks, are read in parallel; a blob the store lacks goes
1599
    /// through [`Repo::read_blob`], which may fetch it lazily.
1600419×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1601419×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1602419×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
160378×
            blobs.push(match got {
160473×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
16050×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
16065×
                Err(crate::store::StoreError::NotFound(_)) => None,
16070×
                Err(e) => return Err(e.into()),
1608
            });
1609
        }
1610419×
        let chunk_refs: Vec<ObjectRef> = blobs
1611419×
            .iter()
1612419×
            .flatten()
1613419×
            .flat_map(|b| b.chunks.iter().copied())
1614419×
            .collect();
1615419×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1616419×
        let mut out = Vec::with_capacity(refs.len());
1617419×
        for (r, blob) in refs.iter().zip(blobs) {
161878×
            match blob {
16195×
                None => out.push(self.read_blob(r)?),
162073×
                Some(b) => {
162173×
                    let mut content = Vec::with_capacity(b.length as usize);
1622112×
                    for c in &b.chunks {
1623112×
                        match chunks.next() {
1624112×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
16250×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
16260×
                            Some(Err(e)) => return Err(e.into()),
16270×
                            None => return fail("chunk list ended early"),
1628
                        }
1629
                    }
163073×
                    out.push(content);
1631
                }
1632
            }
1633
        }
1634414×
        Ok(out)
1635419×
    }
1636
1637
    /// Read a blob's content, fetching it from the remote that withheld it
1638
    /// when it is lazily absent (spec §13.5).
1639112×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1640112×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
16414×
            self.fetch_lazy_blob(r)?;
1642108×
        }
1643112×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1644107×
        let mut out = Vec::with_capacity(blob.length as usize);
1645134×
        for c in &blob.chunks {
1646134×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1647
        }
1648107×
        Ok(out)
1649112×
    }
1650
1651
    // ------------------------------------------------------------ working copy
1652
1653
    /// Attributes from the `.oxyattributes` files in the working directory.
16542×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1655
        // Nested repositories and ignored paths are left out, as in a walk.
16568×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
16572×
        let files: Vec<(String, Vec<u8>)> = listing
16582×
            .files
16592×
            .into_iter()
16602×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
16612×
            .collect();
16622×
        crate::attributes::Attributes::from_files(
16632×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1664
        )
16652×
    }
1666
1667
    /// Folders holding a repository of their own that the last look at the
1668
    /// working copy left out, not being subrepos (oxygen#43).
166929×
    pub fn untracked_nested(&self) -> Vec<String> {
167029×
        self.untracked_nested.borrow().clone()
167129×
    }
1672
1673
    /// Attributes from a materialized state's `.oxyattributes` files.
16743×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
16756×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
16766×
            match &f.content {
16776×
                FileContent::Text { bytes, .. }
16786×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1679
                {
16800×
                    Some((p.as_str(), bytes.as_slice()))
1681
                }
16826×
                _ => None,
1683
            }
16846×
        }))
16853×
    }
1686
1687
    /// Store a blob, raw when the path is `nocompress`.
1688126×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1689126×
        if !nocompress {
1690124×
            return self.store_blob(content);
16912×
        }
16922×
        for c in crate::chunk::chunks(content) {
16932×
            self.store.put_chunk_nocompress(c)?;
1694
        }
16952×
        Ok(self
16962×
            .store
16972×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1698126×
    }
1699
1700
    /// This workspace's state index (oxygen#41): its working copy's base,
1701
    /// saved so a snapshot reads it rather than replaying history.
1702
    /// The state index of the state with these heads: this workspace keeps
1703
    /// the last few it used, named by their heads, so moving between two
1704
    /// states finds both.
17052339×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
17062339×
        let mut heads = heads.to_vec();
17072339×
        heads.sort();
17082339×
        let mut h = blake3::Hasher::new();
17092357×
        for c in &heads {
17102357×
            h.update(&c.0);
17112357×
        }
17122339×
        self.oxy.join("index").join(format!(
17132339×
            "{}{}",
17142339×
            self.state_index_prefix(),
17152339×
            &h.finalize().to_hex()[..16]
17162339×
        ))
17172339×
    }
1718
17194593×
    fn state_index_prefix(&self) -> String {
17204593×
        format!("state-{}-", self.workspace.to_hex())
17214593×
    }
1722
1723
    /// This workspace's state indexes, newest first.
17242254×
    fn state_indexes(&self) -> Vec<PathBuf> {
17252254×
        let prefix = self.state_index_prefix();
17262254×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
17272254×
            .into_iter()
17282254×
            .flatten()
17292254×
            .flatten()
17302254×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
17312254×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
17322254×
            .collect();
17332254×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
17342254×
        found.into_iter().map(|(_, p)| p).collect()
17352254×
    }
1736
1737
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1738
    /// from this workspace's state index when it holds that history: every
1739
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1740
    /// is loaded from history and indexed for next time.
17411949×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
17421949×
        if let Some((st, heads)) = self.read_state_index(deps) {
17431570×
            let mut have = st.maximal(deps);
17441570×
            have.sort();
17451570×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1746
                // Re-encoding reads every history: one found damaged is
1747
                // left to the build that reads it, which reports it.
1748
                #[cfg(test)]
1749151×
                if let Some(mine) = st.write_index() {
1750147×
                    assert_eq!(
1751147×
                        Some(mine),
1752147×
                        self.load_state_history(deps)?.write_index(),
1753
                        "a state index holds the state history gives"
1754
                    );
17554×
                }
1756261×
                return Ok(st);
17571309×
            }
1758
            // An index a few changes behind (a commit, a pull since): add
1759
            // what it lacks, as long as all it holds is history of `deps`.
1760
            // Anything amiss (a change beyond a shallow boundary) takes the
1761
            // long way instead.
17621309×
            let (indexed, started) = (st.len(), std::time::Instant::now());
17631309×
            if let Ok(st) = self.load_state_replayed(deps, st) {
17641308×
                let mut all = deps.to_vec();
17651308×
                all.extend(heads.iter().copied());
17661308×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
17671308×
                within.sort();
17681308×
                want.sort();
17691308×
                if within == want {
1770
                    #[cfg(test)]
1771661×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1772
                    // Writing the index costs far more than replaying a
1773
                    // few small changes: it is rewritten once it falls
1774
                    // behind, or when replaying took long (large changes).
17751306×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
17761306×
                        || started.elapsed() > INDEX_REPLAY_TIME
17777×
                    {
17787×
                        self.write_state_index(deps, &st);
17791299×
                    }
17801306×
                    return Ok(st);
17812×
                }
17821×
            }
1783379×
        }
1784382×
        let st = self.load_state_history(deps)?;
1785382×
        self.write_state_index(deps, &st);
1786382×
        Ok(st)
17871949×
    }
1788
1789
    /// Two history-only states hold the same changes and render the same
1790
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1791
    /// the checkpoint's graphs as the bases of its files' histories.
1792
    #[cfg(test)]
1793661×
    fn assert_same_state(&self, a: &State, b: &State) {
17941322×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1795661×
        assert_eq!(ids(a), ids(b), "the same changes");
17961322×
        let files = |s: &State| {
17971322×
            let mut s = s.clone();
17981322×
            self.load_all_graphs(&mut s).unwrap();
17991322×
            s.materialize().files
18001322×
        };
1801661×
        assert_eq!(files(a), files(b), "the same files");
1802661×
    }
1803
1804
    /// The state index file: its heads, a hash of its changes block and one
1805
    /// of the rest, then the body [`State::write_index`] gives, whose first
1806
    /// block is the changes. Hashed in two parts so the log can read and
1807
    /// check the changes alone.
1808
    /// The index of `deps` if there is one, else the newest, which the
1809
    /// caller may bring up to date.
18101949×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1811
        use std::io::Read;
18121949×
        let _t = crate::timing::phase("load: state index");
18131949×
        let exact = self.state_index_path(deps);
18141949×
        let reading = crate::timing::phase("load:   of which reading the file");
18151949×
        let mut f = match fs::File::open(&exact) {
1816261×
            Ok(f) => {
1817
                // Used now: the newest, so the last to be dropped.
1818261×
                let _ = fs::File::options()
1819261×
                    .write(true)
1820261×
                    .open(&exact)
1821261×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1822261×
                f
1823
            }
18241688×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1825
        };
18261570×
        let total = f.metadata().ok()?.len();
18271570×
        let mut word = [0u8; 4];
18281570×
        f.read_exact(&mut word).ok()?;
18291570×
        let n = u32::from_le_bytes(word) as usize;
18301570×
        let mut head = vec![0u8; 32 * n + 64 + 8];
18311570×
        f.read_exact(&mut head).ok()?;
18321570×
        let heads: Vec<ChangeHash> = head[..32 * n]
18331570×
            .chunks_exact(32)
18341570×
            .map(|c| ObjectRef(c.try_into().unwrap()))
18351570×
            .collect();
18361570×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
18371570×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
18381570×
        let at = (4 + head.len()) as u64;
18391570×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
18400×
            return None;
18411570×
        }
1842
        // The front only: the files' histories after it are read, each
1843
        // checked by its own hash, when a command builds that file.
18441570×
        let mut front = vec![0u8; front_len as usize];
18451570×
        f.read_exact(&mut front).ok()?;
18461570×
        drop(reading);
18471570×
        let checking = crate::timing::phase("load:   of which checking the file");
18481570×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
18491570×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
18503140×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
18511570×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
18520×
            return None;
18531570×
        }
18541570×
        drop(checking);
18551570×
        let histories = crate::state::Histories::File(
18561570×
            std::sync::Arc::new(f),
18571570×
            at + front_len,
18581570×
            total - at - front_len,
18591570×
        );
18601570×
        Some((State::read_index_front(&front, histories).ok()?, heads))
18611949×
    }
1862
1863
    /// The changes of this workspace's state index (the closure of its
1864
    /// heads), read without the rest of the index.
1865
    #[allow(clippy::type_complexity)]
1866174×
    pub(crate) fn read_state_index_changes(
1867174×
        &self,
1868174×
    ) -> Option<(
1869174×
        Vec<ChangeHash>,
1870174×
        crate::fasthash::FastMap<ChangeHash, std::sync::Arc<crate::state::ChangeMeta>>,
1871174×
    )> {
1872
        use std::io::Read;
1873174×
        let _t = crate::timing::phase("load: state index changes");
1874174×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1875157×
        let mut word = [0u8; 4];
1876157×
        f.read_exact(&mut word).ok()?;
1877157×
        let n = u32::from_le_bytes(word) as usize;
1878
        // Heads, the two sums, the front's length, then the changes block.
1879157×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1880157×
        f.read_exact(&mut head).ok()?;
1881157×
        let heads: Vec<ChangeHash> = head[..32 * n]
1882157×
            .chunks_exact(32)
1883157×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1884157×
            .collect();
1885157×
        let sum = &head[32 * n..32 * n + 32];
1886157×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1887157×
        let mut changes = vec![0u8; 4 + len];
1888157×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1889157×
        f.read_exact(&mut changes[4..]).ok()?;
1890157×
        let checking = crate::timing::phase("load:   of which checking");
1891157×
        let mut h = blake3::Hasher::new();
1892157×
        h.update_rayon(&changes);
1893157×
        if h.finalize().as_bytes() != sum {
18940×
            return None;
1895157×
        }
1896157×
        drop(checking);
1897157×
        let _decoding = crate::timing::phase("load:   of which decoding");
1898157×
        Some((heads, State::read_index_changes(&changes[4..]).ok()?))
1899174×
    }
1900
1901
    /// Save `st`, the history-only state of `deps`, as this workspace's
1902
    /// state index; quietly nothing when it cannot be (it is only a cache).
1903390×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1904390×
        let _t = crate::timing::phase("write: state index");
1905390×
        let encoding = crate::timing::phase("write:   of which encoding");
1906390×
        let Some(body) = st.write_index() else {
19070×
            return;
1908
        };
1909390×
        drop(encoding);
1910
        #[cfg(test)]
1911206×
        assert_eq!(
1912206×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1913206×
            Some(body.clone()),
1914
            "a state index reads back as written"
1915
        );
1916390×
        let mut heads = st.maximal(deps);
1917390×
        heads.sort();
1918390×
        let mut w = crate::flat::Writer::default();
1919390×
        w.count(heads.len());
1920390×
        for h in &heads {
192121×
            w.object(h);
192221×
        }
1923
        // The body is the front's length, the front, then the files'
1924
        // histories, which carry their own hashes: the sums cover the
1925
        // front's changes block and the rest of the front.
1926390×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
1927390×
        let front = &body[8..8 + front_len];
1928390×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
1929780×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1930390×
        w.fixed(&sum(&front[..split]));
1931390×
        w.fixed(&sum(&front[split..]));
1932390×
        w.fixed(&body);
1933390×
        let path = self.state_index_path(&heads);
1934390×
        let _ = fs::create_dir_all(self.oxy.join("index"));
1935390×
        let _ = write_cache(&path, &w.0);
1936
        // The last two used: the index of a state moved away from stays for
1937
        // a move back. Older ones (and the unnamed one of before) go.
1938390×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
19391×
            let _ = fs::remove_file(old);
19401×
        }
1941390×
        let _ = fs::remove_file(
1942390×
            self.oxy
1943390×
                .join("index")
1944390×
                .join(format!("state-{}", self.workspace.to_hex())),
1945390×
        );
1946390×
    }
1947
19486×
    fn locks_dir(&self) -> PathBuf {
19496×
        self.oxy.join("locks")
19506×
    }
1951
1952
    /// Whether `path` is locked locally for editing (spec §18, advisory).
19533×
    pub fn is_locked(&self, path: &str) -> bool {
19543×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
19553×
    }
1956
1957
    /// Take the advisory local lock on a `lockable` file and make it writable.
19582×
    pub fn lock_path(&self, path: &str) -> Result<()> {
19592×
        let attrs = self.disk_attributes();
19602×
        if !attrs.lookup(path).lockable {
19611×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
19621×
        }
19631×
        fs::create_dir_all(self.locks_dir())?;
19641×
        write_atomic(
19651×
            &self.locks_dir().join(path.replace('/', "%2F")),
19661×
            std::process::id().to_string().as_bytes(),
19670×
        )?;
19681×
        set_readonly(&self.root.join(path), false)?;
19691×
        Ok(())
19702×
    }
1971
1972
    /// Release the local lock and make the file read-only again.
19731×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
19741×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
19751×
        if self.root.join(path).exists() {
19761×
            set_readonly(&self.root.join(path), true)?;
19770×
        }
19781×
        Ok(())
19791×
    }
1980
1981
    /// Whether a repository path is inside the sparse filter (spec §17).
198224285×
    pub fn in_scope(&self, path: &str) -> bool {
198324285×
        self.config.sparse_paths.is_empty()
198482×
            || self
198582×
                .config
198682×
                .sparse_paths
198782×
                .iter()
198899×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
198924285×
    }
1990
19911×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
19921×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
19931×
    }
1994
1995
    /// Walk the working copy; with a manifest, a file whose size and mtime
1996
    /// match it is not read: an opaque file yields its known blob, and a
1997
    /// text file whose recorded graph key equals its base graph's key in
1998
    /// `keys` (path → key) is marked unchanged; other text files are read
1999
    /// but keep their known hash. Files modified within two seconds of the
2000
    /// manifest are never trusted (a racy stat).
2001
    ///
2002
    /// `.oxyattributes` files are always read, since their content is
2003
    /// needed; and when any of them is not known unchanged (added, removed,
2004
    /// edited, or changed in the base), no text file is taken as unchanged,
2005
    /// because attributes decide how a file compares with the base.
2006
    ///
2007
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2008
    /// (the base state's files) that exists on disk is included even when
2009
    /// an ignore rule matches it, as in Git.
20101244×
    fn walk_working_copy_with(
20111244×
        &self,
20121244×
        cache: Option<&prompt::Manifest>,
20131244×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
20141244×
        keys: Option<&KeyOf>,
20151244×
    ) -> Result<BTreeMap<String, FsEntry>> {
2016
        let mut out: BTreeMap<String, FsEntry>;
20171244×
        let sparse = &self.config.sparse_paths;
20189091×
        let in_scope = |p: &str| {
20199091×
            sparse.is_empty()
20207×
                || sparse
20217×
                    .iter()
20227×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
20239091×
        };
20241244×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2025
        let walk::Listing {
20261244×
            files,
20271244×
            symlinks,
20281244×
            nested,
20291244×
            dirs,
20301244×
        } = match self.listing_cache.take() {
2031162×
            Some(l) => l,
2032
            // Ignore rules apply to untracked paths only, so the base's
2033
            // files are not matched against them (an added file is: a rule
2034
            // written after it was snapshotted leaves it out again).
20359103×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2036
        };
20371244×
        let keys = keys.filter(|k| {
203812035×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
20391241×
            let attrs_unchanged =
20401241×
                files
20411241×
                    .iter()
204212016×
                    .filter(|(r, _, _)| is_attributes(r))
20431241×
                    .all(|(rel, _, meta)| {
20449×
                        stat_cached(rel, meta, cache)
20459×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
20469×
                    });
20471241×
            let none_removed = tracked
20481241×
                .keys()
20499042×
                .filter(|r| is_attributes(r))
20501241×
                .all(|r| on_disk.contains(r.as_str()));
20511241×
            attrs_unchanged && none_removed
20521241×
        });
20531244×
        *self.walked_dirs.borrow_mut() =
20541244×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
20551244×
        drop(walk_phase);
20561244×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2057
        // Reading files is most of a walk's cost; do it in parallel.
2058
        {
2059
            use rayon::prelude::*;
20601244×
            let mut read: Vec<(String, FsEntry)> = files
20611244×
                .par_iter()
206212047×
                .map(|(rel, path, meta)| {
2063
                    // A key is worked out only for a file the manifest
2064
                    // knows with the same stat and a key of its own.
206512047×
                    let key = keys
206612047×
                        .filter(|_| !is_attributes(rel))
206712047×
                        .filter(|_| {
206812007×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
206912007×
                        })
207012047×
                        .and_then(|k| k(rel));
207112047×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
207212047×
                })
20731244×
                .collect::<Result<Vec<_>>>()?;
207412045×
            for (rel, e) in read.iter_mut() {
2075
                // A cached blob the store lost (gc, a partial clone): read the file after all.
207612045×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
20770×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
20780×
                    e.blob = None;
207912045×
                }
2080
            }
2081
            // The listing is in path order, so the map is built without
2082
            // searching.
20831243×
            out = read.into_iter().collect();
20841243×
            for (rel, target) in symlinks {
20852×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
20862×
            }
2087
        }
20881243×
        drop(_read_phase);
20891243×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2090
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2091
        // already tracked as subrepo nodes, they contribute their pin;
2092
        // unregistered ones are left alone.
20931243×
        let modules = self.modules_on_disk();
20941243×
        let removed = self.removed_subrepos();
20951243×
        for rel in &removed {
20963×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
20971×
                self.clear_removed_subrepo(rel);
20982×
            }
2099
        }
21001243×
        let mut untracked_nested = Vec::new();
21011243×
        for dir in nested {
210230×
            let rel = self.rel_path(&dir);
210330×
            if !self.in_scope(&rel) || removed.contains(&rel) {
21043×
                continue;
210527×
            }
210627×
            let registered = modules.entries.get(&rel);
210727×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2108
            {
21091×
                untracked_nested.push(rel);
21101×
                continue;
211126×
            }
211226×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
211326×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2114
        }
21151243×
        untracked_nested.sort();
21161243×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2117
        // Tracked paths the ignore rules hid.
21181243×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
211981×
            if !self.in_scope(rel) {
212010×
                continue;
212171×
            }
212271×
            let path = self.root.join(rel);
212371×
            if *kind == NodeKind::Subrepo {
21244×
                if removed.contains(rel) {
21252×
                    continue;
21262×
                }
21272×
                let present =
21282×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
21292×
                if present {
21300×
                    let pin = subrepos::read_pin(
21310×
                        &path,
21320×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
21330×
                    )?;
21340×
                    out.insert(
21350×
                        rel.clone(),
21360×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2137
                    );
21382×
                } else if let Some(b) = blob {
21392×
                    // Not cloned (or emptied): the pin stays as recorded, as a
21402×
                    // Git gitlink does when its directory is absent.
21412×
                    out.insert(
21422×
                        rel.clone(),
21432×
                        FsEntry {
21442×
                            blob: Some(*b),
21452×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
21462×
                        },
21472×
                    );
21482×
                }
21492×
                continue;
215067×
            }
215167×
            let Ok(meta) = fs::symlink_metadata(&path) else {
215267×
                continue;
2153
            };
21540×
            let ft = meta.file_type();
21550×
            if ft.is_symlink() {
21560×
                let target = fs::read_link(&path)?;
21570×
                out.insert(
21580×
                    rel.clone(),
21590×
                    FsEntry::new(
21600×
                        NodeKind::Symlink,
2161
                        false,
21620×
                        target.to_string_lossy().as_bytes().to_vec(),
2163
                    ),
2164
                );
21650×
            } else if ft.is_file() {
21660×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
21670×
                out.insert(rel.clone(), e);
21680×
            }
2169
        }
21701243×
        Ok(out)
21711244×
    }
2172
2173
    /// The entry for one regular file, read or served from the stat cache.
21740×
    fn file_entry(
21750×
        &self,
21760×
        rel: &str,
21770×
        path: &Path,
21780×
        meta: &walk::Stat,
21790×
        cache: Option<&prompt::Manifest>,
21800×
    ) -> Result<FsEntry> {
21810×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
21820×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
21830×
            e.content = std::sync::Arc::new(fs::read(path)?);
21840×
            e.blob = None;
21850×
        }
21860×
        Ok(e)
21870×
    }
2188
2189
    /// The non-directory paths of a snapshot with their kinds, for the
2190
    /// walker's `tracked` set.
21912×
    pub(crate) fn tracked_kinds(
21922×
        snapshot: &Snapshot,
21932×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
21942×
        snapshot
21952×
            .files
21962×
            .iter()
219712×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
21988×
            .map(|(p, f)| {
21998×
                let blob = match &f.content {
22004×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
22014×
                    _ => None,
2202
                };
22038×
                (p.clone(), (f.kind, blob))
22048×
            })
22052×
            .collect()
22062×
    }
2207
2208
    /// A path under the root as a `/`-separated relative string.
220968×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
221068×
        path.strip_prefix(&self.root)
221168×
            .unwrap_or(path)
221268×
            .components()
2213130×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
221468×
            .collect::<Vec<_>>()
221568×
            .join("/")
221668×
    }
2217
}
2218
2219
impl Repo {
2220
    /// Changes reachable from the bookmark and the working copy, newest first.
222192×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
222292×
        let heads = self.bookmark_heads()?;
222392×
        if self.bare {
22241×
            return self.log_state(&heads);
222591×
        }
222691×
        let (wc_hash, wc) = self.working_copy()?;
222791×
        let mut all = heads.clone();
222891×
        all.push(wc_hash);
222991×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
223091×
        let mut entries: Vec<LogEntry> = Vec::new();
2231
        // A shallow clone knows changes beyond its boundary from a
2232
        // checkpoint's metadata only: its log comes from the state.
223391×
        let metas = if self.is_shallow() {
22341×
            self.load_state_history(&all)?
22351×
                .changes()
22369×
                .map(|(h, m)| (*h, m.clone()))
22371×
                .collect()
2238
        } else {
2239
            // The working copy's change is in hand, and is never in the
2240
            // state index: its metadata is not looked up again.
224190×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
224290×
            below.extend(wc.deps.iter().copied());
224390×
            let _t = crate::timing::phase("log: metadata");
224490×
            let mut metas = self.metas_of(&below)?;
2245322×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
224690×
                metas.push((wc_hash, crate::state::ChangeMeta::of(&wc)));
224790×
            }
224890×
            metas
2249
        };
2250421×
        for (h, meta) in metas {
2251421×
            entries.push(LogEntry {
2252421×
                hash: h,
2253421×
                change: meta,
2254421×
                is_working_copy: h == wc_hash,
2255421×
                is_head: head_set.contains(&h),
2256421×
            });
2257421×
        }
225891×
        let _sorting = crate::timing::phase("log: sort");
2259
        // The hash makes the order total, so an unstable sort gives the same.
2260789×
        entries.sort_unstable_by(|a, b| {
2261789×
            b.is_working_copy
2262789×
                .cmp(&a.is_working_copy)
2263789×
                .then(b.change.hlc.cmp(&a.change.hlc))
2264789×
                .then(b.hash.cmp(&a.hash))
2265789×
        });
226691×
        Ok(entries)
226792×
    }
2268
2269
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2270
    /// count, for paginated views.
22710×
    pub fn log_window(
22720×
        &self,
22730×
        heads: &[ChangeHash],
22740×
        offset: usize,
22750×
        limit: usize,
22760×
    ) -> Result<(Vec<LogEntry>, usize)> {
22770×
        let all = self.log_state(heads)?;
22780×
        let total = all.len();
22790×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
22800×
    }
2281
2282
    /// The log of the state with these heads, newest first, with no working
2283
    /// copy involved (for hosted repositories and any explicit state).
228410×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2285
        // The log needs change metadata only: neither graphs nor the tree.
228610×
        if self.is_shallow() {
22870×
            return Ok(self.log_of(&self.load_state_history(heads)?));
228810×
        }
228910×
        let metas = self.metas_of(heads)?;
229010×
        let depended: BTreeSet<ChangeHash> = metas
229110×
            .iter()
229230×
            .flat_map(|(_, m)| m.deps.iter().copied())
229310×
            .collect();
229410×
        let mut entries: Vec<LogEntry> = metas
229510×
            .into_iter()
229610×
            .map(|(h, meta)| LogEntry {
229730×
                hash: h,
229830×
                is_head: !depended.contains(&h),
229930×
                change: meta,
2300
                is_working_copy: false,
230130×
            })
230210×
            .collect();
230328×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
230410×
        Ok(entries)
230510×
    }
2306
2307
    /// Every change of the state with these heads and its metadata, read
2308
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2309
    /// a shallow clone's boundary is left out.
2310174×
    pub fn metas_of(
2311174×
        &self,
2312174×
        heads: &[ChangeHash],
2313174×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2314174×
        let boundary = self.boundary();
2315
        // The state index holds the metadata of its heads' closure: a
2316
        // change found there is not read from the store (a change object
2317
        // can be as large as the tree it adds).
2318174×
        let read = self.read_state_index_changes();
2319
        // Every one of `heads` in the index, and every head of the index
2320
        // among them: their closure is the index's changes, all of them
2321
        // (it is closed), and no walk is needed to find it.
2322174×
        if let Some((index_heads, all)) = &read {
2323157×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2324157×
            if heads.iter().all(|h| all.contains_key(h))
23250×
                && index_heads.iter().all(|h| asked.contains(h))
2326
            {
23270×
                let (_, all) = read.expect("matched above");
2328
                #[cfg(test)]
2329
                {
2330
                    // The walk the shortcut saves finds the same changes.
23310×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
23320×
                    let mut stack = heads.to_vec();
23330×
                    while let Some(h) = stack.pop() {
23340×
                        if seen.insert(h) {
23350×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
23360×
                        }
2337
                    }
23380×
                    assert_eq!(seen, all.keys().copied().collect::<HashSet<_>>());
2339
                }
23400×
                return Ok(all
23410×
                    .into_iter()
23420×
                    .map(|(h, m)| (h, std::sync::Arc::unwrap_or_clone(m)))
23430×
                    .collect());
2344157×
            }
234517×
        }
2346174×
        let mut indexed = read.map(|(_, all)| all);
2347174×
        let _walk = crate::timing::phase("metadata: walk");
2348174×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2349174×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2350174×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2351174×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
23521268×
        while let Some(h) = stack.pop() {
23531094×
            if !seen.insert(h) {
2354458×
                continue;
2355636×
            }
2356
            // Taken out of the index's map, each once: not copied.
2357636×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2358
                #[cfg(test)]
23590×
                assert_eq!(
23600×
                    *meta,
23610×
                    self.store.get_change_meta(&h)?,
2362
                    "the state index holds a change's metadata"
2363
                );
23640×
                let meta = std::sync::Arc::unwrap_or_clone(meta);
23650×
                stack.extend(meta.deps.iter().copied());
23660×
                out.push((h, meta));
23670×
                continue;
2368636×
            }
2369636×
            let started = std::time::Instant::now();
2370636×
            let meta = match self.store.get_change_meta(&h) {
2371636×
                Ok(m) => m,
23720×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
23730×
                Err(e) => return Err(e.into()),
2374
            };
2375636×
            stored += 1;
2376636×
            from_store += started.elapsed();
2377636×
            stack.extend(meta.deps.iter().copied());
2378636×
            out.push((h, meta));
2379
        }
2380174×
        if stored > 0 && crate::timing::enabled() {
23810×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2382174×
        }
2383174×
        Ok(out)
2384174×
    }
2385
2386
    /// The log of a state already loaded, newest first.
2387
    /// The history of lines `first..=last` (1-based) of `path` in the
2388
    /// state `heads` make (spec §27): every change that inserted or
2389
    /// deleted one of their atoms, or an atom deleted from between them,
2390
    /// newest first. Exact, as atoms keep their identity across edits.
23916×
    pub fn line_history(
23926×
        &self,
23936×
        heads: &[ChangeHash],
23946×
        path: &str,
23956×
        first: usize,
23966×
        last: usize,
23976×
    ) -> Result<Vec<LogEntry>> {
23986×
        if first == 0 || last < first {
23991×
            return fail(format!(
2400
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2401
            ));
24025×
        }
24035×
        let mut state = self.load_state_history(heads)?;
24045×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
24051×
            return fail(format!("{path} is not in that state"));
2406
        };
24074×
        self.load_graphs_of(&mut state, &[node])?;
24084×
        let live = state.live_lines(&node);
24094×
        if last > live.len() {
24101×
            return fail(format!(
2411
                "{path} has {} lines; asked for {first},{last}",
24121×
                live.len()
2413
            ));
24143×
        }
24153×
        let Some(g) = state.file(&node) else {
24160×
            return fail(format!("{path} is not a text file"));
2417
        };
24183×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
24193×
        let touched = g.touching(&atoms);
24203×
        Ok(self
24213×
            .log_of(&state)
24223×
            .into_iter()
242313×
            .filter(|e| touched.contains(&e.hash))
24243×
            .collect())
24256×
    }
2426
24278×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
24288×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
24298×
        let mut entries: Vec<LogEntry> = state
24308×
            .changes()
24318×
            .map(|(h, meta)| LogEntry {
243231×
                hash: *h,
243331×
                change: meta.clone(),
2434
                is_working_copy: false,
243531×
                is_head: head_set.contains(h),
243631×
            })
24378×
            .collect();
243840×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
24398×
        entries
24408×
    }
2441
2442
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2443
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2444
    /// (`resolve_change`).
244567×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
244667×
        let view = self.view()?;
244767×
        if let Some(st) = view.bookmarks.get(spec) {
244839×
            return Ok(self.store.get_state(st)?.heads);
244928×
        }
245028×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
24512×
            return Ok(self.store.get_state(&st)?.heads);
245226×
        }
245326×
        if let Some(heads) = self.tag_heads(spec)? {
24542×
            return Ok(heads);
245524×
        }
245624×
        Ok(vec![self.resolve_change(spec)?])
245767×
    }
2458
2459
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2460
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
246133×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
246233×
        if spec == "@" {
24630×
            return Ok(self.working_copy()?.0);
246433×
        }
246533×
        let view = self.view()?;
246633×
        let named = match view.bookmarks.get(spec) {
24671×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
246832×
            None => match remote_bookmark(&view, spec) {
24691×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
247031×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2471
            },
2472
        };
247333×
        if let Some((kind, heads)) = named {
24743×
            return match heads.len() {
24753×
                1 => Ok(heads[0]),
24760×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2477
            };
247830×
        }
247930×
        if spec.is_empty() || spec == "#" {
24800×
            return fail("empty change specifier");
248130×
        }
248230×
        let entries = self.log()?;
248330×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
248424×
            entries
248524×
                .iter()
2486103×
                .filter(|e| e.hash.starts_with_hex(hp))
248724×
                .collect()
2488
        } else {
24896×
            entries
24906×
                .iter()
249121×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
24926×
                .collect()
2493
        };
249430×
        match matches.len() {
249526×
            1 => Ok(matches[0].hash),
24964×
            0 => match self.resolve_in_remotes(spec)? {
24971×
                Some(h) => Ok(h),
24983×
                None => fail(format!("no change matches {spec:?}")),
2499
            },
2500
            _ => {
25010×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
25020×
                if ids.len() == 1 {
25030×
                    fail(format!(
2504
                        "change {spec} is divergent: {} variants",
25050×
                        matches.len()
2506
                    ))
2507
                } else {
25080×
                    fail(format!("{spec:?} is ambiguous"))
2509
                }
2510
            }
2511
        }
251233×
    }
2513
2514
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2515
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2516
    /// `None` when none matches, or more than one.
25174×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
25184×
        let view = self.view()?;
25194×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
25204×
        for bookmarks in view.remotes.values() {
25213×
            for st in bookmarks.values() {
25223×
                let heads = self.store.get_state(st)?.heads;
25237×
                for e in self.log_state(&heads)? {
25247×
                    let hit = match spec.strip_prefix('#') {
25252×
                        Some(hp) => e.hash.starts_with_hex(hp),
25265×
                        None => e.change.change_id.starts_with_hex(spec),
2527
                    };
25287×
                    if hit {
25291×
                        found.insert(e.hash);
25306×
                    }
2531
                }
2532
            }
2533
        }
25344×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
25354×
    }
2536
2537
    /// Where a change is when no local bookmark or the working copy holds
2538
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2539
    /// it is held locally, or nowhere.
25403×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
25416×
        if self.log()?.iter().any(|e| e.hash == *hash) {
25422×
            return Ok(None);
25431×
        }
25441×
        let view = self.view()?;
25451×
        for (remote, bookmarks) in &view.remotes {
25461×
            for (name, st) in bookmarks {
25471×
                let heads = self.store.get_state(st)?.heads;
25481×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
25491×
                    return Ok(Some(format!("{remote}/{name}")));
25500×
                }
2551
            }
2552
        }
25530×
        Ok(None)
25543×
    }
2555
2556
    /// Human-readable description of what a change does, with line content.
25573×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
25583×
        let change = self.store.get_change(hash)?;
25593×
        let (base, base_snapshot) = self.change_base(&change)?;
25603×
        Ok(render_change(&change, &base, &base_snapshot))
25613×
    }
2562
2563
    /// The base state of `change` (its dependencies) and its rendering, as
2564
    /// much as showing the change needs: the whole tree, and the graphs and
2565
    /// contents of the files the change edits. Other text files are left
2566
    /// unrendered ([`Snapshot::unrendered`]).
25676×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
25686×
        let base = self.load_state_history(&change.deps)?;
25696×
        self.render_base_for(change, base)
25706×
    }
2571
2572
    /// The base for showing `change` alone: the graphs of the files it
2573
    /// edits built, and the base's tree with no file rendered, which is
2574
    /// all [`render_change`](snapshot::render_change) and
2575
    /// [`diff_files_of`](snapshot::diff_files_of) read.
25762×
    pub(crate) fn tree_base_for(
25772×
        &self,
25782×
        change: &Change,
25792×
        mut base: State,
25802×
    ) -> Result<(State, Snapshot)> {
25812×
        let _t = crate::timing::phase("diff: the base's tree");
25822×
        let edited: std::collections::HashSet<NodeId> =
25838×
            change.edits.iter().map(|e| e.node()).collect();
25842×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
25852×
        self.load_graphs_of(&mut base, &nodes)?;
25862×
        let snapshot = Snapshot {
25872×
            tree: base.tree().view(),
25882×
            files: BTreeMap::new(),
25892×
            unrendered: BTreeSet::new(),
25902×
        };
25912×
        Ok((base, snapshot))
25922×
    }
2593
2594
    /// [`Repo::change_base`] with the base already loaded (the working
2595
    /// copy's comes from the state index).
2596213×
    pub(crate) fn render_base_for(
2597213×
        &self,
2598213×
        change: &Change,
2599213×
        mut base: State,
2600213×
    ) -> Result<(State, Snapshot)> {
2601213×
        let _t = crate::timing::phase("diff: render the base");
2602213×
        let edited: std::collections::HashSet<NodeId> =
2603414×
            change.edits.iter().map(|e| e.node()).collect();
2604213×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2605213×
        self.load_graphs_of(&mut base, &nodes)?;
2606213×
        let snapshot = {
2607213×
            let _t = crate::timing::phase("diff:   of which materialize");
2608213×
            base.materialize_nodes(&edited)
2609
        };
2610213×
        Ok((base, snapshot))
2611213×
    }
2612
}
2613
26140×
fn remove_any(path: &Path) -> std::io::Result<()> {
26150×
    let m = fs::symlink_metadata(path)?;
26160×
    if m.is_dir() {
26170×
        fs::remove_dir_all(path)
2618
    } else {
26190×
        fs::remove_file(path)
2620
    }
26210×
}
2622
26235×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
26245×
    let mut perms = fs::metadata(path)?.permissions();
26255×
    perms.set_readonly(readonly);
26265×
    fs::set_permissions(path, perms)
26275×
}
2628
2629
#[cfg(unix)]
26305877×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2631
    use std::os::unix::fs::PermissionsExt;
26325877×
    let mut perms = fs::metadata(path)?.permissions();
26335877×
    let mode = perms.mode();
26345877×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
26355877×
    if want != mode {
26364×
        perms.set_mode(want);
26374×
        fs::set_permissions(path, perms)?;
26385873×
    }
26395877×
    Ok(())
26405877×
}
2641
#[cfg(not(unix))]
2642
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2643
    Ok(())
2644
}
2645
2646
#[cfg(unix)]
264716282×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2648
    use std::os::unix::fs::PermissionsExt;
264916282×
    m.permissions().mode() & 0o111 != 0
265016282×
}
2651
#[cfg(not(unix))]
2652
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2653
    false
2654
}
2655
265612808×
fn op_ref(k: OpKey) -> OpRef {
265712808×
    OpRef {
265812808×
        change: k.0,
265912808×
        index: k.1,
266012808×
    }
266112808×
}
2662
26636005×
fn split_path(path: &str) -> (&str, &str) {
26646005×
    match path.rfind('/') {
26655060×
        Some(i) => (&path[..i], &path[i + 1..]),
2666945×
        None => ("", path),
2667
    }
26686005×
}
2669
2670
/// Whether `rel` is an attributes file (spec §7.6).
267167270×
fn is_attributes(rel: &str) -> bool {
267267270×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
267367270×
}
2674
2675
/// The manifest entry for `rel` when its size and mtime match it outside
2676
/// the racy window.
267724063×
fn stat_cached<'m>(
267824063×
    rel: &str,
267924063×
    meta: &walk::Stat,
268024063×
    cache: Option<&'m prompt::Manifest>,
268124063×
) -> Option<&'m prompt::ManifestEntry> {
268224063×
    let m = cache?;
268319133×
    let e = m.entries.get(rel)?;
268417796×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
268517796×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
268624063×
}
2687
2688
/// Read one working-copy file, or serve it from the stat cache (spec
2689
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2690
/// an opaque file is not read at all (its stored blob stands in), and a
2691
/// text file the manifest recorded equal to a base graph whose key is
2692
/// `key`, the key the base has now, is not read either: equal keys mean
2693
/// equal renderings, so it still equals the base. Touches no repository
2694
/// state, so the walk runs it in parallel; the caller checks that a cached
2695
/// blob is still in the store.
269612047×
fn read_file_entry(
269712047×
    rel: &str,
269812047×
    path: &Path,
269912047×
    meta: &walk::Stat,
270012047×
    cache: Option<&prompt::Manifest>,
270112047×
    key: Option<[u8; 32]>,
270212047×
) -> Result<FsEntry> {
270312047×
    let exec = meta.exec;
270412047×
    let stat = Some((meta.size, meta.mtime_ns));
270512047×
    let mut e = match stat_cached(rel, meta, cache) {
27064249×
        Some(e) if e.blob.is_some() => FsEntry {
27071×
            blob: e.blob,
27081×
            content_hash: Some(e.hash),
27091×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27101×
        },
27114248×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
27124243×
            content_hash: Some(e.hash),
27134243×
            unchanged: true,
27144243×
            graph_key: e.graph,
27154243×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27164243×
        },
27175×
        Some(e) => FsEntry {
27185×
            content_hash: Some(e.hash),
27195×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2720
        },
27217798×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2722
    };
2723
    // The stat the manifest records: taken before the read, so a file that
2724
    // changes meanwhile is read again next time.
272512046×
    e.stat = stat;
272612046×
    Ok(e)
272712047×
}
2728
2729
/// Two maps side by side in key order: each key of either, with its value
2730
/// in each. Linear, with no lookups, for maps of a whole tree.
27312473×
pub(crate) fn join<'a, A, B>(
27322473×
    a: &'a BTreeMap<String, A>,
27332473×
    b: &'a BTreeMap<String, B>,
27342473×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
27352473×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
273635424×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
27372473×
        (None, None) => None,
27382917×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
27395781×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
274024253×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2741326×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2742300×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2743
            std::cmp::Ordering::Equal => {
274423627×
                let (k, va) = a.next()?;
274523627×
                let (_, vb) = b.next()?;
274623627×
                Some((k, Some(va), Some(vb)))
2747
            }
2748
        },
274935424×
    })
27502473×
}
2751
2752
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2753
/// lookups.
27541244×
pub(crate) fn missing_from<'a, A, B>(
27551244×
    a: &'a BTreeMap<String, A>,
27561244×
    b: &BTreeMap<String, B>,
27571244×
) -> Vec<(&'a String, &'a A)> {
27581244×
    let mut keys = b.keys().peekable();
27591244×
    a.iter()
27609052×
        .filter(|(k, _)| {
276117443×
            while keys.next_if(|kb| *kb < *k).is_some() {}
27629052×
            keys.peek() != Some(k)
27639052×
        })
27641244×
        .collect()
27651244×
}