OXYGENHUB

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

1824 of 2056 lines run, 426 of 686 functions · run #301 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.
752432×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762432×
    let Some(url) = &config.storage_url else {
772427×
        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×
    )?)
1002432×
}
101
102161×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103161×
    Err(RepoError::Msg(s.into()))
104161×
}
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.
1644012×
pub(crate) fn name_file(name: &str) -> String {
1654012×
    name.replace('%', "%25").replace('/', "%2F")
1664012×
}
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
1736950×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1746950×
    Ok(crate::durable::write_atomic(path, data)?)
1756950×
}
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
1912795×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1922795×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1932795×
    fs::write(&tmp, data)?;
1942795×
    fs::rename(&tmp, path)?;
1952795×
    Ok(())
1962795×
}
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 {
23622629×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
23722629×
        FsEntry {
23822629×
            kind,
23922629×
            exec,
24022629×
            content: std::sync::Arc::new(content),
24122629×
            blob: None,
24222629×
            content_hash: None,
24322629×
            unchanged: false,
24422629×
            graph_key: None,
24522629×
            stat: None,
24622629×
        }
24722629×
    }
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
    /// New untracked files the last walk left out for their size, with
264
    /// their sizes (oxygen#98).
265
    pub(crate) skipped_large: std::cell::RefCell<Vec<(String, u64)>>,
266
    root: PathBuf,
267
    oxy: PathBuf,
268
    store: Store,
269
    workspace: WorkspaceId,
270
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
271
    bare: bool,
272
    keys_dir: PathBuf,
273
    user_config: PathBuf,
274
    pub config: Config,
275
    /// What the working copy's file system can represent (spec §7.7).
276
    platform: crate::portable::Platform,
277
    /// The encodings of the changes last read for their inline inserts,
278
    /// oldest first.
279
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
280
    /// `--at-op`: read the repository as it was after this operation;
281
    /// recording an operation is refused.
282
    at_op: Option<ObjectRef>,
283
    /// The directories (with their times) and nested repositories of the
284
    /// last walk, for the manifest written from it.
285
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
286
    /// The directories a manifest check listed, for its restamp only.
287
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
288
}
289
290
/// A walk's directories with their times, and its nested repositories.
291
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
292
293
/// Marker file of a bare repository, inside `.oxy/`.
294
const BARE_MARKER: &str = "bare";
295
/// Marker of a hosted repository that has no id yet: the first push binds
296
/// it to the pusher's id (spec §16.1).
297
const UNBOUND_MARKER: &str = "unbound";
298
299
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
300
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
3017533×
pub fn default_home() -> PathBuf {
3027533×
    if let Ok(h) = std::env::var("OXY_HOME") {
3037527×
        return PathBuf::from(h);
3046×
    }
3056×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3060×
        return PathBuf::from(x).join("oxy");
3076×
    }
308
    // Windows has no HOME as a rule: the roaming profile's application
309
    // data, as Windows programs keep theirs.
310
    #[cfg(windows)]
311
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
312
        return PathBuf::from(d).join("oxy");
313
    }
3146×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3156×
    PathBuf::from(home).join(".config").join("oxy")
3167533×
}
317
3182433×
pub fn default_keys_dir() -> PathBuf {
3192433×
    default_home().join("keys")
3202433×
}
321
3224864×
pub fn default_user_config() -> PathBuf {
3234864×
    default_home().join("config.toml")
3244864×
}
325
326
/// Where `create_identity` records the author.
327
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
328
pub enum IdentityScope {
329
    /// The user file: every repository of this user signs with it.
330
    User,
331
    /// This repository only.
332
    Repo,
333
}
334
335
impl Repo {
336
    // ------------------------------------------------------------ lifecycle
337
338224×
    pub fn init(root: &Path) -> Result<Repo> {
339224×
        let mut id = [0u8; 16];
340224×
        rand::rngs::OsRng.fill_bytes(&mut id);
341224×
        Self::init_with_id(root, id)
342224×
    }
343
344
    /// Initialize a repository with a given repository ID (clones share the
345
    /// ID of their origin, spec §14.4).
346467×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
347467×
        Self::init_on(root, id, None)
348467×
    }
349
350
    /// A new repository with a fresh id, bare or not, on `storage` or in
351
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
35212×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
35312×
        let mut id = [0u8; 16];
35412×
        rand::rngs::OsRng.fill_bytes(&mut id);
35512×
        if bare {
3560×
            Self::init_bare_on(root, id, storage)
357
        } else {
35812×
            Self::init_on(root, id, storage)
359
        }
36012×
    }
361
362
    /// Initialize a repository whose objects and operation head are kept
363
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
364482×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
365482×
        fs::create_dir_all(root)?;
366482×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
367482×
        let oxy = root.join(OXY_DIR);
368482×
        if oxy.exists() {
3691×
            return fail(format!("{} is already an oxy repository", root.display()));
370481×
        }
371481×
        fs::create_dir_all(oxy.join("ops"))?;
372481×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
373481×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
374481×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
375481×
        if let Some(url) = storage {
3763×
            config.set("storage.url", url)?;
377478×
        }
378481×
        config.save(&oxy.join("config"))?;
379481×
        let workspace = WorkspaceId::random();
380481×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
381481×
        let store = open_objects(&oxy, &config)?;
382480×
        let repo = Repo {
383480×
            last_change: Default::default(),
384480×
            at_op: None,
385480×
            walked_dirs: Default::default(),
386480×
            listed_dirs: Default::default(),
387480×
            git_export_skipped: Default::default(),
388480×
            manifest_cache: Default::default(),
389480×
            listing_cache: Default::default(),
390480×
            untracked_nested: Default::default(),
391480×
            skipped_large: Default::default(),
392480×
            root,
393480×
            oxy,
394480×
            store,
395480×
            workspace,
396480×
            bare: false,
397480×
            keys_dir: default_keys_dir(),
398480×
            platform: crate::portable::Platform::current(),
399480×
            user_config: default_user_config(),
400480×
            config,
401480×
        };
402480×
        repo.register_workspace(&workspace, &repo.root)?;
403
404480×
        let wc = repo.new_working_copy(vec![], "");
405480×
        let wc_hash = repo.store.put_change(&wc)?;
406480×
        let mut view = View::default();
407480×
        view.bookmarks.insert(
408480×
            repo.config.bookmark.clone(),
409480×
            repo.store.put_state(&StateObject::new(vec![]))?,
410
        );
411480×
        view.workspaces.insert(workspace, wc_hash);
412480×
        repo.record_op(&[], "oxy init", view)?;
413478×
        Ok(repo)
414482×
    }
415
416
    /// Create a bare repository: an object store, operation log and
417
    /// references with no workspace and no working copy, for hosting
418
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4195×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4205×
        let mut id = [0u8; 16];
4215×
        rand::rngs::OsRng.fill_bytes(&mut id);
4225×
        Self::init_bare_with_id(root, id)
4235×
    }
424
42540×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
42640×
        Self::init_bare_on(root, id, None)
42740×
    }
428
429
    /// [`Repo::init_on`] for a bare repository.
43040×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
43140×
        fs::create_dir_all(root)?;
43240×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
43340×
        let oxy = root.join(OXY_DIR);
43440×
        if oxy.exists() {
4350×
            return fail(format!("{} is already an oxy repository", root.display()));
43640×
        }
43740×
        fs::create_dir_all(oxy.join("ops"))?;
43840×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
43940×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
44040×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
44140×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
44240×
        if let Some(url) = storage {
4430×
            config.set("storage.url", url)?;
44440×
        }
44540×
        config.save(&oxy.join("config"))?;
44640×
        let store = open_objects(&oxy, &config)?;
44740×
        let repo = Repo {
44840×
            last_change: Default::default(),
44940×
            at_op: None,
45040×
            walked_dirs: Default::default(),
45140×
            listed_dirs: Default::default(),
45240×
            git_export_skipped: Default::default(),
45340×
            manifest_cache: Default::default(),
45440×
            listing_cache: Default::default(),
45540×
            untracked_nested: Default::default(),
45640×
            skipped_large: Default::default(),
45740×
            root,
45840×
            oxy,
45940×
            store,
46040×
            workspace: WorkspaceId::ZERO,
46140×
            bare: true,
46240×
            keys_dir: default_keys_dir(),
46340×
            platform: crate::portable::Platform::current(),
46440×
            user_config: default_user_config(),
46540×
            config,
46640×
        };
46740×
        let mut view = View::default();
46840×
        view.bookmarks.insert(
46940×
            repo.config.bookmark.clone(),
47040×
            repo.store.put_state(&StateObject::new(vec![]))?,
471
        );
47240×
        repo.record_op(&[], "oxy init --bare", view)?;
47340×
        Ok(repo)
47440×
    }
475
476
    /// A bare repository with no id yet. Its `id()` is all zero until the
477
    /// first push binds it (`bind_id`), so an existing repository can be
478
    /// pushed to a freshly created hosted one and keep its identity.
47914×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
48014×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
48114×
        fs::remove_file(repo.oxy.join("id"))?;
48214×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
48314×
        Ok(repo)
48414×
    }
485
4863451×
    pub fn is_unbound(&self) -> bool {
4873451×
        self.oxy.join(UNBOUND_MARKER).is_file()
4883451×
    }
489
490
    /// Give an unbound repository its id.
49113×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
49213×
        if !self.is_unbound() {
4930×
            return fail("this repository already has an id");
49413×
        }
49513×
        if id == [0; 16] {
4960×
            return fail("a repository id cannot be all zero");
49713×
        }
49813×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
49913×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
50013×
        Ok(())
50113×
    }
502
503
    /// Whether this repository has no working copy (`init_bare`).
50476×
    pub fn is_bare(&self) -> bool {
50576×
        self.bare
50676×
    }
507
508
    /// Open the repository containing `start` (searching upwards).
5091911×
    pub fn open(start: &Path) -> Result<Repo> {
5101911×
        let start = start.canonicalize()?;
5111911×
        let mut dir: Option<&Path> = Some(&start);
5121911×
        while let Some(d) = dir {
5131911×
            let oxy = d.join(OXY_DIR);
5141911×
            if oxy.is_file() {
515
                // A secondary workspace (spec §12.2): the file points at the repository.
5169×
                let text = fs::read_to_string(&oxy)?;
5179×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5180×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
519
                };
5209×
                let format = fs::read_to_string(shared.join("format"))?;
5219×
                if format != FORMAT_LINE {
5220×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5239×
                }
5249×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5259×
                let store = open_objects(&shared, &config)?;
5269×
                let mut repo = Repo {
5279×
                    last_change: Default::default(),
5289×
                    at_op: None,
5299×
                    walked_dirs: Default::default(),
5309×
                    listed_dirs: Default::default(),
5319×
                    git_export_skipped: Default::default(),
5329×
                    manifest_cache: Default::default(),
5339×
                    listing_cache: Default::default(),
5349×
                    untracked_nested: Default::default(),
5359×
                    skipped_large: Default::default(),
5369×
                    root: d.to_path_buf(),
5379×
                    oxy: shared,
5389×
                    store,
5399×
                    workspace,
5409×
                    bare: false,
5419×
                    keys_dir: default_keys_dir(),
5429×
                    platform: crate::portable::Platform::current(),
5439×
                    user_config: default_user_config(),
5449×
                    config,
5459×
                };
5469×
                repo.apply_workspace_bookmark();
5479×
                return Ok(repo);
5481902×
            }
5491902×
            if oxy.is_dir() {
5501902×
                let format = fs::read_to_string(oxy.join("format"))?;
5511902×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5521902×
                let bare = oxy.join(BARE_MARKER).is_file();
5531902×
                let workspace = if bare {
554148×
                    WorkspaceId::ZERO
555
                } else {
5561754×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5571754×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
558
                };
5591902×
                let store = open_objects(&oxy, &config)?;
5601902×
                let mut repo = Repo {
5611902×
                    last_change: Default::default(),
5621902×
                    at_op: None,
5631902×
                    walked_dirs: Default::default(),
5641902×
                    listed_dirs: Default::default(),
5651902×
                    git_export_skipped: Default::default(),
5661902×
                    manifest_cache: Default::default(),
5671902×
                    listing_cache: Default::default(),
5681902×
                    untracked_nested: Default::default(),
5691902×
                    skipped_large: Default::default(),
5701902×
                    root: d.to_path_buf(),
5711902×
                    oxy,
5721902×
                    store,
5731902×
                    workspace,
5741902×
                    bare,
5751902×
                    keys_dir: default_keys_dir(),
5761902×
                    platform: crate::portable::Platform::current(),
5771902×
                    user_config: default_user_config(),
5781902×
                    config,
5791902×
                };
5801902×
                if !bare {
5811754×
                    repo.apply_workspace_bookmark();
5821754×
                }
5831902×
                if format == FORMAT1_LINE {
5841×
                    repo.migrate_format1()?;
5851901×
                } else if format != FORMAT_LINE {
5860×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5871901×
                }
5881902×
                return Ok(repo);
5890×
            }
5900×
            dir = d.parent();
591
        }
5920×
        fail(format!(
593
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
5940×
            start.display()
595
        ))
5961911×
    }
597
598
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
599
    /// into format 2, where each bookmark names a `state` object.
6001×
    fn migrate_format1(&self) -> Result<()> {
6011×
        let (head, version) = self.read_head()?;
602
        // Collect the chain root-first.
6031×
        let mut chain: Vec<Format1Op> = Vec::new();
6041×
        let mut cur = Some(head);
6053×
        while let Some(r) = cur {
6062×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
6072×
            cur = op.parents.first().copied();
6082×
            chain.push(op);
609
        }
6101×
        chain.reverse();
6111×
        let mut new_parent: Option<ObjectRef> = None;
6122×
        for old in chain {
6132×
            let mut view = View::default();
6142×
            for (name, heads) in &old.view.bookmarks {
6152×
                view.bookmarks.insert(
6162×
                    name.clone(),
6172×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
618
                );
619
            }
6202×
            view.workspaces = old.view.workspaces.clone();
6212×
            let op = Op {
6222×
                parents: new_parent.into_iter().collect(),
6232×
                hlc: old.hlc,
6242×
                command: old.command,
6252×
                view,
6262×
                workspace: None,
6272×
                undoes: None,
6282×
            };
6292×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
630
        }
6311×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6320×
            return fail("the operation log changed while it was rewritten; run the command again");
6331×
        }
6341×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6351×
        Ok(())
6361×
    }
637
638
    /// Pack automatically once many loose objects have accumulated.
639638×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
640638×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6410×
            self.store.pack_loose()?;
6420×
            self.store.merge_packs()?;
643638×
        }
644638×
        Ok(())
645638×
    }
646
647
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6483167×
    pub fn id(&self) -> Result<[u8; 16]> {
6493167×
        if self.is_unbound() {
65019×
            return Ok([0; 16]);
6513148×
        }
6523148×
        let path = self.oxy.join("id");
6533148×
        match fs::read_to_string(&path) {
6543148×
            Ok(h) => hex::decode(h.trim())
6553148×
                .ok()
6563148×
                .and_then(|v| v.try_into().ok())
6573148×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6580×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6590×
                let mut id = [0u8; 16];
6600×
                rand::rngs::OsRng.fill_bytes(&mut id);
6610×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6620×
                Ok(id)
663
            }
6640×
            Err(e) => Err(e.into()),
665
        }
6663167×
    }
667
66862×
    pub fn root(&self) -> &Path {
66962×
        &self.root
67062×
    }
671490×
    pub fn store(&self) -> &Store {
672490×
        &self.store
673490×
    }
67411×
    pub fn workspace(&self) -> WorkspaceId {
67511×
        self.workspace
67611×
    }
677
678
    /// Use a different user directory for keys and the user config file
679
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
680
    /// Act as if the working copy were on another platform's file system
681
    /// (tests of Windows and macOS behaviour on any host).
6822×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
6832×
        self.platform = platform;
6842×
        self
6852×
    }
686
6870×
    pub fn platform(&self) -> crate::portable::Platform {
6880×
        self.platform
6890×
    }
690
691167×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
692167×
        let dir = dir.into();
693167×
        self.keys_dir = dir.join("keys");
694167×
        self.user_config = dir.join("config.toml");
695167×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
696167×
            self.config = c;
697167×
        }
698167×
        self.apply_workspace_bookmark();
699167×
        self
700167×
    }
701
702
    /// The workspace's current bookmark (spec §10.1) overrides the
703
    /// configured default when `oxy bookmark switch` has recorded one.
7041930×
    fn apply_workspace_bookmark(&mut self) {
7051930×
        if let Ok(b) = fs::read_to_string(
7061930×
            self.oxy
7071930×
                .join("workspaces")
7081930×
                .join(self.workspace.to_hex())
7091930×
                .join("bookmark"),
7101930×
        ) {
71135×
            let b = b.trim();
71235×
            if !b.is_empty() {
71335×
                self.config.bookmark = b.to_string();
71435×
            }
7151895×
        }
7161930×
    }
717
7182×
    pub fn user_config_path(&self) -> &Path {
7192×
        &self.user_config
7202×
    }
721
722
    /// Set a key in the user file and refresh the effective configuration.
72313×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
72413×
        Config::set_user(&self.user_config, key, value)?;
72512×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
72612×
        Ok(())
72713×
    }
728
729364×
    pub fn save_config(&self) -> Result<()> {
730364×
        self.config.save(&self.oxy.join("config"))
731364×
    }
732
7334216×
    fn author(&self) -> KeyId {
7344216×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7354216×
    }
736
}
737
738
impl Repo {
7391613×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7401613×
        let mut c = Change {
7411613×
            version: crate::objects::CHANGE_VERSION,
7421613×
            change_id: ChangeId::random(),
7431613×
            deps,
7441613×
            author: self.author(),
7451613×
            hlc: Hlc::now(),
7461613×
            message: message.into(),
7471613×
            tree_ops: vec![],
7481613×
            edits: vec![],
7491613×
            kind: ChangeKind::WorkingCopy,
7501613×
        };
7511613×
        c.normalize();
7521613×
        c
7531613×
    }
754
755
    // ------------------------------------------------------------ operation log
756
75713644×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
75813644×
        if let Some(r) = self.at_op {
7595×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
76013639×
        }
76113639×
        let r = self.head_ref()?;
76213637×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
76313637×
        Ok((r, op))
76413644×
    }
765
7669460×
    pub fn view(&self) -> Result<View> {
7679460×
        Ok(self.head_op()?.1.view)
7689460×
    }
769
7703318×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
7713318×
        self.record_op_undoing(parents, command, view, None)
7723318×
    }
773
774
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
7753321×
    fn record_op_undoing(
7763321×
        &self,
7773321×
        parents: &[ObjectRef],
7783321×
        command: &str,
7793321×
        view: View,
7803321×
        undoes: Option<ObjectRef>,
7813321×
    ) -> Result<ObjectRef> {
7823321×
        if self.at_op.is_some() {
7831×
            return fail(
784
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
785
            );
7863320×
        }
7873320×
        let op = Op {
7883320×
            parents: parents.to_vec(),
7893320×
            hlc: Hlc::now(),
7903320×
            command: command.into(),
7913320×
            view,
7923320×
            workspace: Some(self.workspace),
7933320×
            undoes,
7943320×
        };
7953320×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
796
        // The head is the commit point: everything it names must be on disk first.
7973318×
        let flushing = crate::timing::phase("op: flush the store");
7983318×
        self.store.flush()?;
7993316×
        drop(flushing);
800
        // Compare and swap (spec §12.1): when another process recorded an
801
        // operation since this one read the head, the two are merged
802
        // instead of one overwriting the other. On this disk the head moves
803
        // under a short lock; on any other store by its record's version,
804
        // and a record that moved meanwhile is read again and merged again.
8053316×
        let _lock = if self.store.is_local() {
8063308×
            Some(self.lock_ops()?)
807
        } else {
8088×
            None
809
        };
8103316×
        let Some(parent) = parents.first() else {
811
            // The first operation (init): there is no head yet.
812520×
            if !self.swap_head(&r, None)? {
8132×
                return fail(format!(
814
                    "{} already holds a repository's operation log",
8152×
                    self.store.backend().describe()
816
                ));
817518×
            }
818518×
            return Ok(r);
819
        };
8202796×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8212796×
        for _ in 0..HEAD_TRIES {
8222796×
            let (current, version) = self.read_head()?;
8232796×
            let to = if current == *parent {
8242779×
                r
825
            } else {
82617×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
82716×
                let merged = Op {
82817×
                    parents: vec![current, r],
82917×
                    hlc: Hlc::now(),
83017×
                    command: format!("{command} (merged with a concurrent operation)"),
83117×
                    view: self.merge_views(&base, &op.view, &theirs)?,
83216×
                    workspace: Some(self.workspace),
83316×
                    undoes: None,
834
                };
83516×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
83616×
                self.store.flush()?;
83716×
                m
838
            };
8392795×
            if self.swap_head(&to, version.as_ref())? {
8402789×
                return Ok(to);
8410×
            }
842
        }
8430×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8443321×
    }
845
846
    /// The operation head's lock, held only while the head pointer moves.
8473318×
    fn lock_ops(&self) -> Result<FileLock> {
8483318×
        fs::create_dir_all(self.oxy.join("ops"))?;
8493318×
        FileLock::acquire(
8503318×
            self.oxy.join("ops").join("lock"),
8513318×
            "another oxy process holds the operation log",
852
        )
8533318×
    }
854
85513641×
    fn head_ref(&self) -> Result<ObjectRef> {
85613641×
        Ok(self.read_head()?.0)
85713641×
    }
858
859
    /// The operation head, and on a store its record's version for
860
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
861
    /// any other store (a bucket, or memory in tests) it is the store's
862
    /// [`HEAD_RECORD`] reference record (oxygen#68).
86316526×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
86416526×
        if self.store.is_local() {
86516507×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
86616507×
            let r = ObjectRef::from_hex(hex.trim())
86716507×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
86816504×
            return Ok((r, None));
86919×
        }
87019×
        let backend = self.store.backend();
87119×
        match backend.read_ref(HEAD_RECORD) {
87219×
            Ok(Some((bytes, version))) => {
87319×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
8740×
                    || {
8750×
                        RepoError::Msg(format!(
8760×
                            "the operation head in {} is corrupt",
8770×
                            backend.describe()
8780×
                        ))
8790×
                    },
8800×
                )?;
88119×
                Ok((r, Some(version)))
882
            }
8830×
            Ok(None) => fail(format!(
884
                "{} holds no operation log (no {HEAD_RECORD} record)",
8850×
                backend.describe()
886
            )),
8870×
            Err(e) => fail(format!("read the operation head: {e}")),
888
        }
88916526×
    }
890
891
    /// Move the operation head to `to` from the `expected` version
892
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
893
    /// disk the caller holds the operations lock and the head always
894
    /// moves; on a store it moves only if the record is unchanged, and
895
    /// `false` says another process moved it first.
8963328×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
8973328×
        if self.store.is_local() {
8983318×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
8993312×
            return Ok(true);
90010×
        }
90110×
        match self
90210×
            .store
90310×
            .backend()
90410×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
905
        {
9067×
            Ok(_) => Ok(true),
9073×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
9080×
            Err(e) => fail(format!("move the operation head: {e}")),
909
        }
9103328×
    }
911
912
    /// Three-way merge of two views that both started from `base` (spec
913
    /// §12.1). A reference only one side changed takes that side's value.
914
    /// When both changed it differently: a bookmark keeps both sides'
915
    /// heads (it may then have several), a change beats a deletion, a
916
    /// workspace changed by both is an error (only one of them matches the
917
    /// files on disk), and otherwise this process's value wins for remote
918
    /// references and the policy, the first value for a tag (tags never
919
    /// move).
92017×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
92160×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
92260×
            b: &BTreeMap<K, V>,
92360×
            o: &BTreeMap<K, V>,
92460×
            t: &BTreeMap<K, V>,
92560×
            mut both: impl FnMut(&V, &V) -> Result<V>,
92660×
        ) -> Result<BTreeMap<K, V>> {
92760×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
92860×
            let mut out = BTreeMap::new();
92961×
            for k in keys {
93061×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
93161×
                let v = if ov == tv || tv == bv {
93231×
                    ov.cloned()
93330×
                } else if ov == bv {
93418×
                    tv.cloned()
935
                } else {
93612×
                    match (ov, tv) {
93712×
                        (Some(x), Some(y)) => Some(both(x, y)?),
9380×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
9390×
                        (None, None) => None,
940
                    }
941
                };
94260×
                if let Some(v) = v {
94360×
                    out.insert(k.clone(), v);
94460×
                }
945
            }
94659×
            Ok(out)
94760×
        }
94817×
        let bookmarks = pick(
94917×
            &base.bookmarks,
95017×
            &ours.bookmarks,
95117×
            &theirs.bookmarks,
95211×
            |x, y| {
95311×
                let mut heads = self.store.get_state(x)?.heads;
95411×
                heads.extend(self.store.get_state(y)?.heads);
95511×
                let heads = self.load_state(&heads)?.maximal(&heads);
95611×
                Ok(self.store.put_state(&StateObject::new(heads))?)
95711×
            },
9580×
        )?;
959
        // Two operations that both replaced one workspace's working copy
960
        // cannot both be right: the files on disk match only one of them.
961
        // The working-copy lock keeps this from happening; should it happen
962
        // anyway, this operation is not recorded.
96317×
        let workspaces = pick(
96417×
            &base.workspaces,
96517×
            &ours.workspaces,
96617×
            &theirs.workspaces,
9671×
            |_, _| {
9681×
                fail(
969
                    "another oxy process changed this working copy at the same time; \
970
                     this command was not recorded: check `oxy status` and run it again",
971
                )
9721×
            },
9731×
        )?;
97416×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
97516×
        let empty = BTreeMap::new();
97616×
        let names: BTreeSet<&String> = base
97716×
            .remotes
97816×
            .keys()
97916×
            .chain(ours.remotes.keys())
98016×
            .chain(theirs.remotes.keys())
98116×
            .collect();
98216×
        let mut remotes = BTreeMap::new();
98316×
        for n in names {
98410×
            let m = pick(
98510×
                base.remotes.get(n).unwrap_or(&empty),
98610×
                ours.remotes.get(n).unwrap_or(&empty),
98710×
                theirs.remotes.get(n).unwrap_or(&empty),
9880×
                |x, _| Ok(*x),
9890×
            )?;
99010×
            if !m.is_empty() {
99110×
                remotes.insert(n.clone(), m);
99210×
            }
993
        }
99416×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
99516×
            ours.policy
9960×
        } else if ours.policy == base.policy {
9970×
            theirs.policy
998
        } else {
9990×
            ours.policy.or(theirs.policy)
1000
        };
100116×
        self.store.flush()?;
100216×
        Ok(View {
100316×
            bookmarks,
100416×
            workspaces,
100516×
            remotes,
100616×
            policy,
100716×
            tags,
100816×
        })
100917×
    }
1010
101147×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
101247×
        let mut out = Vec::new();
101347×
        let (mut r, mut op) = self.head_op()?;
1014
        loop {
1015255×
            let next = op.parents.first().copied();
1016255×
            out.push((r, op));
1017255×
            match next {
1018208×
                Some(p) => {
1019208×
                    r = p;
1020208×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1021
                }
102247×
                None => break,
1023
            }
1024
        }
102547×
        Ok(out)
102647×
    }
1027
1028
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1029
    ///
1030
    /// The command undone is the newest one this workspace ran: operations
1031
    /// that only recorded a working-copy snapshot are skipped (the files are
1032
    /// still on disk and the next snapshot recreates them), as are pushes
1033
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1034
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1035
    /// operations are never undone, and a command an earlier undo already
1036
    /// reverted is passed over, so undoing again goes further back.
1037
    ///
1038
    /// When nothing newer came from another workspace, the operation head
1039
    /// moves back to before the command. Otherwise the command is reverted
1040
    /// in place: every reference it changed goes back to its value before
1041
    /// it, recorded as a new operation that names it, and anything another
1042
    /// workspace changed since is kept. A reference both the command and a
1043
    /// later operation of another workspace changed is not guessed at: the
1044
    /// undo is refused, naming it.
1045
    ///
1046
    /// When the working copy is clean and was clean after the command's
1047
    /// predecessor, its files follow too, since nothing on disk can be
1048
    /// lost; otherwise they stay as they are (an undone commit's edits come
1049
    /// back as uncommitted work).
105016×
    pub fn undo(&self) -> Result<Undone> {
105116×
        let _wc = self.lock_working_copy()?;
105216×
        let clean_now =
105316×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
105416×
        let (head_ref, head) = self.head_op()?;
105516×
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
105640×
        let load = |r: &ObjectRef| -> Result<Op> {
105740×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
105840×
        };
105916×
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
106016×
        let mut pending_checkout: Option<Op> = None;
106116×
        let mut others = 0usize;
106216×
        let (mut r, mut op) = (head_ref, head.clone());
106315×
        let (target_ref, target, parent) = loop {
106441×
            let parent = match op.parents.first() {
106540×
                Some(p) => Some((*p, load(p)?)),
10661×
                None => None,
1067
            };
106841×
            if skip.contains(&r) {
10691×
                pending_checkout = None;
107040×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
107110×
                // A push cannot be taken back: undoing it would only make
107210×
                // this repository forget what the remote holds.
107330×
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
107410×
                others += 1;
107520×
            } else if let Some(u) = op.undoes {
10761×
                skip.insert(u);
10771×
                pending_checkout = None;
107819×
            } else if op.command.ends_with(" (checkout)") {
10793×
                pending_checkout = Some(op.clone());
10803×
            } else {
108116×
                match parent {
108215×
                    Some((_, p)) => break (r, op, p),
10831×
                    None => return fail("nothing to undo in this workspace"),
1084
                }
1085
            }
108625×
            match parent {
108725×
                Some((pr, p)) => (r, op) = (pr, p),
10880×
                None => return fail("nothing to undo in this workspace"),
1089
            }
1090
        };
109115×
        let before = parent.view;
109215×
        let after = pending_checkout
109315×
            .map(|o| o.view)
109415×
            .unwrap_or_else(|| target.view.clone());
109515×
        let changes = self.view_changes(&before, &after)?;
109615×
        let pushed = self.pushed_by(&before, &after, &head.view)?;
109715×
        let restored_wc = before.workspaces.get(&self.workspace).copied();
109815×
        if others == 0 {
1099
            // Only this workspace's operations since: move the head back.
110010×
            let _lock = if self.store.is_local() {
110110×
                Some(self.lock_ops()?)
1102
            } else {
11030×
                None
1104
            };
110510×
            let parent_ref = *target.parents.first().expect("the target has a parent");
110610×
            let (now, version) = self.read_head()?;
110710×
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
11080×
                return fail("another oxy command ran while undoing; run undo again");
110910×
            }
1110
        } else {
11115×
            let view = self.revert_view(&head.view, &before, &after)?;
11123×
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1113
        }
111413×
        self.drop_manifest();
111513×
        if let Some(then) = restored_wc {
111613×
            if clean_now && Some(then) != wc_now {
1117
                // Past `core.snapshot-retention` the working copy may be
1118
                // gone: the files then stay as they are.
111910×
                let Ok(wc) = self.store.get_change(&then) else {
11200×
                    return Ok(Undone {
11210×
                        command: target.command,
11220×
                        changes,
11230×
                        others_kept: others,
11240×
                        pushed,
11250×
                    });
1126
                };
112710×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
11288×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1129
                    // The files differ from the restored working copy by
1130
                    // exactly what the undone command did: nothing else is
1131
                    // on disk, as the working copy was clean.
11328×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
11332×
                }
11343×
            }
11350×
        }
113613×
        Ok(Undone {
113713×
            command: target.command,
113813×
            changes,
113913×
            others_kept: others,
114013×
            pushed,
114113×
        })
114216×
    }
1143
1144
    /// Whether operation `op` was a push: it changed only what this
1145
    /// repository knows of remotes.
114631×
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
114731×
        let Some(p) = parent else {
11481×
            return false;
1149
        };
115030×
        op.command.starts_with("oxy push")
11511×
            && op.view.bookmarks == p.view.bookmarks
11521×
            && op.view.tags == p.view.tags
11531×
            && op.view.workspaces == p.view.workspaces
11541×
            && op.view.policy == p.view.policy
115531×
    }
1156
1157
    /// Whether operation `op` (whose predecessor is `parent`) was this
1158
    /// workspace's. Operations record their workspace (oxygen#99); for older
1159
    /// ones it is read from the view: one that changed only other
1160
    /// workspaces' working copies was theirs, anything else counts as ours.
116130×
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
116230×
        if let Some(w) = op.workspace {
116330×
            return w == self.workspace;
11640×
        }
11650×
        let Some(p) = parent else {
11660×
            return true;
1167
        };
11680×
        let ids: BTreeSet<&WorkspaceId> = op
11690×
            .view
11700×
            .workspaces
11710×
            .keys()
11720×
            .chain(p.view.workspaces.keys())
11730×
            .collect();
11740×
        let moved: Vec<&WorkspaceId> = ids
11750×
            .into_iter()
11760×
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
11770×
            .collect();
11780×
        moved.is_empty() || moved.contains(&&self.workspace)
117930×
    }
1180
1181
    /// `current` with what changed from `before` to `after` put back, this
1182
    /// workspace's working copy included; refused when a later operation
1183
    /// changed one of the same references again.
11845×
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
118510×
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
118610×
            cur: &mut BTreeMap<K, V>,
118710×
            before: &BTreeMap<K, V>,
118810×
            after: &BTreeMap<K, V>,
118910×
            name: impl Fn(&K) -> String,
119010×
            clashes: &mut Vec<String>,
119110×
        ) {
119210×
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
119310×
            for k in keys {
11945×
                let (b, a) = (before.get(k), after.get(k));
11955×
                if a == b {
11964×
                    continue;
11971×
                }
11981×
                if cur.get(k) != a {
11991×
                    clashes.push(name(k));
12001×
                    continue;
12010×
                }
12020×
                match b {
12030×
                    Some(v) => cur.insert(k.clone(), v.clone()),
12040×
                    None => cur.remove(k),
1205
                };
1206
            }
120710×
        }
12085×
        let mut out = current.clone();
12095×
        let mut clashes = Vec::new();
1210
        // A bookmark another workspace moved since is put back head by
1211
        // head: the heads the command added go, the heads it replaced
1212
        // return, and the other workspace's heads stay. Only when a later
1213
        // change was built on one the command added is that not possible.
12145×
        let names: BTreeSet<&String> = before
12155×
            .bookmarks
12165×
            .keys()
12175×
            .chain(after.bookmarks.keys())
12185×
            .collect();
12198×
        for name in names {
12208×
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
12218×
            let cur = current.bookmarks.get(name);
12228×
            if a == b {
12234×
                continue;
12244×
            }
12254×
            if cur == a {
12262×
                match b {
12272×
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
12280×
                    None => out.bookmarks.remove(name),
1229
                };
12302×
                continue;
12312×
            }
12322×
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
12330×
                clashes.push(format!("bookmark {name}"));
12340×
                continue;
1235
            };
12362×
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
12372×
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
12382×
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
12392×
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
12402×
            if !added.iter().all(|h| now.contains(h)) {
12411×
                clashes.push(format!(
1242
                    "bookmark {name} (a later change builds on this one)"
1243
                ));
12441×
                continue;
12451×
            }
12461×
            let mut heads: Vec<ChangeHash> = now
12471×
                .iter()
12483×
                .filter(|h| !added.contains(h))
12491×
                .chain(was.difference(&became))
12501×
                .copied()
12511×
                .collect();
12521×
            heads.sort();
12531×
            heads.dedup();
12541×
            let heads = self.load_state(&heads)?.maximal(&heads);
12551×
            out.bookmarks.insert(
12561×
                name.clone(),
12571×
                self.store.put_state(&StateObject::new(heads))?,
1258
            );
1259
        }
1260
12615×
        back(
12625×
            &mut out.tags,
12635×
            &before.tags,
12645×
            &after.tags,
12650×
            |k| format!("tag {k}"),
12665×
            &mut clashes,
1267
        );
12685×
        let mine = self.workspace;
126915×
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
127015×
            v.workspaces
127115×
                .iter()
127229×
                .filter(|(k, _)| **k != mine)
127315×
                .map(|(k, v)| (*k, *v))
127415×
                .collect()
127515×
        };
12765×
        let mut theirs = others(&out);
12775×
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
12781×
            Some(p) => format!("the workspace at {}", p.display()),
12790×
            None => format!("workspace {}", id.to_hex()),
12801×
        };
12815×
        back(
12825×
            &mut theirs,
12835×
            &others(before),
12845×
            &others(after),
12855×
            workspace_name,
12865×
            &mut clashes,
1287
        );
12885×
        let empty = BTreeMap::new();
12895×
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
12905×
        for n in names {
12910×
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
12920×
            back(
12930×
                &mut cur,
12940×
                before.remotes.get(n).unwrap_or(&empty),
12950×
                after.remotes.get(n).unwrap_or(&empty),
12960×
                |k| format!("{n}/{k}"),
12970×
                &mut clashes,
1298
            );
12990×
            if cur.is_empty() {
13000×
                out.remotes.remove(n);
13010×
            } else {
13020×
                out.remotes.insert(n.clone(), cur);
13030×
            }
1304
        }
13055×
        if before.policy != after.policy {
13060×
            if out.policy == after.policy {
13070×
                out.policy = before.policy;
13080×
            } else {
13090×
                clashes.push("the policy".into());
13100×
            }
13115×
        }
13125×
        if !clashes.is_empty() {
13132×
            return fail(format!(
1314
                "undo would also take back what another workspace has done since to {}; \
1315
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
13162×
                clashes.join(", ")
1317
            ));
13183×
        }
13193×
        out.workspaces = theirs;
13203×
        match before.workspaces.get(&mine) {
13213×
            Some(wc) => out.workspaces.insert(mine, *wc),
13220×
            None => out.workspaces.remove(&mine),
1323
        };
13243×
        Ok(out)
13255×
    }
1326
1327
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1328
    /// in `now` already holds: undoing them locally leaves them there.
132915×
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
133015×
        let mut out = Vec::new();
133118×
        for (name, st) in &after.bookmarks {
133218×
            if before.bookmarks.get(name) == Some(st) {
13334×
                continue;
133414×
            }
133514×
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
133614×
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
13370×
                None => BTreeSet::new(),
1338
            };
133914×
            let added: Vec<ChangeHash> = self
134014×
                .store
134114×
                .get_state(st)?
1342
                .heads
134314×
                .into_iter()
134420×
                .filter(|h| !had.contains(h))
134514×
                .collect();
134614×
            if added.is_empty() {
13471×
                continue;
134813×
            }
134913×
            for (remote, bookmarks) in &now.remotes {
13501×
                if let Some(rs) = bookmarks.get(name) {
13511×
                    let theirs = self.store.get_state(rs)?.heads;
13521×
                    if added.iter().any(|h| theirs.contains(h)) {
13531×
                        out.push((name.clone(), remote.clone()));
13541×
                    }
13550×
                }
1356
            }
1357
        }
135815×
        Ok(out)
135915×
    }
1360
1361
    /// The last operation that was not a snapshot.
13622×
    pub fn last_command(&self) -> Result<Op> {
13632×
        let (_, mut op) = self.head_op()?;
13644×
        while op.is_snapshot() {
13652×
            let Some(parent) = op.parents.first() else {
13660×
                break;
1367
            };
13682×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1369
        }
13702×
        Ok(op)
13712×
    }
1372
1373
    // ------------------------------------------------------------ states
1374
1375
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1376206×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1377206×
        if let Some(st) = self.load_state_checkpointed(heads)? {
13784×
            return Ok(st);
1379201×
        }
1380201×
        self.load_state_full(heads)
1381206×
    }
1382
1383
    /// The state of `heads` for its history (changes, tree, metadata) with
1384
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1385
    /// and friends. Build the graphs a command needs with
1386
    /// [`Repo::load_graphs_of`].
13871690×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
13881690×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
138931×
            return Ok(st);
13901659×
        }
13911659×
        self.load_state_replayed(heads, State::new_history_only())
13921690×
    }
1393
1394
    /// Build these file graphs in a history-only state.
13951772×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
13961772×
        state
13971772×
            .load_graphs(
13981772×
                nodes,
139954×
                |refs| {
140054×
                    self.read_blobs(refs).map_err(|e| {
14013×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14023×
                    })
140354×
                },
14041952×
                |h| self.change_bytes(h),
1405
            )
14061772×
            .map_err(|e| self.index_damage(e))
14071772×
    }
1408
1409
    /// An error building graphs, and when it is a state index found
1410
    /// damaged (a file's history that does not match its hash), the
1411
    /// workspace's state indexes removed: they are rebuilt from history by
1412
    /// the next command.
14134×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
14144×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
14153×
            return e.into();
1416
        };
14172×
        for path in self.state_indexes() {
14182×
            let _ = fs::remove_file(path);
14192×
        }
14201×
        RepoError::Msg(format!(
14211×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
14221×
        ))
14234×
    }
1424
1425
    /// The graphs of `nodes` of a history-only state, built beside it (see
1426
    /// [`State::build_graphs_detached`]).
142777×
    pub fn build_graphs_detached(
142877×
        &self,
142977×
        state: &State,
143077×
        nodes: &[crate::ids::NodeId],
143177×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
143277×
        Ok(state
143377×
            .build_graphs_detached(
143477×
                nodes,
14350×
                |refs| {
14360×
                    self.read_blobs(refs).map_err(|e| {
14370×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14380×
                    })
14390×
                },
144083×
                |h| self.change_bytes(h),
1441
            )
144277×
            .map_err(|e| self.index_damage(e))?
144377×
            .into_iter()
144477×
            .collect())
144577×
    }
1446
1447
    /// The contents of texts [`State::single_text`] gave: blobs read in
1448
    /// one go, inline ones from their changes.
1449354×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1450
        use crate::objects::TextRef;
1451354×
        let refs: Vec<ObjectRef> = texts
1452354×
            .iter()
14535550×
            .filter_map(|t| match t {
14541×
                TextRef::Blob(r, _, _) => Some(*r),
14555549×
                TextRef::Inline { .. } => None,
14565550×
            })
1457354×
            .collect();
1458354×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1459354×
        let mut out = Vec::with_capacity(texts.len());
14605550×
        for t in texts {
14615550×
            let lines = match t {
14621×
                TextRef::Blob(_, count, form) => {
14631×
                    let content = blobs
14641×
                        .next()
14651×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
14661×
                    crate::objects::text_lines(&content, *count, *form)?
1467
                }
14685549×
                TextRef::Inline { change, start, end } => {
14695549×
                    let bytes = self.change_bytes(change)?;
14705549×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
14710×
                        RepoError::Msg("an inline insert lies outside its change".into())
14720×
                    })?;
14735549×
                    crate::objects::inline_lines(range)?
1474
                }
1475
            };
14765550×
            out.push(lines.bytes().to_vec());
1477
        }
1478354×
        Ok(out)
1479354×
    }
1480
1481
    /// Build every graph a history-only state still lacks, making it full.
14821805×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
14831805×
        state
14841805×
            .load_all_graphs(
148516×
                |refs| {
148616×
                    self.read_blobs(refs).map_err(|e| {
14870×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14880×
                    })
148916×
                },
14903768×
                |h| self.change_bytes(h),
1491
            )
14921805×
            .map_err(|e| self.index_damage(e))
14931805×
    }
1494
1495
    /// A change's encoding, for building graphs of its inline inserts. The
1496
    /// last few read are kept: a checkout building graphs a batch at a
1497
    /// time reads the same large changes for every batch, often in turn.
149811352×
    fn change_bytes(
149911352×
        &self,
150011352×
        h: &ChangeHash,
150111352×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
150211352×
        let mut cache = self.last_change.borrow_mut();
150319536×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
15048906×
            let hit = cache.remove(i);
15058906×
            let b = hit.1.clone();
15068906×
            cache.push(hit);
15078906×
            return Ok(b);
15082446×
        }
15092446×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
15100×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
15110×
        })?);
15122446×
        cache.push((*h, b.clone()));
1513
        // The last few, within a memory budget; the newest always stays.
15143941×
        while cache.len() > CHANGE_CACHE_COUNT
15152446×
            || (cache.len() > 1
15167304×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15171495×
        {
15181495×
            cache.remove(0);
15191495×
        }
15202446×
        Ok(b)
152111352×
    }
1522
1523
    /// Load the dependency closure of `heads` change by change.
1524255×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1525255×
        self.load_state_replayed(heads, State::new())
1526255×
    }
1527
15283254×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
15293254×
        let history = state.is_history_only();
15303254×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
15313254×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1532
        {
15333254×
            let _t = crate::timing::phase("load: read and add changes");
15343254×
            let (mut read, mut add, mut fetch) = (
15353254×
                std::time::Duration::ZERO,
15363254×
                std::time::Duration::ZERO,
15373254×
                std::time::Duration::ZERO,
15383254×
            );
153913031×
            while let Some(h) = stack.pop() {
1540
                // A change the state holds brings its history with it.
15419780×
                if !seen.insert(h) || state.contains(&h) {
15422249×
                    continue;
15437531×
                }
15447531×
                let t0 = std::time::Instant::now();
1545
                // A history-only state reads text only for the graphs it
1546
                // builds; either way the hash is the one asked for.
15477531×
                let (c, texts) = if history {
15486194×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
15496193×
                    fetch += t0.elapsed();
15506193×
                    Change::decode_skeleton(&bytes, h)
15516193×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1552
                } else {
15531337×
                    (self.store.get_change(&h)?, Vec::new())
1554
                };
15557528×
                read += t0.elapsed();
15567528×
                stack.extend(c.deps.iter().copied());
15577528×
                let t1 = std::time::Instant::now();
15587528×
                state.add_known(h, c, texts);
15597528×
                add += t1.elapsed();
1560
            }
15613251×
            crate::timing::record("load:   of which reading", read);
15623251×
            crate::timing::record("load:     of which fetching", fetch);
15633251×
            crate::timing::record("load:   of which applying", add);
1564
        }
15653251×
        let _t = crate::timing::phase("load: validate");
15663251×
        state.validate()?;
15673251×
        Ok(state)
15683254×
    }
1569
15702320×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
15712320×
        if self.bare {
15722×
            return fail("this is a bare repository: it has no working copy");
15732318×
        }
15742318×
        let view = self.view()?;
15752318×
        let h = *view
15762318×
            .workspaces
15772318×
            .get(&self.workspace)
15782318×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
15792317×
        Ok((h, self.store.get_change(&h)?))
15802320×
    }
1581
1582
    /// Heads of a bookmark's state (spec §10.1).
15831767×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
15841767×
        match view.bookmarks.get(bookmark) {
15851767×
            Some(st) => Ok(self.store.get_state(st)?.heads),
15860×
            None => Ok(vec![]),
1587
        }
15881767×
    }
1589
1590510×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1591510×
        self.heads_of(&self.view()?, &self.config.bookmark)
1592510×
    }
1593
1594
    // ------------------------------------------------------------ blobs
1595
1596399×
    fn blob_for(content: &[u8]) -> Blob {
1597399×
        Blob::of(content)
1598399×
    }
1599
1600246×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1601246×
        Self::blob_for(content).hash()
1602246×
    }
1603
1604151×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1605194×
        for c in crate::chunk::chunks(content) {
1606194×
            self.store.put_chunk(c)?;
1607
        }
1608151×
        Ok(self
1609151×
            .store
1610151×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1611151×
    }
1612
1613
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1614
    /// all their chunks, are read in parallel; a blob the store lacks goes
1615
    /// through [`Repo::read_blob`], which may fetch it lazily.
1616428×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1617428×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1618428×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
161980×
            blobs.push(match got {
162075×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
16210×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
16225×
                Err(crate::store::StoreError::NotFound(_)) => None,
16230×
                Err(e) => return Err(e.into()),
1624
            });
1625
        }
1626428×
        let chunk_refs: Vec<ObjectRef> = blobs
1627428×
            .iter()
1628428×
            .flatten()
1629428×
            .flat_map(|b| b.chunks.iter().copied())
1630428×
            .collect();
1631428×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1632428×
        let mut out = Vec::with_capacity(refs.len());
1633428×
        for (r, blob) in refs.iter().zip(blobs) {
163480×
            match blob {
16355×
                None => out.push(self.read_blob(r)?),
163675×
                Some(b) => {
163775×
                    let mut content = Vec::with_capacity(b.length as usize);
1638114×
                    for c in &b.chunks {
1639114×
                        match chunks.next() {
1640114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
16410×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
16420×
                            Some(Err(e)) => return Err(e.into()),
16430×
                            None => return fail("chunk list ended early"),
1644
                        }
1645
                    }
164675×
                    out.push(content);
1647
                }
1648
            }
1649
        }
1650423×
        Ok(out)
1651428×
    }
1652
1653
    /// Read a blob's content, fetching it from the remote that withheld it
1654
    /// when it is lazily absent (spec §13.5).
1655113×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1656113×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
16574×
            self.fetch_lazy_blob(r)?;
1658109×
        }
1659113×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1660108×
        let mut out = Vec::with_capacity(blob.length as usize);
1661135×
        for c in &blob.chunks {
1662135×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1663
        }
1664108×
        Ok(out)
1665113×
    }
1666
1667
    // ------------------------------------------------------------ working copy
1668
1669
    /// Attributes from the `.oxyattributes` files in the working directory.
16702×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1671
        // Nested repositories and ignored paths are left out, as in a walk.
16728×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
16732×
        let files: Vec<(String, Vec<u8>)> = listing
16742×
            .files
16752×
            .into_iter()
16762×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
16772×
            .collect();
16782×
        crate::attributes::Attributes::from_files(
16792×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1680
        )
16812×
    }
1682
1683
    /// Folders holding a repository of their own that the last look at the
1684
    /// working copy left out, not being subrepos (oxygen#43).
168529×
    pub fn untracked_nested(&self) -> Vec<String> {
168629×
        self.untracked_nested.borrow().clone()
168729×
    }
1688
1689
    /// New untracked files the last snapshot left out for being larger than
1690
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
169133×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
169233×
        self.skipped_large.borrow().clone()
169333×
    }
1694
1695
    /// Attributes from a materialized state's `.oxyattributes` files.
16963×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
16976×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
16986×
            match &f.content {
16996×
                FileContent::Text { bytes, .. }
17006×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1701
                {
17020×
                    Some((p.as_str(), bytes.as_slice()))
1703
                }
17046×
                _ => None,
1705
            }
17066×
        }))
17073×
    }
1708
1709
    /// Store a blob, raw when the path is `nocompress`.
1710132×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1711132×
        if !nocompress {
1712130×
            return self.store_blob(content);
17132×
        }
17142×
        for c in crate::chunk::chunks(content) {
17152×
            self.store.put_chunk_nocompress(c)?;
1716
        }
17172×
        Ok(self
17182×
            .store
17192×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1720132×
    }
1721
1722
    /// This workspace's state index (oxygen#41): its working copy's base,
1723
    /// saved so a snapshot reads it rather than replaying history.
1724
    /// The state index of the state with these heads: this workspace keeps
1725
    /// the last few it used, named by their heads, so moving between two
1726
    /// states finds both.
17272401×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
17282401×
        let mut heads = heads.to_vec();
17292401×
        heads.sort();
17302401×
        let mut h = blake3::Hasher::new();
17312401×
        for c in &heads {
17322379×
            h.update(&c.0);
17332379×
        }
17342401×
        self.oxy.join("index").join(format!(
17352401×
            "{}{}",
17362401×
            self.state_index_prefix(),
17372401×
            &h.finalize().to_hex()[..16]
17382401×
        ))
17392401×
    }
1740
17414711×
    fn state_index_prefix(&self) -> String {
17424711×
        format!("state-{}-", self.workspace.to_hex())
17434711×
    }
1744
1745
    /// This workspace's state indexes, newest first.
17462310×
    fn state_indexes(&self) -> Vec<PathBuf> {
17472310×
        let prefix = self.state_index_prefix();
17482310×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
17492310×
            .into_iter()
17502310×
            .flatten()
17512310×
            .flatten()
17522310×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
17532310×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
17542310×
            .collect();
17552310×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
17562310×
        found.into_iter().map(|(_, p)| p).collect()
17572310×
    }
1758
1759
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1760
    /// from this workspace's state index when it holds that history: every
1761
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1762
    /// is loaded from history and indexed for next time.
17632002×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
17642002×
        if let Some((st, heads)) = self.read_state_index(deps) {
17651610×
            let mut have = st.maximal(deps);
17661610×
            have.sort();
17671610×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1768
                // Re-encoding reads every history: one found damaged is
1769
                // left to the build that reads it, which reports it.
1770
                #[cfg(test)]
1771157×
                if let Some(mine) = st.write_index() {
1772153×
                    assert_eq!(
1773153×
                        Some(mine),
1774153×
                        self.load_state_history(deps)?.write_index(),
1775
                        "a state index holds the state history gives"
1776
                    );
17774×
                }
1778270×
                return Ok(st);
17791340×
            }
1780
            // An index a few changes behind (a commit, a pull since): add
1781
            // what it lacks, as long as all it holds is history of `deps`.
1782
            // Anything amiss (a change beyond a shallow boundary) takes the
1783
            // long way instead.
17841340×
            let (indexed, started) = (st.len(), std::time::Instant::now());
17851340×
            if let Ok(st) = self.load_state_replayed(deps, st) {
17861339×
                let mut all = deps.to_vec();
17871339×
                all.extend(heads.iter().copied());
17881339×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
17891339×
                within.sort();
17901339×
                want.sort();
17911339×
                if within == want {
1792
                    #[cfg(test)]
1793686×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1794
                    // Writing the index costs far more than replaying a
1795
                    // few small changes: it is rewritten once it falls
1796
                    // behind, or when replaying took long (large changes).
17971337×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
17981337×
                        || started.elapsed() > INDEX_REPLAY_TIME
17993×
                    {
18003×
                        self.write_state_index(deps, &st);
18011334×
                    }
18021337×
                    return Ok(st);
18032×
                }
18041×
            }
1805392×
        }
1806395×
        let st = self.load_state_history(deps)?;
1807395×
        self.write_state_index(deps, &st);
1808395×
        Ok(st)
18092002×
    }
1810
1811
    /// Two history-only states hold the same changes and render the same
1812
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1813
    /// the checkpoint's graphs as the bases of its files' histories.
1814
    #[cfg(test)]
1815686×
    fn assert_same_state(&self, a: &State, b: &State) {
18161372×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1817686×
        assert_eq!(ids(a), ids(b), "the same changes");
18181372×
        let files = |s: &State| {
18191372×
            let mut s = s.clone();
18201372×
            self.load_all_graphs(&mut s).unwrap();
18211372×
            s.materialize().files
18221372×
        };
1823686×
        assert_eq!(files(a), files(b), "the same files");
1824686×
    }
1825
1826
    /// The state index file: its heads, a hash of its changes block and one
1827
    /// of the rest, then the body [`State::write_index`] gives, whose first
1828
    /// block is the changes. Hashed in two parts so the log can read and
1829
    /// check the changes alone.
1830
    /// The index of `deps` if there is one, else the newest, which the
1831
    /// caller may bring up to date.
18322002×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1833
        use std::io::Read;
18342002×
        let _t = crate::timing::phase("load: state index");
18352002×
        let exact = self.state_index_path(deps);
18362002×
        let reading = crate::timing::phase("load:   of which reading the file");
18372002×
        let mut f = match fs::File::open(&exact) {
1838270×
            Ok(f) => {
1839
                // Used now: the newest, so the last to be dropped.
1840270×
                let _ = fs::File::options()
1841270×
                    .write(true)
1842270×
                    .open(&exact)
1843270×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1844270×
                f
1845
            }
18461732×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1847
        };
18481610×
        let total = f.metadata().ok()?.len();
18491610×
        let mut word = [0u8; 4];
18501610×
        f.read_exact(&mut word).ok()?;
18511610×
        let n = u32::from_le_bytes(word) as usize;
18521610×
        let mut head = vec![0u8; 32 * n + 64 + 8];
18531610×
        f.read_exact(&mut head).ok()?;
18541610×
        let heads: Vec<ChangeHash> = head[..32 * n]
18551610×
            .chunks_exact(32)
18561610×
            .map(|c| ObjectRef(c.try_into().unwrap()))
18571610×
            .collect();
18581610×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
18591610×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
18601610×
        let at = (4 + head.len()) as u64;
18611610×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
18620×
            return None;
18631610×
        }
1864
        // The front only: the files' histories after it are read, each
1865
        // checked by its own hash, when a command builds that file.
18661610×
        let mut front = vec![0u8; front_len as usize];
18671610×
        f.read_exact(&mut front).ok()?;
18681610×
        drop(reading);
18691610×
        let checking = crate::timing::phase("load:   of which checking the file");
18701610×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
18711610×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
18723220×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
18731610×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
18740×
            return None;
18751610×
        }
18761610×
        drop(checking);
18771610×
        let histories = crate::state::Histories::File(
18781610×
            std::sync::Arc::new(f),
18791610×
            at + front_len,
18801610×
            total - at - front_len,
18811610×
        );
18821610×
        Some((State::read_index_front(&front, histories).ok()?, heads))
18832002×
    }
1884
1885
    /// The changes of this workspace's state index (the closure of its
1886
    /// heads), read without the rest of the index.
1887
    #[allow(clippy::type_complexity)]
1888177×
    pub(crate) fn read_state_index_changes(
1889177×
        &self,
1890177×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1891
        use std::io::Read;
1892177×
        let _t = crate::timing::phase("load: state index changes");
1893177×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1894160×
        let mut word = [0u8; 4];
1895160×
        f.read_exact(&mut word).ok()?;
1896160×
        let n = u32::from_le_bytes(word) as usize;
1897
        // Heads, the two sums, the front's length, then the changes block.
1898160×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1899160×
        f.read_exact(&mut head).ok()?;
1900160×
        let heads: Vec<ChangeHash> = head[..32 * n]
1901160×
            .chunks_exact(32)
1902160×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1903160×
            .collect();
1904160×
        let sum = &head[32 * n..32 * n + 32];
1905160×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1906160×
        let mut changes = vec![0u8; 4 + len];
1907160×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1908160×
        f.read_exact(&mut changes[4..]).ok()?;
1909160×
        let checking = crate::timing::phase("load:   of which checking");
1910160×
        let mut h = blake3::Hasher::new();
1911160×
        h.update_rayon(&changes);
1912160×
        if h.finalize().as_bytes() != sum {
19130×
            return None;
1914160×
        }
1915160×
        drop(checking);
1916160×
        let _decoding = crate::timing::phase("load:   of which decoding");
1917160×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
1918177×
    }
1919
1920
    /// Save `st`, the history-only state of `deps`, as this workspace's
1921
    /// state index; quietly nothing when it cannot be (it is only a cache).
1922399×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1923399×
        let _t = crate::timing::phase("write: state index");
1924399×
        let encoding = crate::timing::phase("write:   of which encoding");
1925399×
        let Some(body) = st.write_index() else {
19260×
            return;
1927
        };
1928399×
        drop(encoding);
1929
        #[cfg(test)]
1930212×
        assert_eq!(
1931212×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1932212×
            Some(body.clone()),
1933
            "a state index reads back as written"
1934
        );
1935399×
        let mut heads = st.maximal(deps);
1936399×
        heads.sort();
1937399×
        let mut w = crate::flat::Writer::default();
1938399×
        w.count(heads.len());
1939399×
        for h in &heads {
194017×
            w.object(h);
194117×
        }
1942
        // The body is the front's length, the front, then the files'
1943
        // histories, which carry their own hashes: the sums cover the
1944
        // front's changes block and the rest of the front.
1945399×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
1946399×
        let front = &body[8..8 + front_len];
1947399×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
1948798×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1949399×
        w.fixed(&sum(&front[..split]));
1950399×
        w.fixed(&sum(&front[split..]));
1951399×
        w.fixed(&body);
1952399×
        let path = self.state_index_path(&heads);
1953399×
        let _ = fs::create_dir_all(self.oxy.join("index"));
1954399×
        let _ = write_cache(&path, &w.0);
1955
        // The last two used: the index of a state moved away from stays for
1956
        // a move back. Older ones (and the unnamed one of before) go.
1957399×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
19581×
            let _ = fs::remove_file(old);
19591×
        }
1960399×
        let _ = fs::remove_file(
1961399×
            self.oxy
1962399×
                .join("index")
1963399×
                .join(format!("state-{}", self.workspace.to_hex())),
1964399×
        );
1965399×
    }
1966
19676×
    fn locks_dir(&self) -> PathBuf {
19686×
        self.oxy.join("locks")
19696×
    }
1970
1971
    /// Whether `path` is locked locally for editing (spec §18, advisory).
19723×
    pub fn is_locked(&self, path: &str) -> bool {
19733×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
19743×
    }
1975
1976
    /// Take the advisory local lock on a `lockable` file and make it writable.
19772×
    pub fn lock_path(&self, path: &str) -> Result<()> {
19782×
        let attrs = self.disk_attributes();
19792×
        if !attrs.lookup(path).lockable {
19801×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
19811×
        }
19821×
        fs::create_dir_all(self.locks_dir())?;
19831×
        write_atomic(
19841×
            &self.locks_dir().join(path.replace('/', "%2F")),
19851×
            std::process::id().to_string().as_bytes(),
19860×
        )?;
19871×
        set_readonly(&self.root.join(path), false)?;
19881×
        Ok(())
19892×
    }
1990
1991
    /// Release the local lock and make the file read-only again.
19921×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
19931×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
19941×
        if self.root.join(path).exists() {
19951×
            set_readonly(&self.root.join(path), true)?;
19960×
        }
19971×
        Ok(())
19981×
    }
1999
2000
    /// Whether a repository path is inside the sparse filter (spec §17).
200124393×
    pub fn in_scope(&self, path: &str) -> bool {
200224393×
        self.config.sparse_paths.is_empty()
200382×
            || self
200482×
                .config
200582×
                .sparse_paths
200682×
                .iter()
200799×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
200824393×
    }
2009
20101×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
20111×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
20121×
    }
2013
2014
    /// Walk the working copy; with a manifest, a file whose size and mtime
2015
    /// match it is not read: an opaque file yields its known blob, and a
2016
    /// text file whose recorded graph key equals its base graph's key in
2017
    /// `keys` (path → key) is marked unchanged; other text files are read
2018
    /// but keep their known hash. Files modified within two seconds of the
2019
    /// manifest are never trusted (a racy stat).
2020
    ///
2021
    /// `.oxyattributes` files are always read, since their content is
2022
    /// needed; and when any of them is not known unchanged (added, removed,
2023
    /// edited, or changed in the base), no text file is taken as unchanged,
2024
    /// because attributes decide how a file compares with the base.
2025
    ///
2026
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2027
    /// (the base state's files) that exists on disk is included even when
2028
    /// an ignore rule matches it, as in Git.
20291284×
    fn walk_working_copy_with(
20301284×
        &self,
20311284×
        cache: Option<&prompt::Manifest>,
20321284×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
20331284×
        keys: Option<&KeyOf>,
20341284×
    ) -> Result<BTreeMap<String, FsEntry>> {
2035
        let mut out: BTreeMap<String, FsEntry>;
20361284×
        let sparse = &self.config.sparse_paths;
20379151×
        let in_scope = |p: &str| {
20389151×
            sparse.is_empty()
20397×
                || sparse
20407×
                    .iter()
20417×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
20429151×
        };
20431284×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2044
        let walk::Listing {
20451284×
            files,
20461284×
            symlinks,
20471284×
            nested,
20481284×
            dirs,
20491284×
        } = match self.listing_cache.take() {
2050167×
            Some(l) => l,
2051
            // Ignore rules apply to untracked paths only, so the base's
2052
            // files are not matched against them (an added file is: a rule
2053
            // written after it was snapshotted leaves it out again).
20549163×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2055
        };
2056
        // A new file larger than the limit is left out and named, not taken
2057
        // in unseen (oxygen#98): a build's output or a downloaded image
2058
        // would otherwise be stored by the next status, kept by the
2059
        // operation log. Files tracked, or already in the working copy, stay.
20601284×
        let limit = self.config.max_new_file;
20611284×
        let mut skipped = Vec::new();
20621284×
        let files: Vec<_> = files
20631284×
            .into_iter()
206412115×
            .filter(|(rel, _, meta)| {
206512115×
                let new = !tracked.contains_key(rel)
20663118×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
206712115×
                if limit > 0 && new && meta.size > limit {
20683×
                    skipped.push((rel.clone(), meta.size));
20693×
                    return false;
207012112×
                }
207112112×
                true
207212115×
            })
20731284×
            .collect();
20741284×
        *self.skipped_large.borrow_mut() = skipped;
20751284×
        let keys = keys.filter(|k| {
207612100×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
20771281×
            let attrs_unchanged =
20781281×
                files
20791281×
                    .iter()
208012081×
                    .filter(|(r, _, _)| is_attributes(r))
20811281×
                    .all(|(rel, _, meta)| {
20829×
                        stat_cached(rel, meta, cache)
20839×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
20849×
                    });
20851281×
            let none_removed = tracked
20861281×
                .keys()
20879092×
                .filter(|r| is_attributes(r))
20881281×
                .all(|r| on_disk.contains(r.as_str()));
20891281×
            attrs_unchanged && none_removed
20901281×
        });
20911284×
        *self.walked_dirs.borrow_mut() =
20921284×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
20931284×
        drop(walk_phase);
20941284×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2095
        // Reading files is most of a walk's cost; do it in parallel.
2096
        {
2097
            use rayon::prelude::*;
20981284×
            let mut read: Vec<(String, FsEntry)> = files
20991284×
                .par_iter()
210012112×
                .map(|(rel, path, meta)| {
2101
                    // A key is worked out only for a file the manifest
2102
                    // knows with the same stat and a key of its own.
210312112×
                    let key = keys
210412112×
                        .filter(|_| !is_attributes(rel))
210512112×
                        .filter(|_| {
210612072×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
210712072×
                        })
210812112×
                        .and_then(|k| k(rel));
210912112×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
211012112×
                })
21111284×
                .collect::<Result<Vec<_>>>()?;
211212110×
            for (rel, e) in read.iter_mut() {
2113
                // A cached blob the store lost (gc, a partial clone): read the file after all.
211412110×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
21150×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
21160×
                    e.blob = None;
211712110×
                }
2118
            }
2119
            // The listing is in path order, so the map is built without
2120
            // searching.
21211283×
            out = read.into_iter().collect();
21221283×
            for (rel, target) in symlinks {
21232×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
21242×
            }
2125
        }
21261283×
        drop(_read_phase);
21271283×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2128
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2129
        // already tracked as subrepo nodes, they contribute their pin;
2130
        // unregistered ones are left alone.
21311283×
        let modules = self.modules_on_disk();
21321283×
        let removed = self.removed_subrepos();
21331283×
        for rel in &removed {
21343×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
21351×
                self.clear_removed_subrepo(rel);
21362×
            }
2137
        }
21381283×
        let mut untracked_nested = Vec::new();
21391283×
        for dir in nested {
214031×
            let rel = self.rel_path(&dir);
214131×
            if !self.in_scope(&rel) || removed.contains(&rel) {
21423×
                continue;
214328×
            }
214428×
            let registered = modules.entries.get(&rel);
214528×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2146
            {
21471×
                untracked_nested.push(rel);
21481×
                continue;
214927×
            }
215027×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
215127×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2152
        }
21531283×
        untracked_nested.sort();
21541283×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2155
        // Tracked paths the ignore rules hid.
21561283×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
215786×
            if !self.in_scope(rel) {
215810×
                continue;
215976×
            }
216076×
            let path = self.root.join(rel);
216176×
            if *kind == NodeKind::Subrepo {
21624×
                if removed.contains(rel) {
21632×
                    continue;
21642×
                }
21652×
                let present =
21662×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
21672×
                if present {
21680×
                    let pin = subrepos::read_pin(
21690×
                        &path,
21700×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
21710×
                    )?;
21720×
                    out.insert(
21730×
                        rel.clone(),
21740×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2175
                    );
21762×
                } else if let Some(b) = blob {
21772×
                    // Not cloned (or emptied): the pin stays as recorded, as a
21782×
                    // Git gitlink does when its directory is absent.
21792×
                    out.insert(
21802×
                        rel.clone(),
21812×
                        FsEntry {
21822×
                            blob: Some(*b),
21832×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
21842×
                        },
21852×
                    );
21862×
                }
21872×
                continue;
218872×
            }
218972×
            let Ok(meta) = fs::symlink_metadata(&path) else {
219072×
                continue;
2191
            };
21920×
            let ft = meta.file_type();
21930×
            if ft.is_symlink() {
21940×
                let target = fs::read_link(&path)?;
21950×
                out.insert(
21960×
                    rel.clone(),
21970×
                    FsEntry::new(
21980×
                        NodeKind::Symlink,
2199
                        false,
22000×
                        target.to_string_lossy().as_bytes().to_vec(),
2201
                    ),
2202
                );
22030×
            } else if ft.is_file() {
22040×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
22050×
                out.insert(rel.clone(), e);
22060×
            }
2207
        }
22081283×
        Ok(out)
22091284×
    }
2210
2211
    /// The entry for one regular file, read or served from the stat cache.
22120×
    fn file_entry(
22130×
        &self,
22140×
        rel: &str,
22150×
        path: &Path,
22160×
        meta: &walk::Stat,
22170×
        cache: Option<&prompt::Manifest>,
22180×
    ) -> Result<FsEntry> {
22190×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
22200×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
22210×
            e.content = std::sync::Arc::new(fs::read(path)?);
22220×
            e.blob = None;
22230×
        }
22240×
        Ok(e)
22250×
    }
2226
2227
    /// The non-directory paths of a snapshot with their kinds, for the
2228
    /// walker's `tracked` set.
22292×
    pub(crate) fn tracked_kinds(
22302×
        snapshot: &Snapshot,
22312×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
22322×
        snapshot
22332×
            .files
22342×
            .iter()
223512×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
22368×
            .map(|(p, f)| {
22378×
                let blob = match &f.content {
22384×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
22394×
                    _ => None,
2240
                };
22418×
                (p.clone(), (f.kind, blob))
22428×
            })
22432×
            .collect()
22442×
    }
2245
2246
    /// A path under the root as a `/`-separated relative string.
224770×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
224870×
        path.strip_prefix(&self.root)
224970×
            .unwrap_or(path)
225070×
            .components()
2251134×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
225270×
            .collect::<Vec<_>>()
225370×
            .join("/")
225470×
    }
2255
}
2256
2257
impl Repo {
2258
    /// Changes reachable from the bookmark and the working copy, newest first.
225995×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
226095×
        let heads = self.bookmark_heads()?;
226195×
        if self.bare {
22621×
            return self.log_state(&heads);
226394×
        }
226494×
        let (wc_hash, wc) = self.working_copy()?;
226594×
        let mut all = heads.clone();
226694×
        all.push(wc_hash);
226794×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
226894×
        let mut entries: Vec<LogEntry> = Vec::new();
2269
        // A shallow clone knows changes beyond its boundary from a
2270
        // checkpoint's metadata only: its log comes from the state.
227194×
        let metas = if self.is_shallow() {
22721×
            self.load_state_history(&all)?
22731×
                .changes()
22749×
                .map(|(h, m)| (*h, m.clone()))
22751×
                .collect()
2276
        } else {
2277
            // The working copy's change is in hand, and is never in the
2278
            // state index: its metadata is not looked up again.
227993×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
228093×
            below.extend(wc.deps.iter().copied());
228193×
            let _t = crate::timing::phase("log: metadata");
228293×
            let mut metas = self.metas_of(&below)?;
2283325×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
228493×
                // First, where the log puts it, so the order may hold.
228593×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
228693×
            }
228793×
            metas
2288
        };
2289427×
        for (h, meta) in metas {
2290427×
            entries.push(LogEntry {
2291427×
                hash: h,
2292427×
                change: meta,
2293427×
                is_working_copy: h == wc_hash,
2294427×
                is_head: head_set.contains(&h),
2295427×
            });
2296427×
        }
229794×
        let _sorting = crate::timing::phase("log: sort");
2298
        // The hash makes the order total, so an unstable sort gives the same.
2299
        // From the state index the order already holds (oxygen#94).
2300784×
        let order = |a: &LogEntry, b: &LogEntry| {
2301784×
            b.is_working_copy
2302784×
                .cmp(&a.is_working_copy)
2303784×
                .then(crate::state::log_order(
2304784×
                    (&a.hash, &a.change.hlc),
2305784×
                    (&b.hash, &b.change.hlc),
2306
                ))
2307784×
        };
2308217×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
230946×
            entries.sort_unstable_by(order);
231048×
        }
231194×
        Ok(entries)
231295×
    }
2313
2314
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2315
    /// count, for paginated views.
23160×
    pub fn log_window(
23170×
        &self,
23180×
        heads: &[ChangeHash],
23190×
        offset: usize,
23200×
        limit: usize,
23210×
    ) -> Result<(Vec<LogEntry>, usize)> {
23220×
        let all = self.log_state(heads)?;
23230×
        let total = all.len();
23240×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
23250×
    }
2326
2327
    /// The log of the state with these heads, newest first, with no working
2328
    /// copy involved (for hosted repositories and any explicit state).
232910×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2330
        // The log needs change metadata only: neither graphs nor the tree.
233110×
        if self.is_shallow() {
23320×
            return Ok(self.log_of(&self.load_state_history(heads)?));
233310×
        }
233410×
        let metas = self.metas_of(heads)?;
233510×
        let depended: BTreeSet<ChangeHash> = metas
233610×
            .iter()
233730×
            .flat_map(|(_, m)| m.deps.iter().copied())
233810×
            .collect();
233910×
        let mut entries: Vec<LogEntry> = metas
234010×
            .into_iter()
234110×
            .map(|(h, meta)| LogEntry {
234230×
                hash: h,
234330×
                is_head: !depended.contains(&h),
234430×
                change: meta,
2345
                is_working_copy: false,
234630×
            })
234710×
            .collect();
234852×
        let order = |a: &LogEntry, b: &LogEntry| {
234952×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
235052×
        };
235113×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
23524×
            entries.sort_unstable_by(order);
23536×
        }
235410×
        Ok(entries)
235510×
    }
2356
2357
    /// Every change of the state with these heads and its metadata, read
2358
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2359
    /// a shallow clone's boundary is left out.
2360177×
    pub fn metas_of(
2361177×
        &self,
2362177×
        heads: &[ChangeHash],
2363177×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2364177×
        let boundary = self.boundary();
2365
        // The state index holds the metadata of its heads' closure: a
2366
        // change found there is not read from the store (a change object
2367
        // can be as large as the tree it adds).
2368177×
        let read = self.read_state_index_changes();
2369
        // Every one of `heads` in the index, and every head of the index
2370
        // among them: their closure is the index's changes, all of them
2371
        // (it is closed), and no walk is needed to find it.
2372177×
        if let Some((index_heads, all)) = &read {
2373160×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2374160×
            let in_index = || {
2375160×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2376160×
                    index_heads.iter().collect();
2377
                // Usually the heads asked are the index's: no set of all.
2378160×
                heads.iter().all(|h| index_heads.contains(h)) || {
2379160×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2380160×
                        all.iter().map(|(h, _)| h).collect();
2381160×
                    heads.iter().all(|h| all.contains(h))
2382
                }
2383160×
            };
2384160×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
23850×
                let (_, all) = read.expect("matched above");
2386
                #[cfg(test)]
2387
                {
2388
                    // The walk the shortcut saves finds the same changes.
23890×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
23900×
                    let mut stack = heads.to_vec();
23910×
                    while let Some(h) = stack.pop() {
23920×
                        if seen.insert(h) {
23930×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
23940×
                        }
2395
                    }
23960×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2397
                }
23980×
                return Ok(all);
2399160×
            }
240017×
        }
2401177×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2402177×
            read.map(|(_, all)| all.into_iter().collect());
2403177×
        let _walk = crate::timing::phase("metadata: walk");
2404177×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2405177×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2406177×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2407177×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
24081277×
        while let Some(h) = stack.pop() {
24091100×
            if !seen.insert(h) {
2410461×
                continue;
2411639×
            }
2412
            // Taken out of the index's map, each once: not copied.
2413639×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2414
                #[cfg(test)]
24150×
                assert_eq!(
2416
                    meta,
24170×
                    self.store.get_change_meta(&h)?,
2418
                    "the state index holds a change's metadata"
2419
                );
24200×
                stack.extend(meta.deps.iter().copied());
24210×
                out.push((h, meta));
24220×
                continue;
2423639×
            }
2424639×
            let started = std::time::Instant::now();
2425639×
            let meta = match self.store.get_change_meta(&h) {
2426639×
                Ok(m) => m,
24270×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
24280×
                Err(e) => return Err(e.into()),
2429
            };
2430639×
            stored += 1;
2431639×
            from_store += started.elapsed();
2432639×
            stack.extend(meta.deps.iter().copied());
2433639×
            out.push((h, meta));
2434
        }
2435177×
        if stored > 0 && crate::timing::enabled() {
24360×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2437177×
        }
2438177×
        Ok(out)
2439177×
    }
2440
2441
    /// The log of a state already loaded, newest first.
2442
    /// The history of lines `first..=last` (1-based) of `path` in the
2443
    /// state `heads` make (spec §27): every change that inserted or
2444
    /// deleted one of their atoms, or an atom deleted from between them,
2445
    /// newest first. Exact, as atoms keep their identity across edits.
24466×
    pub fn line_history(
24476×
        &self,
24486×
        heads: &[ChangeHash],
24496×
        path: &str,
24506×
        first: usize,
24516×
        last: usize,
24526×
    ) -> Result<Vec<LogEntry>> {
24536×
        if first == 0 || last < first {
24541×
            return fail(format!(
2455
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2456
            ));
24575×
        }
24585×
        let mut state = self.load_state_history(heads)?;
24595×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
24601×
            return fail(format!("{path} is not in that state"));
2461
        };
24624×
        self.load_graphs_of(&mut state, &[node])?;
24634×
        let live = state.live_lines(&node);
24644×
        if last > live.len() {
24651×
            return fail(format!(
2466
                "{path} has {} lines; asked for {first},{last}",
24671×
                live.len()
2468
            ));
24693×
        }
24703×
        let Some(g) = state.file(&node) else {
24710×
            return fail(format!("{path} is not a text file"));
2472
        };
24733×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
24743×
        let touched = g.touching(&atoms);
24753×
        Ok(self
24763×
            .log_of(&state)
24773×
            .into_iter()
247813×
            .filter(|e| touched.contains(&e.hash))
24793×
            .collect())
24806×
    }
2481
24828×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
24838×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
24848×
        let mut entries: Vec<LogEntry> = state
24858×
            .changes()
24868×
            .map(|(h, meta)| LogEntry {
248731×
                hash: *h,
248831×
                change: meta.clone(),
2489
                is_working_copy: false,
249031×
                is_head: head_set.contains(h),
249131×
            })
24928×
            .collect();
249334×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
24948×
        entries
24958×
    }
2496
2497
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2498
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2499
    /// (`resolve_change`).
250067×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
250167×
        let view = self.view()?;
250267×
        if let Some(st) = view.bookmarks.get(spec) {
250339×
            return Ok(self.store.get_state(st)?.heads);
250428×
        }
250528×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
25062×
            return Ok(self.store.get_state(&st)?.heads);
250726×
        }
250826×
        if let Some(heads) = self.tag_heads(spec)? {
25092×
            return Ok(heads);
251024×
        }
251124×
        Ok(vec![self.resolve_change(spec)?])
251267×
    }
2513
2514
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2515
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
251636×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
251736×
        if spec == "@" {
25180×
            return Ok(self.working_copy()?.0);
251936×
        }
252036×
        let view = self.view()?;
252136×
        let named = match view.bookmarks.get(spec) {
25221×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
252335×
            None => match remote_bookmark(&view, spec) {
25241×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
252534×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2526
            },
2527
        };
252836×
        if let Some((kind, heads)) = named {
25293×
            return match heads.len() {
25303×
                1 => Ok(heads[0]),
25310×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2532
            };
253333×
        }
253433×
        if spec.is_empty() || spec == "#" {
25350×
            return fail("empty change specifier");
253633×
        }
253733×
        let entries = self.log()?;
2538
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2539
        // cannot be a ChangeId, which has 32 (oxygen#103).
254033×
        let full_hash =
2541128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
254233×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
254327×
            entries
254427×
                .iter()
2545109×
                .filter(|e| e.hash.starts_with_hex(hp))
254627×
                .collect()
2547
        } else {
25486×
            entries
25496×
                .iter()
255021×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
25516×
                .collect()
2552
        };
255333×
        match matches.len() {
255428×
            1 => Ok(matches[0].hash),
25555×
            0 => match self.resolve_in_remotes(spec)? {
25561×
                Some(h) => Ok(h),
25574×
                None => fail(format!("no change matches {spec:?}")),
2558
            },
2559
            _ => {
25600×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
25610×
                if ids.len() == 1 {
25620×
                    fail(format!(
2563
                        "change {spec} is divergent: {} variants",
25640×
                        matches.len()
2565
                    ))
2566
                } else {
25670×
                    fail(format!("{spec:?} is ambiguous"))
2568
                }
2569
            }
2570
        }
257136×
    }
2572
2573
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2574
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2575
    /// `None` when none matches, or more than one.
25765×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
25775×
        let view = self.view()?;
25785×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
25795×
        for bookmarks in view.remotes.values() {
25803×
            for st in bookmarks.values() {
25813×
                let heads = self.store.get_state(st)?.heads;
25827×
                for e in self.log_state(&heads)? {
25837×
                    let hit = match spec.strip_prefix('#') {
25842×
                        Some(hp) => e.hash.starts_with_hex(hp),
25855×
                        None => e.change.change_id.starts_with_hex(spec),
2586
                    };
25877×
                    if hit {
25881×
                        found.insert(e.hash);
25896×
                    }
2590
                }
2591
            }
2592
        }
25935×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
25945×
    }
2595
2596
    /// Where a change is when no local bookmark or the working copy holds
2597
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2598
    /// it is held locally, or nowhere.
25993×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
26006×
        if self.log()?.iter().any(|e| e.hash == *hash) {
26012×
            return Ok(None);
26021×
        }
26031×
        let view = self.view()?;
26041×
        for (remote, bookmarks) in &view.remotes {
26051×
            for (name, st) in bookmarks {
26061×
                let heads = self.store.get_state(st)?.heads;
26071×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
26081×
                    return Ok(Some(format!("{remote}/{name}")));
26090×
                }
2610
            }
2611
        }
26120×
        Ok(None)
26133×
    }
2614
2615
    /// Human-readable description of what a change does, with line content.
26163×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
26173×
        let change = self.store.get_change(hash)?;
26183×
        let (base, base_snapshot) = self.change_base(&change)?;
26193×
        Ok(render_change(&change, &base, &base_snapshot))
26203×
    }
2621
2622
    /// The base state of `change` (its dependencies) and its rendering, as
2623
    /// much as showing the change needs: the whole tree, and the graphs and
2624
    /// contents of the files the change edits. Other text files are left
2625
    /// unrendered ([`Snapshot::unrendered`]).
26266×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
26276×
        let base = self.load_state_history(&change.deps)?;
26286×
        self.render_base_for(change, base)
26296×
    }
2630
2631
    /// The base for showing `change` alone: the graphs of the files it
2632
    /// edits built, and the base's tree with no file rendered, which is
2633
    /// all [`render_change`](snapshot::render_change) and
2634
    /// [`diff_files_of`](snapshot::diff_files_of) read.
26353×
    pub(crate) fn tree_base_for(
26363×
        &self,
26373×
        change: &Change,
26383×
        mut base: State,
26393×
    ) -> Result<(State, Snapshot)> {
26403×
        let _t = crate::timing::phase("diff: the base's tree");
26413×
        let edited: std::collections::HashSet<NodeId> =
26428×
            change.edits.iter().map(|e| e.node()).collect();
26433×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
26443×
        self.load_graphs_of(&mut base, &nodes)?;
26453×
        let snapshot = Snapshot {
26463×
            tree: base.tree().view(),
26473×
            files: BTreeMap::new(),
26483×
            unrendered: BTreeSet::new(),
26493×
        };
26503×
        Ok((base, snapshot))
26513×
    }
2652
2653
    /// [`Repo::change_base`] with the base already loaded (the working
2654
    /// copy's comes from the state index).
2655213×
    pub(crate) fn render_base_for(
2656213×
        &self,
2657213×
        change: &Change,
2658213×
        mut base: State,
2659213×
    ) -> Result<(State, Snapshot)> {
2660213×
        let _t = crate::timing::phase("diff: render the base");
2661213×
        let edited: std::collections::HashSet<NodeId> =
2662393×
            change.edits.iter().map(|e| e.node()).collect();
2663213×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2664213×
        self.load_graphs_of(&mut base, &nodes)?;
2665213×
        let snapshot = {
2666213×
            let _t = crate::timing::phase("diff:   of which materialize");
2667213×
            base.materialize_nodes(&edited)
2668
        };
2669213×
        Ok((base, snapshot))
2670213×
    }
2671
}
2672
26730×
fn remove_any(path: &Path) -> std::io::Result<()> {
26740×
    let m = fs::symlink_metadata(path)?;
26750×
    if m.is_dir() {
26760×
        fs::remove_dir_all(path)
2677
    } else {
26780×
        fs::remove_file(path)
2679
    }
26800×
}
2681
26825×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
26835×
    let mut perms = fs::metadata(path)?.permissions();
26845×
    perms.set_readonly(readonly);
26855×
    fs::set_permissions(path, perms)
26865×
}
2687
2688
#[cfg(unix)]
26895871×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2690
    use std::os::unix::fs::PermissionsExt;
26915871×
    let mut perms = fs::metadata(path)?.permissions();
26925871×
    let mode = perms.mode();
26935871×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
26945871×
    if want != mode {
26954×
        perms.set_mode(want);
26964×
        fs::set_permissions(path, perms)?;
26975867×
    }
26985871×
    Ok(())
26995871×
}
2700
#[cfg(not(unix))]
2701
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2702
    Ok(())
2703
}
2704
2705
#[cfg(unix)]
270616368×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2707
    use std::os::unix::fs::PermissionsExt;
270816368×
    m.permissions().mode() & 0o111 != 0
270916368×
}
2710
#[cfg(not(unix))]
2711
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2712
    false
2713
}
2714
271512875×
fn op_ref(k: OpKey) -> OpRef {
271612875×
    OpRef {
271712875×
        change: k.0,
271812875×
        index: k.1,
271912875×
    }
272012875×
}
2721
27226039×
fn split_path(path: &str) -> (&str, &str) {
27236039×
    match path.rfind('/') {
27245061×
        Some(i) => (&path[..i], &path[i + 1..]),
2725978×
        None => ("", path),
2726
    }
27276039×
}
2728
2729
/// Whether `rel` is an attributes file (spec §7.6).
273067489×
fn is_attributes(rel: &str) -> bool {
273167489×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
273267489×
}
2733
2734
/// The manifest entry for `rel` when its size and mtime match it outside
2735
/// the racy window.
273624193×
fn stat_cached<'m>(
273724193×
    rel: &str,
273824193×
    meta: &walk::Stat,
273924193×
    cache: Option<&'m prompt::Manifest>,
274024193×
) -> Option<&'m prompt::ManifestEntry> {
274124193×
    let m = cache?;
274219245×
    let e = m.entries.get(rel)?;
274317892×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
274417892×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
274524193×
}
2746
2747
/// Read one working-copy file, or serve it from the stat cache (spec
2748
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2749
/// an opaque file is not read at all (its stored blob stands in), and a
2750
/// text file the manifest recorded equal to a base graph whose key is
2751
/// `key`, the key the base has now, is not read either: equal keys mean
2752
/// equal renderings, so it still equals the base. Touches no repository
2753
/// state, so the walk runs it in parallel; the caller checks that a cached
2754
/// blob is still in the store.
275512112×
fn read_file_entry(
275612112×
    rel: &str,
275712112×
    path: &Path,
275812112×
    meta: &walk::Stat,
275912112×
    cache: Option<&prompt::Manifest>,
276012112×
    key: Option<[u8; 32]>,
276112112×
) -> Result<FsEntry> {
276212112×
    let exec = meta.exec;
276312112×
    let stat = Some((meta.size, meta.mtime_ns));
276412112×
    let mut e = match stat_cached(rel, meta, cache) {
27654247×
        Some(e) if e.blob.is_some() => FsEntry {
27661×
            blob: e.blob,
27671×
            content_hash: Some(e.hash),
27681×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27691×
        },
27704246×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
27714241×
            content_hash: Some(e.hash),
27724241×
            unchanged: true,
27734241×
            graph_key: e.graph,
27744241×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27754241×
        },
27765×
        Some(e) => FsEntry {
27775×
            content_hash: Some(e.hash),
27785×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2779
        },
27807865×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2781
    };
2782
    // The stat the manifest records: taken before the read, so a file that
2783
    // changes meanwhile is read again next time.
278412111×
    e.stat = stat;
278512111×
    Ok(e)
278612112×
}
2787
2788
/// Two maps side by side in key order: each key of either, with its value
2789
/// in each. Linear, with no lookups, for maps of a whole tree.
27902542×
pub(crate) fn join<'a, A, B>(
27912542×
    a: &'a BTreeMap<String, A>,
27922542×
    b: &'a BTreeMap<String, B>,
27932542×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
27942542×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
279535574×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
27962542×
        (None, None) => None,
27972932×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
27985811×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
279924289×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2800330×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2801302×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2802
            std::cmp::Ordering::Equal => {
280323657×
                let (k, va) = a.next()?;
280423657×
                let (_, vb) = b.next()?;
280523657×
                Some((k, Some(va), Some(vb)))
2806
            }
2807
        },
280835574×
    })
28092542×
}
2810
2811
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2812
/// lookups.
28131284×
pub(crate) fn missing_from<'a, A, B>(
28141284×
    a: &'a BTreeMap<String, A>,
28151284×
    b: &BTreeMap<String, B>,
28161284×
) -> Vec<(&'a String, &'a A)> {
28171284×
    let mut keys = b.keys().peekable();
28181284×
    a.iter()
28199102×
        .filter(|(k, _)| {
282017526×
            while keys.next_if(|kb| *kb < *k).is_some() {}
28219102×
            keys.peek() != Some(k)
28229102×
        })
28231284×
        .collect()
28241284×
}