OXYGENHUB

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

1855 of 2088 lines run, 433 of 703 functions · run #332 on show-stat · 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.
752527×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762527×
    let Some(url) = &config.storage_url else {
772522×
        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×
    )?)
1002527×
}
101
102176×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103176×
    Err(RepoError::Msg(s.into()))
104176×
}
105
106
mod bookmarks;
107
mod checkout;
108
mod checkpoint;
109
mod config;
110
mod doctor;
111
mod fsck;
112
mod gc;
113
mod git;
114
mod history;
115
mod hooks;
116
mod hosted;
117
mod identity;
118
mod inspect;
119
mod keyless;
120
mod ops;
121
mod policy;
122
mod prompt;
123
mod receipts;
124
mod revset;
125
mod snapshot;
126
pub mod strata;
127
mod subrepos;
128
mod sync;
129
mod tags;
130
#[cfg(test)]
131
mod tests;
132
mod touched;
133
mod transparency;
134
mod walk;
135
mod workspace;
136
137
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
138
pub use checkout::CheckoutReport;
139
pub use config::{parse_size, read_config_file, Config};
140
pub use doctor::{Check, DoctorReport, Health};
141
pub use fsck::{FsckReport, Problem, Severity};
142
pub use gc::GcReport;
143
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
144
pub use hooks::{json_array, json_str, HookOutcome};
145
pub use hosted::FileEdit;
146
pub use identity::{Rotation, SignatureStatus};
147
pub use inspect::{BisectStep, BlameLine, Description};
148
pub use keyless::home_key;
149
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
150
pub use policy::PolicyUpdate;
151
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
152
pub use receipts::ReceiptInfo;
153
pub use revset::{Revset, REVSET_BUDGET};
154
pub use snapshot::{
155
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
156
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
157
    Selection, SnapshotResult,
158
};
159
pub use subrepos::{SubrepoInfo, SubrepoSync};
160
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT};
161
pub use tags::TagInfo;
162
pub use transparency::LogAudit;
163
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
164
165
/// The file name under which per-bookmark or per-tag data is kept: `/`
166
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
167
/// than a directory that would clash with it.
1684201×
pub(crate) fn name_file(name: &str) -> String {
1694201×
    name.replace('%', "%25").replace('/', "%2F")
1704201×
}
171
172
/// The name a [`name_file`] file name stands for.
17343×
pub(crate) fn file_name_to_name(file: &str) -> String {
17443×
    file.replace("%2F", "/").replace("%25", "%")
17543×
}
176
1777377×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1787377×
    Ok(crate::durable::write_atomic(path, data)?)
1797377×
}
180
181
/// Replace a cache file: whole or not at all, but without waiting for the
182
/// disk. A cache checks its own bytes when read, so one a crash leaves
183
/// short or stale is rebuilt rather than trusted.
184
/// How many changes a state index may fall behind its working copy before
185
/// it is written again; until then each load replays them.
186
const INDEX_REPLAY_LIMIT: usize = 16;
187
/// The changes whose encodings are kept for building graphs: a batch of
188
/// files often takes inline text from a few changes in turn.
189
const CHANGE_CACHE_COUNT: usize = 4;
190
const CHANGE_CACHE_BYTES: usize = 512 << 20;
191
/// How many state indexes a workspace keeps.
192
const STATE_INDEXES_KEPT: usize = 2;
193
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
194
1952950×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1962950×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1972950×
    fs::write(&tmp, data)?;
1982950×
    fs::rename(&tmp, path)?;
1992950×
    Ok(())
2002950×
}
201
202
pub struct LogEntry {
203
    pub hash: ChangeHash,
204
    /// Metadata from the state; the full change may be absent in a shallow repository.
205
    pub change: crate::state::ChangeMeta,
206
    pub is_working_copy: bool,
207
    pub is_head: bool,
208
}
209
210
/// A text file's base graph key, by path, as a walk asks for it.
211
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
212
213
/// A file as found on disk or in an imported tree.
214
#[derive(Clone)]
215
pub(crate) struct FsEntry {
216
    pub kind: NodeKind,
217
    pub exec: bool,
218
    /// File content, or a symlink's target. Empty when `blob` is set.
219
    /// Shared, so a new file's insert holds it without a copy.
220
    pub content: std::sync::Arc<Vec<u8>>,
221
    /// The stored blob of an opaque file whose size and mtime are unchanged
222
    /// since the last manifest (spec §12.3 stat cache); the content was not
223
    /// read.
224
    pub blob: Option<ObjectRef>,
225
    /// BLAKE3 of the content, carried over from the manifest when the stat
226
    /// is unchanged, so the manifest can be rewritten without rehashing.
227
    pub content_hash: Option<[u8; 32]>,
228
    /// A text file known equal to the base's rendering without reading it:
229
    /// its stat matches the manifest and the manifest recorded it equal to
230
    /// a base file graph with the same key (spec §12.3). `content` is empty.
231
    pub unchanged: bool,
232
    /// The base graph key this file equals, for the next manifest.
233
    pub graph_key: Option<[u8; 32]>,
234
    /// Size and mtime already known to be current (a checkout leaving the
235
    /// file as it was), so the manifest need not stat it again.
236
    pub stat: Option<(u64, u128)>,
237
}
238
239
impl FsEntry {
24022803×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
24122803×
        FsEntry {
24222803×
            kind,
24322803×
            exec,
24422803×
            content: std::sync::Arc::new(content),
24522803×
            blob: None,
24622803×
            content_hash: None,
24722803×
            unchanged: false,
24822803×
            graph_key: None,
24922803×
            stat: None,
25022803×
        }
25122803×
    }
252
}
253
254
pub struct Repo {
255
    /// The key a host accepts certified updates with (spec §14.7): when
256
    /// set, accepting a reference update signed by a short-lived key also
257
    /// records the host's acceptance and its time.
258
    pub(crate) acceptor: Option<std::sync::Arc<(Identity, crate::identity::SecretKey)>>,
259
    /// With `author.signer = keyless`, the fresh key the hub last
260
    /// certified and when its certificate ends (spec §14.7): kept in memory
261
    /// only, for one command.
262
    pub(crate) keyless_key: std::cell::RefCell<Option<(KeyId, crate::identity::SecretKey, u64)>>,
263
    /// Oxygen-pinned subrepos skipped by the running Git export.
264
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
265
    /// The manifest as last read, with the file identity it was read from,
266
    /// so one command parses it once (see `read_manifest`).
267
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
268
    /// A listing of the working copy left by a failed clean check, for the
269
    /// snapshot that follows it to reuse; taken by the next walk and
270
    /// dropped whenever the manifest is written.
271
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
272
    /// The nested repositories the last walk left out, being neither
273
    /// registered nor tracked subrepos (oxygen#43).
274
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
275
    /// New untracked files the last walk left out for their size, with
276
    /// their sizes (oxygen#98).
277
    pub(crate) skipped_large: std::cell::RefCell<Vec<(String, u64)>>,
278
    root: PathBuf,
279
    oxy: PathBuf,
280
    store: Store,
281
    workspace: WorkspaceId,
282
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
283
    bare: bool,
284
    keys_dir: PathBuf,
285
    user_config: PathBuf,
286
    pub config: Config,
287
    /// What the working copy's file system can represent (spec §7.7).
288
    platform: crate::portable::Platform,
289
    /// The encodings of the changes last read for their inline inserts,
290
    /// oldest first.
291
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
292
    /// `--at-op`: read the repository as it was after this operation;
293
    /// recording an operation is refused.
294
    at_op: Option<ObjectRef>,
295
    /// The operation head this handle reads (oxygenhub#249): read once, on
296
    /// first use, and moved only by this handle's own operations or by
297
    /// [`Repo::refresh`], so one command or request never mixes two heads.
298
    head_seen: std::cell::Cell<Option<ObjectRef>>,
299
    /// The directories (with their times) and nested repositories of the
300
    /// last walk, for the manifest written from it.
301
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
302
    /// The directories a manifest check listed, for its restamp only.
303
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
304
}
305
306
/// A walk's directories with their times, and its nested repositories.
307
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
308
309
/// Marker file of a bare repository, inside `.oxy/`.
310
const BARE_MARKER: &str = "bare";
311
/// Marker of a hosted repository that has no id yet: the first push binds
312
/// it to the pusher's id (spec §16.1).
313
const UNBOUND_MARKER: &str = "unbound";
314
315
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
316
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
3177832×
pub fn default_home() -> PathBuf {
3187832×
    if let Ok(h) = std::env::var("OXY_HOME") {
3197826×
        return PathBuf::from(h);
3206×
    }
3216×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3220×
        return PathBuf::from(x).join("oxy");
3236×
    }
324
    // Windows has no HOME as a rule: the roaming profile's application
325
    // data, as Windows programs keep theirs.
326
    #[cfg(windows)]
327
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
328
        return PathBuf::from(d).join("oxy");
329
    }
3306×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3316×
    PathBuf::from(home).join(".config").join("oxy")
3327832×
}
333
3342528×
pub fn default_keys_dir() -> PathBuf {
3352528×
    default_home().join("keys")
3362528×
}
337
3385054×
pub fn default_user_config() -> PathBuf {
3395054×
    default_home().join("config.toml")
3405054×
}
341
342
/// Where `create_identity` records the author.
343
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
344
pub enum IdentityScope {
345
    /// The user file: every repository of this user signs with it.
346
    User,
347
    /// This repository only.
348
    Repo,
349
}
350
351
impl Repo {
352
    // ------------------------------------------------------------ lifecycle
353
354231×
    pub fn init(root: &Path) -> Result<Repo> {
355231×
        let mut id = [0u8; 16];
356231×
        rand::rngs::OsRng.fill_bytes(&mut id);
357231×
        Self::init_with_id(root, id)
358231×
    }
359
360
    /// Initialize a repository with a given repository ID (clones share the
361
    /// ID of their origin, spec §14.4).
362488×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
363488×
        Self::init_on(root, id, None)
364488×
    }
365
366
    /// A new repository with a fresh id, bare or not, on `storage` or in
367
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
36812×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
36912×
        let mut id = [0u8; 16];
37012×
        rand::rngs::OsRng.fill_bytes(&mut id);
37112×
        if bare {
3720×
            Self::init_bare_on(root, id, storage)
373
        } else {
37412×
            Self::init_on(root, id, storage)
375
        }
37612×
    }
377
378
    /// Initialize a repository whose objects and operation head are kept
379
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
380503×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
381503×
        fs::create_dir_all(root)?;
382503×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
383503×
        let oxy = root.join(OXY_DIR);
384503×
        if oxy.exists() {
3851×
            return fail(format!("{} is already an oxy repository", root.display()));
386502×
        }
387502×
        fs::create_dir_all(oxy.join("ops"))?;
388502×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
389502×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
390502×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
391502×
        if let Some(url) = storage {
3923×
            config.set("storage.url", url)?;
393499×
        }
394502×
        config.save(&oxy.join("config"))?;
395502×
        let workspace = WorkspaceId::random();
396502×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
397502×
        let store = open_objects(&oxy, &config)?;
398501×
        let repo = Repo {
399501×
            acceptor: None,
400501×
            keyless_key: Default::default(),
401501×
            last_change: Default::default(),
402501×
            at_op: None,
403501×
            head_seen: Default::default(),
404501×
            walked_dirs: Default::default(),
405501×
            listed_dirs: Default::default(),
406501×
            git_export_skipped: Default::default(),
407501×
            manifest_cache: Default::default(),
408501×
            listing_cache: Default::default(),
409501×
            untracked_nested: Default::default(),
410501×
            skipped_large: Default::default(),
411501×
            root,
412501×
            oxy,
413501×
            store,
414501×
            workspace,
415501×
            bare: false,
416501×
            keys_dir: default_keys_dir(),
417501×
            platform: crate::portable::Platform::current(),
418501×
            user_config: default_user_config(),
419501×
            config,
420501×
        };
421501×
        repo.register_workspace(&workspace, &repo.root)?;
422
423501×
        let wc = repo.new_working_copy(vec![], "");
424501×
        let wc_hash = repo.store.put_change(&wc)?;
425501×
        let mut view = View::default();
426501×
        view.bookmarks.insert(
427501×
            repo.config.bookmark.clone(),
428501×
            repo.store.put_state(&StateObject::new(vec![]))?,
429
        );
430501×
        view.workspaces.insert(workspace, wc_hash);
431501×
        repo.record_op(&[], "oxy init", view)?;
432499×
        Ok(repo)
433503×
    }
434
435
    /// Create a bare repository: an object store, operation log and
436
    /// references with no workspace and no working copy, for hosting
437
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4385×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4395×
        let mut id = [0u8; 16];
4405×
        rand::rngs::OsRng.fill_bytes(&mut id);
4415×
        Self::init_bare_with_id(root, id)
4425×
    }
443
44440×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
44540×
        Self::init_bare_on(root, id, None)
44640×
    }
447
448
    /// [`Repo::init_on`] for a bare repository.
44940×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
45040×
        fs::create_dir_all(root)?;
45140×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
45240×
        let oxy = root.join(OXY_DIR);
45340×
        if oxy.exists() {
4540×
            return fail(format!("{} is already an oxy repository", root.display()));
45540×
        }
45640×
        fs::create_dir_all(oxy.join("ops"))?;
45740×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
45840×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
45940×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
46040×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
46140×
        if let Some(url) = storage {
4620×
            config.set("storage.url", url)?;
46340×
        }
46440×
        config.save(&oxy.join("config"))?;
46540×
        let store = open_objects(&oxy, &config)?;
46640×
        let repo = Repo {
46740×
            acceptor: None,
46840×
            keyless_key: Default::default(),
46940×
            last_change: Default::default(),
47040×
            at_op: None,
47140×
            head_seen: Default::default(),
47240×
            walked_dirs: Default::default(),
47340×
            listed_dirs: Default::default(),
47440×
            git_export_skipped: Default::default(),
47540×
            manifest_cache: Default::default(),
47640×
            listing_cache: Default::default(),
47740×
            untracked_nested: Default::default(),
47840×
            skipped_large: Default::default(),
47940×
            root,
48040×
            oxy,
48140×
            store,
48240×
            workspace: WorkspaceId::ZERO,
48340×
            bare: true,
48440×
            keys_dir: default_keys_dir(),
48540×
            platform: crate::portable::Platform::current(),
48640×
            user_config: default_user_config(),
48740×
            config,
48840×
        };
48940×
        let mut view = View::default();
49040×
        view.bookmarks.insert(
49140×
            repo.config.bookmark.clone(),
49240×
            repo.store.put_state(&StateObject::new(vec![]))?,
493
        );
49440×
        repo.record_op(&[], "oxy init --bare", view)?;
49540×
        Ok(repo)
49640×
    }
497
498
    /// A bare repository with no id yet. Its `id()` is all zero until the
499
    /// first push binds it (`bind_id`), so an existing repository can be
500
    /// pushed to a freshly created hosted one and keep its identity.
50114×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
50214×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
50314×
        fs::remove_file(repo.oxy.join("id"))?;
50414×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
50514×
        Ok(repo)
50614×
    }
507
5083684×
    pub fn is_unbound(&self) -> bool {
5093684×
        self.oxy.join(UNBOUND_MARKER).is_file()
5103684×
    }
511
512
    /// Give an unbound repository its id.
51313×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
51413×
        if !self.is_unbound() {
5150×
            return fail("this repository already has an id");
51613×
        }
51713×
        if id == [0; 16] {
5180×
            return fail("a repository id cannot be all zero");
51913×
        }
52013×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
52113×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
52213×
        Ok(())
52313×
    }
524
525
    /// Whether this repository has no working copy (`init_bare`).
52676×
    pub fn is_bare(&self) -> bool {
52776×
        self.bare
52876×
    }
529
530
    /// Open the repository containing `start` (searching upwards).
5311985×
    pub fn open(start: &Path) -> Result<Repo> {
5321985×
        let start = start.canonicalize()?;
5331985×
        let mut dir: Option<&Path> = Some(&start);
5341985×
        while let Some(d) = dir {
5351985×
            let oxy = d.join(OXY_DIR);
5361985×
            if oxy.is_file() {
537
                // A secondary workspace (spec §12.2): the file points at the repository.
5389×
                let text = fs::read_to_string(&oxy)?;
5399×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5400×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
541
                };
5429×
                let format = fs::read_to_string(shared.join("format"))?;
5439×
                if format != FORMAT_LINE {
5440×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5459×
                }
5469×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5479×
                let store = open_objects(&shared, &config)?;
5489×
                let mut repo = Repo {
5499×
                    acceptor: None,
5509×
                    keyless_key: Default::default(),
5519×
                    last_change: Default::default(),
5529×
                    at_op: None,
5539×
                    head_seen: Default::default(),
5549×
                    walked_dirs: Default::default(),
5559×
                    listed_dirs: Default::default(),
5569×
                    git_export_skipped: Default::default(),
5579×
                    manifest_cache: Default::default(),
5589×
                    listing_cache: Default::default(),
5599×
                    untracked_nested: Default::default(),
5609×
                    skipped_large: Default::default(),
5619×
                    root: d.to_path_buf(),
5629×
                    oxy: shared,
5639×
                    store,
5649×
                    workspace,
5659×
                    bare: false,
5669×
                    keys_dir: default_keys_dir(),
5679×
                    platform: crate::portable::Platform::current(),
5689×
                    user_config: default_user_config(),
5699×
                    config,
5709×
                };
5719×
                repo.apply_workspace_bookmark();
5729×
                return Ok(repo);
5731976×
            }
5741976×
            if oxy.is_dir() {
5751976×
                let format = fs::read_to_string(oxy.join("format"))?;
5761976×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5771976×
                let bare = oxy.join(BARE_MARKER).is_file();
5781976×
                let workspace = if bare {
579148×
                    WorkspaceId::ZERO
580
                } else {
5811828×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5821828×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
583
                };
5841976×
                let store = open_objects(&oxy, &config)?;
5851976×
                let mut repo = Repo {
5861976×
                    acceptor: None,
5871976×
                    keyless_key: Default::default(),
5881976×
                    last_change: Default::default(),
5891976×
                    at_op: None,
5901976×
                    head_seen: Default::default(),
5911976×
                    walked_dirs: Default::default(),
5921976×
                    listed_dirs: Default::default(),
5931976×
                    git_export_skipped: Default::default(),
5941976×
                    manifest_cache: Default::default(),
5951976×
                    listing_cache: Default::default(),
5961976×
                    untracked_nested: Default::default(),
5971976×
                    skipped_large: Default::default(),
5981976×
                    root: d.to_path_buf(),
5991976×
                    oxy,
6001976×
                    store,
6011976×
                    workspace,
6021976×
                    bare,
6031976×
                    keys_dir: default_keys_dir(),
6041976×
                    platform: crate::portable::Platform::current(),
6051976×
                    user_config: default_user_config(),
6061976×
                    config,
6071976×
                };
6081976×
                if !bare {
6091828×
                    repo.apply_workspace_bookmark();
6101828×
                }
6111976×
                if format == FORMAT1_LINE {
6121×
                    repo.migrate_format1()?;
6131975×
                } else if format != FORMAT_LINE {
6140×
                    return fail(format!("unsupported repository format: {}", format.trim()));
6151975×
                }
6161976×
                return Ok(repo);
6170×
            }
6180×
            dir = d.parent();
619
        }
6200×
        fail(format!(
621
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
6220×
            start.display()
623
        ))
6241985×
    }
625
626
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
627
    /// into format 2, where each bookmark names a `state` object.
6281×
    fn migrate_format1(&self) -> Result<()> {
6291×
        let (head, version) = self.read_head()?;
630
        // Collect the chain root-first.
6311×
        let mut chain: Vec<Format1Op> = Vec::new();
6321×
        let mut cur = Some(head);
6333×
        while let Some(r) = cur {
6342×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
6352×
            cur = op.parents.first().copied();
6362×
            chain.push(op);
637
        }
6381×
        chain.reverse();
6391×
        let mut new_parent: Option<ObjectRef> = None;
6402×
        for old in chain {
6412×
            let mut view = View::default();
6422×
            for (name, heads) in &old.view.bookmarks {
6432×
                view.bookmarks.insert(
6442×
                    name.clone(),
6452×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
646
                );
647
            }
6482×
            view.workspaces = old.view.workspaces.clone();
6492×
            let op = Op {
6502×
                parents: new_parent.into_iter().collect(),
6512×
                hlc: old.hlc,
6522×
                command: old.command,
6532×
                view,
6542×
                workspace: None,
6552×
                undoes: None,
6562×
            };
6572×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
658
        }
6591×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6600×
            return fail("the operation log changed while it was rewritten; run the command again");
6611×
        }
6621×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6631×
        Ok(())
6641×
    }
665
666
    /// Pack automatically once many loose objects have accumulated, and
667
    /// delete what packing retired over [`crate::store::RETIRED_FOR`] ago
668
    /// (a store nobody runs `oxy gc` on would keep both copies forever).
669681×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
670681×
        self.store
671681×
            .expire_retired(crate::store::RETIRED_FOR, &mut |_| {})?;
672681×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6730×
            self.store.pack_loose()?;
6740×
            self.store.merge_packs()?;
675681×
        }
676681×
        Ok(())
677681×
    }
678
679
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6803389×
    pub fn id(&self) -> Result<[u8; 16]> {
6813389×
        if self.is_unbound() {
68219×
            return Ok([0; 16]);
6833370×
        }
6843370×
        let path = self.oxy.join("id");
6853370×
        match fs::read_to_string(&path) {
6863370×
            Ok(h) => hex::decode(h.trim())
6873370×
                .ok()
6883370×
                .and_then(|v| v.try_into().ok())
6893370×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6900×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6910×
                let mut id = [0u8; 16];
6920×
                rand::rngs::OsRng.fill_bytes(&mut id);
6930×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6940×
                Ok(id)
695
            }
6960×
            Err(e) => Err(e.into()),
697
        }
6983389×
    }
699
70062×
    pub fn root(&self) -> &Path {
70162×
        &self.root
70262×
    }
703545×
    pub fn store(&self) -> &Store {
704545×
        &self.store
705545×
    }
70610×
    pub fn workspace(&self) -> WorkspaceId {
70710×
        self.workspace
70810×
    }
709
710
    /// Use a different user directory for keys and the user config file
711
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
712
    /// Act as if the working copy were on another platform's file system
713
    /// (tests of Windows and macOS behaviour on any host).
714
    /// Accept certified updates as `identity` (a host's key), recording when
715
    /// (spec §14.7).
7161×
    pub fn with_acceptor(mut self, identity: Identity, sk: crate::identity::SecretKey) -> Repo {
7171×
        self.acceptor = Some(std::sync::Arc::new((identity, sk)));
7181×
        self
7191×
    }
720
7212×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
7222×
        self.platform = platform;
7232×
        self
7242×
    }
725
7260×
    pub fn platform(&self) -> crate::portable::Platform {
7270×
        self.platform
7280×
    }
729
730177×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
731177×
        let dir = dir.into();
732177×
        self.keys_dir = dir.join("keys");
733177×
        self.user_config = dir.join("config.toml");
734177×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
735177×
            self.config = c;
736177×
        }
737177×
        self.apply_workspace_bookmark();
738177×
        self
739177×
    }
740
741
    /// The workspace's current bookmark (spec §10.1) overrides the
742
    /// configured default when `oxy bookmark switch` has recorded one.
7432014×
    fn apply_workspace_bookmark(&mut self) {
7442014×
        if let Ok(b) = fs::read_to_string(
7452014×
            self.oxy
7462014×
                .join("workspaces")
7472014×
                .join(self.workspace.to_hex())
7482014×
                .join("bookmark"),
7492014×
        ) {
75035×
            let b = b.trim();
75135×
            if !b.is_empty() {
75235×
                self.config.bookmark = b.to_string();
75335×
            }
7541979×
        }
7552014×
    }
756
7572×
    pub fn user_config_path(&self) -> &Path {
7582×
        &self.user_config
7592×
    }
760
761
    /// Set a key in the user file and refresh the effective configuration.
76222×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
76322×
        Config::set_user(&self.user_config, key, value)?;
76421×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
76521×
        Ok(())
76622×
    }
767
768378×
    pub fn save_config(&self) -> Result<()> {
769378×
        self.config.save(&self.oxy.join("config"))
770378×
    }
771
7724447×
    fn author(&self) -> KeyId {
7734447×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7744447×
    }
775
}
776
777
impl Repo {
7781699×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7791699×
        let mut c = Change {
7801699×
            version: crate::objects::CHANGE_VERSION,
7811699×
            change_id: ChangeId::random(),
7821699×
            deps,
7831699×
            author: self.author(),
7841699×
            hlc: Hlc::now(),
7851699×
            message: message.into(),
7861699×
            tree_ops: vec![],
7871699×
            edits: vec![],
7881699×
            kind: ChangeKind::WorkingCopy,
7891699×
        };
7901699×
        c.normalize();
7911699×
        c
7921699×
    }
793
794
    // ------------------------------------------------------------ operation log
795
79614427×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
79714427×
        if let Some(r) = self.at_op {
7985×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
79914422×
        }
80014422×
        let r = self.head_ref()?;
80114420×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
80214420×
        Ok((r, op))
80314427×
    }
804
80510008×
    pub fn view(&self) -> Result<View> {
80610008×
        Ok(self.head_op()?.1.view)
80710008×
    }
808
8093522×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
8103522×
        self.record_op_undoing(parents, command, view, None)
8113522×
    }
812
813
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
8143525×
    fn record_op_undoing(
8153525×
        &self,
8163525×
        parents: &[ObjectRef],
8173525×
        command: &str,
8183525×
        view: View,
8193525×
        undoes: Option<ObjectRef>,
8203525×
    ) -> Result<ObjectRef> {
8213525×
        if self.at_op.is_some() {
8221×
            return fail(
823
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
824
            );
8253524×
        }
8263524×
        let op = Op {
8273524×
            parents: parents.to_vec(),
8283524×
            hlc: Hlc::now(),
8293524×
            command: command.into(),
8303524×
            view,
8313524×
            workspace: Some(self.workspace),
8323524×
            undoes,
8333524×
        };
8343524×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
835
        // The head is the commit point: everything it names must be on disk first.
8363522×
        let flushing = crate::timing::phase("op: flush the store");
8373522×
        self.store.flush()?;
8383520×
        drop(flushing);
839
        // Compare and swap (spec §12.1): when another process recorded an
840
        // operation since this one read the head, the two are merged
841
        // instead of one overwriting the other. On this disk the head moves
842
        // under a short lock; on any other store by its record's version,
843
        // and a record that moved meanwhile is read again and merged again.
8443520×
        let _lock = if self.store.is_local() {
8453508×
            Some(self.lock_ops()?)
846
        } else {
84712×
            None
848
        };
8493520×
        let Some(parent) = parents.first() else {
850
            // The first operation (init): there is no head yet.
851541×
            if !self.swap_head(&r, None)? {
8522×
                return fail(format!(
853
                    "{} already holds a repository's operation log",
8542×
                    self.store.backend().describe()
855
                ));
856539×
            }
857539×
            return Ok(r);
858
        };
8592979×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8602979×
        for _ in 0..HEAD_TRIES {
8612979×
            let (current, version) = self.read_head()?;
8622979×
            let to = if current == *parent {
8632955×
                r
864
            } else {
86524×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
86623×
                let merged = Op {
86724×
                    parents: vec![current, r],
86824×
                    hlc: Hlc::now(),
86924×
                    command: format!("{command} (merged with a concurrent operation)"),
87024×
                    view: self.merge_views(&base, &op.view, &theirs)?,
87123×
                    workspace: Some(self.workspace),
87223×
                    undoes: None,
873
                };
87423×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
87523×
                self.store.flush()?;
87623×
                m
877
            };
8782978×
            if self.swap_head(&to, version.as_ref())? {
8792972×
                return Ok(to);
8800×
            }
881
        }
8820×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8833525×
    }
884
885
    /// The operation head's lock, held only while the head pointer moves.
8863518×
    fn lock_ops(&self) -> Result<FileLock> {
8873518×
        fs::create_dir_all(self.oxy.join("ops"))?;
8883518×
        FileLock::acquire(
8893518×
            self.oxy.join("ops").join("lock"),
8903518×
            "another oxy process holds the operation log",
891
        )
8923518×
    }
893
894
    /// The operation head this handle reads: the one it first read, or
895
    /// the last one it moved the head to (see [`Repo::refresh`]).
89614424×
    fn head_ref(&self) -> Result<ObjectRef> {
89714424×
        if let Some(r) = self.head_seen.get() {
89811150×
            return Ok(r);
8993274×
        }
9003274×
        let r = self.read_head()?.0;
9013272×
        self.head_seen.set(Some(r));
9023272×
        Ok(r)
90314424×
    }
904
905
    /// Read the operation head again: what another process or handle
906
    /// recorded since this handle first read it becomes visible. A handle
907
    /// keeps the head it first read for the rest of its life otherwise,
908
    /// so whatever it reads comes from one view (oxygenhub#249); a loop
909
    /// that waits for others' operations, or a step that must see what
910
    /// another handle just recorded, refreshes. Packs written since are
911
    /// picked up too.
912455×
    pub fn refresh(&self) -> Result<()> {
913455×
        self.forget_head();
914455×
        self.store.refresh()?;
915455×
        Ok(())
916455×
    }
917
918
    /// Read the operation head again on next use, as [`Repo::refresh`]
919
    /// does, leaving the packs as they are.
9202170×
    pub(crate) fn forget_head(&self) {
9212170×
        self.head_seen.set(None);
9222170×
    }
923
924
    /// The operation head, and on a store its record's version for
925
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
926
    /// any other store (a bucket, or memory in tests) it is the store's
927
    /// [`HEAD_RECORD`] reference record (oxygen#68).
9286342×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
9296342×
        if self.store.is_local() {
9306324×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
9316324×
            let r = ObjectRef::from_hex(hex.trim())
9326324×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
9336321×
            return Ok((r, None));
93418×
        }
93518×
        let backend = self.store.backend();
93618×
        match backend.read_ref(HEAD_RECORD) {
93718×
            Ok(Some((bytes, version))) => {
93818×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
9390×
                    || {
9400×
                        RepoError::Msg(format!(
9410×
                            "the operation head in {} is corrupt",
9420×
                            backend.describe()
9430×
                        ))
9440×
                    },
9450×
                )?;
94618×
                Ok((r, Some(version)))
947
            }
9480×
            Ok(None) => fail(format!(
949
                "{} holds no operation log (no {HEAD_RECORD} record)",
9500×
                backend.describe()
951
            )),
9520×
            Err(e) => fail(format!("read the operation head: {e}")),
953
        }
9546342×
    }
955
956
    /// Move the operation head to `to` from the `expected` version
957
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
958
    /// disk the caller holds the operations lock and the head always
959
    /// moves; on a store it moves only if the record is unchanged, and
960
    /// `false` says another process moved it first.
9613532×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
9623532×
        if self.store.is_local() {
9633518×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
9643512×
            self.head_seen.set(Some(*to));
9653512×
            return Ok(true);
96614×
        }
96714×
        match self
96814×
            .store
96914×
            .backend()
97014×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
971
        {
972
            Ok(_) => {
97311×
                self.head_seen.set(Some(*to));
97411×
                Ok(true)
975
            }
9763×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
9770×
            Err(e) => fail(format!("move the operation head: {e}")),
978
        }
9793532×
    }
980
981
    /// Three-way merge of two views that both started from `base` (spec
982
    /// §12.1). A reference only one side changed takes that side's value.
983
    /// When both changed it differently: a bookmark keeps both sides'
984
    /// heads (it may then have several), a change beats a deletion, a
985
    /// workspace changed by both is an error (only one of them matches the
986
    /// files on disk), and otherwise this process's value wins for remote
987
    /// references and the policy, the first value for a tag (tags never
988
    /// move).
98924×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
99086×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
99186×
            b: &BTreeMap<K, V>,
99286×
            o: &BTreeMap<K, V>,
99386×
            t: &BTreeMap<K, V>,
99486×
            mut both: impl FnMut(&V, &V) -> Result<V>,
99586×
        ) -> Result<BTreeMap<K, V>> {
99686×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
99786×
            let mut out = BTreeMap::new();
99889×
            for k in keys {
99989×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
100089×
                let v = if ov == tv || tv == bv {
100145×
                    ov.cloned()
100244×
                } else if ov == bv {
100327×
                    tv.cloned()
1004
                } else {
100517×
                    match (ov, tv) {
100617×
                        (Some(x), Some(y)) => Some(both(x, y)?),
10070×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
10080×
                        (None, None) => None,
1009
                    }
1010
                };
101188×
                if let Some(v) = v {
101288×
                    out.insert(k.clone(), v);
101388×
                }
1014
            }
101585×
            Ok(out)
101686×
        }
101724×
        let bookmarks = pick(
101824×
            &base.bookmarks,
101924×
            &ours.bookmarks,
102024×
            &theirs.bookmarks,
102116×
            |x, y| {
102216×
                let mut heads = self.store.get_state(x)?.heads;
102316×
                heads.extend(self.store.get_state(y)?.heads);
102416×
                let heads = self.load_state(&heads)?.maximal(&heads);
102516×
                Ok(self.store.put_state(&StateObject::new(heads))?)
102616×
            },
10270×
        )?;
1028
        // Two operations that both replaced one workspace's working copy
1029
        // cannot both be right: the files on disk match only one of them.
1030
        // The working-copy lock keeps this from happening; should it happen
1031
        // anyway, this operation is not recorded.
103224×
        let workspaces = pick(
103324×
            &base.workspaces,
103424×
            &ours.workspaces,
103524×
            &theirs.workspaces,
10361×
            |_, _| {
10371×
                fail(
1038
                    "another oxy process changed this working copy at the same time; \
1039
                     this command was not recorded: check `oxy status` and run it again",
1040
                )
10411×
            },
10421×
        )?;
104323×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
104423×
        let empty = BTreeMap::new();
104523×
        let names: BTreeSet<&String> = base
104623×
            .remotes
104723×
            .keys()
104823×
            .chain(ours.remotes.keys())
104923×
            .chain(theirs.remotes.keys())
105023×
            .collect();
105123×
        let mut remotes = BTreeMap::new();
105223×
        for n in names {
105315×
            let m = pick(
105415×
                base.remotes.get(n).unwrap_or(&empty),
105515×
                ours.remotes.get(n).unwrap_or(&empty),
105615×
                theirs.remotes.get(n).unwrap_or(&empty),
10570×
                |x, _| Ok(*x),
10580×
            )?;
105915×
            if !m.is_empty() {
106015×
                remotes.insert(n.clone(), m);
106115×
            }
1062
        }
106323×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
106423×
            ours.policy
10650×
        } else if ours.policy == base.policy {
10660×
            theirs.policy
1067
        } else {
10680×
            ours.policy.or(theirs.policy)
1069
        };
107023×
        self.store.flush()?;
107123×
        Ok(View {
107223×
            bookmarks,
107323×
            workspaces,
107423×
            remotes,
107523×
            policy,
107623×
            tags,
107723×
        })
107824×
    }
1079
108053×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
108153×
        let mut out = Vec::new();
108253×
        let (mut r, mut op) = self.head_op()?;
1083
        loop {
1084285×
            let next = op.parents.first().copied();
1085285×
            out.push((r, op));
1086285×
            match next {
1087232×
                Some(p) => {
1088232×
                    r = p;
1089232×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1090
                }
109153×
                None => break,
1092
            }
1093
        }
109453×
        Ok(out)
109553×
    }
1096
1097
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1098
    ///
1099
    /// The command undone is the newest one this workspace ran: operations
1100
    /// that only recorded a working-copy snapshot are skipped (the files are
1101
    /// still on disk and the next snapshot recreates them), as are pushes
1102
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1103
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1104
    /// operations are never undone, and a command an earlier undo already
1105
    /// reverted is passed over, so undoing again goes further back.
1106
    ///
1107
    /// When nothing newer came from another workspace, the operation head
1108
    /// moves back to before the command. Otherwise the command is reverted
1109
    /// in place: every reference it changed goes back to its value before
1110
    /// it, recorded as a new operation that names it, and anything another
1111
    /// workspace changed since is kept. A reference both the command and a
1112
    /// later operation of another workspace changed is not guessed at: the
1113
    /// undo is refused, naming it.
1114
    ///
1115
    /// When the working copy is clean and was clean after the command's
1116
    /// predecessor, its files follow too, since nothing on disk can be
1117
    /// lost; otherwise they stay as they are (an undone commit's edits come
1118
    /// back as uncommitted work).
111916×
    pub fn undo(&self) -> Result<Undone> {
112016×
        let _wc = self.lock_working_copy()?;
112116×
        let clean_now =
112216×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
112316×
        let (head_ref, head) = self.head_op()?;
112416×
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
112540×
        let load = |r: &ObjectRef| -> Result<Op> {
112640×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
112740×
        };
112816×
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
112916×
        let mut pending_checkout: Option<Op> = None;
113016×
        let mut others = 0usize;
113116×
        let (mut r, mut op) = (head_ref, head.clone());
113215×
        let (target_ref, target, parent) = loop {
113341×
            let parent = match op.parents.first() {
113440×
                Some(p) => Some((*p, load(p)?)),
11351×
                None => None,
1136
            };
113741×
            if skip.contains(&r) {
11381×
                pending_checkout = None;
113940×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
114010×
                // A push cannot be taken back: undoing it would only make
114110×
                // this repository forget what the remote holds.
114230×
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
114310×
                others += 1;
114420×
            } else if let Some(u) = op.undoes {
11451×
                skip.insert(u);
11461×
                pending_checkout = None;
114719×
            } else if op.command.ends_with(" (checkout)") {
11483×
                pending_checkout = Some(op.clone());
11493×
            } else {
115016×
                match parent {
115115×
                    Some((_, p)) => break (r, op, p),
11521×
                    None => return fail("nothing to undo in this workspace"),
1153
                }
1154
            }
115525×
            match parent {
115625×
                Some((pr, p)) => (r, op) = (pr, p),
11570×
                None => return fail("nothing to undo in this workspace"),
1158
            }
1159
        };
116015×
        let before = parent.view;
116115×
        let after = pending_checkout
116215×
            .map(|o| o.view)
116315×
            .unwrap_or_else(|| target.view.clone());
116415×
        let changes = self.view_changes(&before, &after)?;
116515×
        let pushed = self.pushed_by(&before, &after, &head.view)?;
116615×
        let restored_wc = before.workspaces.get(&self.workspace).copied();
116715×
        if others == 0 {
1168
            // Only this workspace's operations since: move the head back.
116910×
            let _lock = if self.store.is_local() {
117010×
                Some(self.lock_ops()?)
1171
            } else {
11720×
                None
1173
            };
117410×
            let parent_ref = *target.parents.first().expect("the target has a parent");
117510×
            let (now, version) = self.read_head()?;
117610×
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
11770×
                return fail("another oxy command ran while undoing; run undo again");
117810×
            }
1179
        } else {
11805×
            let view = self.revert_view(&head.view, &before, &after)?;
11813×
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1182
        }
118313×
        self.drop_manifest();
118413×
        if let Some(then) = restored_wc {
118513×
            if clean_now && Some(then) != wc_now {
1186
                // Past `core.snapshot-retention` the working copy may be
1187
                // gone: the files then stay as they are.
118810×
                let Ok(wc) = self.store.get_change(&then) else {
11890×
                    return Ok(Undone {
11900×
                        command: target.command,
11910×
                        changes,
11920×
                        others_kept: others,
11930×
                        pushed,
11940×
                    });
1195
                };
119610×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
11978×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1198
                    // The files differ from the restored working copy by
1199
                    // exactly what the undone command did: nothing else is
1200
                    // on disk, as the working copy was clean.
12018×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
12022×
                }
12033×
            }
12040×
        }
120513×
        Ok(Undone {
120613×
            command: target.command,
120713×
            changes,
120813×
            others_kept: others,
120913×
            pushed,
121013×
        })
121116×
    }
1212
1213
    /// Whether operation `op` was a push: it changed only what this
1214
    /// repository knows of remotes.
121531×
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
121631×
        let Some(p) = parent else {
12171×
            return false;
1218
        };
121930×
        op.command.starts_with("oxy push")
12201×
            && op.view.bookmarks == p.view.bookmarks
12211×
            && op.view.tags == p.view.tags
12221×
            && op.view.workspaces == p.view.workspaces
12231×
            && op.view.policy == p.view.policy
122431×
    }
1225
1226
    /// Whether operation `op` (whose predecessor is `parent`) was this
1227
    /// workspace's. Operations record their workspace (oxygen#99); for older
1228
    /// ones it is read from the view: one that changed only other
1229
    /// workspaces' working copies was theirs, anything else counts as ours.
123030×
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
123130×
        if let Some(w) = op.workspace {
123230×
            return w == self.workspace;
12330×
        }
12340×
        let Some(p) = parent else {
12350×
            return true;
1236
        };
12370×
        let ids: BTreeSet<&WorkspaceId> = op
12380×
            .view
12390×
            .workspaces
12400×
            .keys()
12410×
            .chain(p.view.workspaces.keys())
12420×
            .collect();
12430×
        let moved: Vec<&WorkspaceId> = ids
12440×
            .into_iter()
12450×
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
12460×
            .collect();
12470×
        moved.is_empty() || moved.contains(&&self.workspace)
124830×
    }
1249
1250
    /// `current` with what changed from `before` to `after` put back, this
1251
    /// workspace's working copy included; refused when a later operation
1252
    /// changed one of the same references again.
12535×
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
125410×
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
125510×
            cur: &mut BTreeMap<K, V>,
125610×
            before: &BTreeMap<K, V>,
125710×
            after: &BTreeMap<K, V>,
125810×
            name: impl Fn(&K) -> String,
125910×
            clashes: &mut Vec<String>,
126010×
        ) {
126110×
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
126210×
            for k in keys {
12635×
                let (b, a) = (before.get(k), after.get(k));
12645×
                if a == b {
12654×
                    continue;
12661×
                }
12671×
                if cur.get(k) != a {
12681×
                    clashes.push(name(k));
12691×
                    continue;
12700×
                }
12710×
                match b {
12720×
                    Some(v) => cur.insert(k.clone(), v.clone()),
12730×
                    None => cur.remove(k),
1274
                };
1275
            }
127610×
        }
12775×
        let mut out = current.clone();
12785×
        let mut clashes = Vec::new();
1279
        // A bookmark another workspace moved since is put back head by
1280
        // head: the heads the command added go, the heads it replaced
1281
        // return, and the other workspace's heads stay. Only when a later
1282
        // change was built on one the command added is that not possible.
12835×
        let names: BTreeSet<&String> = before
12845×
            .bookmarks
12855×
            .keys()
12865×
            .chain(after.bookmarks.keys())
12875×
            .collect();
12888×
        for name in names {
12898×
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
12908×
            let cur = current.bookmarks.get(name);
12918×
            if a == b {
12924×
                continue;
12934×
            }
12944×
            if cur == a {
12952×
                match b {
12962×
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
12970×
                    None => out.bookmarks.remove(name),
1298
                };
12992×
                continue;
13002×
            }
13012×
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
13020×
                clashes.push(format!("bookmark {name}"));
13030×
                continue;
1304
            };
13052×
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
13062×
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
13072×
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
13082×
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
13092×
            if !added.iter().all(|h| now.contains(h)) {
13101×
                clashes.push(format!(
1311
                    "bookmark {name} (a later change builds on this one)"
1312
                ));
13131×
                continue;
13141×
            }
13151×
            let mut heads: Vec<ChangeHash> = now
13161×
                .iter()
13173×
                .filter(|h| !added.contains(h))
13181×
                .chain(was.difference(&became))
13191×
                .copied()
13201×
                .collect();
13211×
            heads.sort();
13221×
            heads.dedup();
13231×
            let heads = self.load_state(&heads)?.maximal(&heads);
13241×
            out.bookmarks.insert(
13251×
                name.clone(),
13261×
                self.store.put_state(&StateObject::new(heads))?,
1327
            );
1328
        }
1329
13305×
        back(
13315×
            &mut out.tags,
13325×
            &before.tags,
13335×
            &after.tags,
13340×
            |k| format!("tag {k}"),
13355×
            &mut clashes,
1336
        );
13375×
        let mine = self.workspace;
133815×
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
133915×
            v.workspaces
134015×
                .iter()
134129×
                .filter(|(k, _)| **k != mine)
134215×
                .map(|(k, v)| (*k, *v))
134315×
                .collect()
134415×
        };
13455×
        let mut theirs = others(&out);
13465×
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
13471×
            Some(p) => format!("the workspace at {}", p.display()),
13480×
            None => format!("workspace {}", id.to_hex()),
13491×
        };
13505×
        back(
13515×
            &mut theirs,
13525×
            &others(before),
13535×
            &others(after),
13545×
            workspace_name,
13555×
            &mut clashes,
1356
        );
13575×
        let empty = BTreeMap::new();
13585×
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
13595×
        for n in names {
13600×
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
13610×
            back(
13620×
                &mut cur,
13630×
                before.remotes.get(n).unwrap_or(&empty),
13640×
                after.remotes.get(n).unwrap_or(&empty),
13650×
                |k| format!("{n}/{k}"),
13660×
                &mut clashes,
1367
            );
13680×
            if cur.is_empty() {
13690×
                out.remotes.remove(n);
13700×
            } else {
13710×
                out.remotes.insert(n.clone(), cur);
13720×
            }
1373
        }
13745×
        if before.policy != after.policy {
13750×
            if out.policy == after.policy {
13760×
                out.policy = before.policy;
13770×
            } else {
13780×
                clashes.push("the policy".into());
13790×
            }
13805×
        }
13815×
        if !clashes.is_empty() {
13822×
            return fail(format!(
1383
                "undo would also take back what another workspace has done since to {}; \
1384
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
13852×
                clashes.join(", ")
1386
            ));
13873×
        }
13883×
        out.workspaces = theirs;
13893×
        match before.workspaces.get(&mine) {
13903×
            Some(wc) => out.workspaces.insert(mine, *wc),
13910×
            None => out.workspaces.remove(&mine),
1392
        };
13933×
        Ok(out)
13945×
    }
1395
1396
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1397
    /// in `now` already holds: undoing them locally leaves them there.
139815×
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
139915×
        let mut out = Vec::new();
140018×
        for (name, st) in &after.bookmarks {
140118×
            if before.bookmarks.get(name) == Some(st) {
14024×
                continue;
140314×
            }
140414×
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
140514×
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
14060×
                None => BTreeSet::new(),
1407
            };
140814×
            let added: Vec<ChangeHash> = self
140914×
                .store
141014×
                .get_state(st)?
1411
                .heads
141214×
                .into_iter()
141320×
                .filter(|h| !had.contains(h))
141414×
                .collect();
141514×
            if added.is_empty() {
14161×
                continue;
141713×
            }
141813×
            for (remote, bookmarks) in &now.remotes {
14191×
                if let Some(rs) = bookmarks.get(name) {
14201×
                    let theirs = self.store.get_state(rs)?.heads;
14211×
                    if added.iter().any(|h| theirs.contains(h)) {
14221×
                        out.push((name.clone(), remote.clone()));
14231×
                    }
14240×
                }
1425
            }
1426
        }
142715×
        Ok(out)
142815×
    }
1429
1430
    /// The last operation that was not a snapshot.
14312×
    pub fn last_command(&self) -> Result<Op> {
14322×
        let (_, mut op) = self.head_op()?;
14334×
        while op.is_snapshot() {
14342×
            let Some(parent) = op.parents.first() else {
14350×
                break;
1436
            };
14372×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1438
        }
14392×
        Ok(op)
14402×
    }
1441
1442
    // ------------------------------------------------------------ states
1443
1444
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1445208×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1446208×
        if let Some(st) = self.load_state_checkpointed(heads)? {
14474×
            return Ok(st);
1448203×
        }
1449203×
        self.load_state_full(heads)
1450208×
    }
1451
1452
    /// The state of `heads` for its history (changes, tree, metadata) with
1453
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1454
    /// and friends. Build the graphs a command needs with
1455
    /// [`Repo::load_graphs_of`].
14561755×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
14571755×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
145831×
            return Ok(st);
14591724×
        }
14601724×
        self.load_state_replayed(heads, State::new_history_only())
14611755×
    }
1462
1463
    /// Build these file graphs in a history-only state.
14641859×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
14651859×
        state
14661859×
            .load_graphs(
14671859×
                nodes,
146854×
                |refs| {
146954×
                    self.read_blobs(refs).map_err(|e| {
14703×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14713×
                    })
147254×
                },
14732161×
                |h| self.change_bytes(h),
1474
            )
14751859×
            .map_err(|e| self.index_damage(e))
14761859×
    }
1477
1478
    /// An error building graphs, and when it is a state index found
1479
    /// damaged (a file's history that does not match its hash), the
1480
    /// workspace's state indexes removed: they are rebuilt from history by
1481
    /// the next command.
14824×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
14834×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
14843×
            return e.into();
1485
        };
14862×
        for path in self.state_indexes() {
14872×
            let _ = fs::remove_file(path);
14882×
        }
14891×
        RepoError::Msg(format!(
14901×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
14911×
        ))
14924×
    }
1493
1494
    /// The graphs of `nodes` of a history-only state, built beside it (see
1495
    /// [`State::build_graphs_detached`]).
149677×
    pub fn build_graphs_detached(
149777×
        &self,
149877×
        state: &State,
149977×
        nodes: &[crate::ids::NodeId],
150077×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
150177×
        Ok(state
150277×
            .build_graphs_detached(
150377×
                nodes,
15040×
                |refs| {
15050×
                    self.read_blobs(refs).map_err(|e| {
15060×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15070×
                    })
15080×
                },
150983×
                |h| self.change_bytes(h),
1510
            )
151177×
            .map_err(|e| self.index_damage(e))?
151277×
            .into_iter()
151377×
            .collect())
151477×
    }
1515
1516
    /// The contents of texts [`State::single_text`] gave: blobs read in
1517
    /// one go, inline ones from their changes.
1518373×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1519
        use crate::objects::TextRef;
1520373×
        let refs: Vec<ObjectRef> = texts
1521373×
            .iter()
15225590×
            .filter_map(|t| match t {
15231×
                TextRef::Blob(r, _, _) => Some(*r),
15245589×
                TextRef::Inline { .. } => None,
15255590×
            })
1526373×
            .collect();
1527373×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1528373×
        let mut out = Vec::with_capacity(texts.len());
15295590×
        for t in texts {
15305590×
            let lines = match t {
15311×
                TextRef::Blob(_, count, form) => {
15321×
                    let content = blobs
15331×
                        .next()
15341×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
15351×
                    crate::objects::text_lines(&content, *count, *form)?
1536
                }
15375589×
                TextRef::Inline { change, start, end } => {
15385589×
                    let bytes = self.change_bytes(change)?;
15395589×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
15400×
                        RepoError::Msg("an inline insert lies outside its change".into())
15410×
                    })?;
15425589×
                    crate::objects::inline_lines(range)?
1543
                }
1544
            };
15455590×
            out.push(lines.bytes().to_vec());
1546
        }
1547373×
        Ok(out)
1548373×
    }
1549
1550
    /// Build every graph a history-only state still lacks, making it full.
15511881×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
15521881×
        state
15531881×
            .load_all_graphs(
155416×
                |refs| {
155516×
                    self.read_blobs(refs).map_err(|e| {
15560×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15570×
                    })
155816×
                },
15593933×
                |h| self.change_bytes(h),
1560
            )
15611881×
            .map_err(|e| self.index_damage(e))
15621881×
    }
1563
1564
    /// A change's encoding, for building graphs of its inline inserts. The
1565
    /// last few read are kept: a checkout building graphs a batch at a
1566
    /// time reads the same large changes for every batch, often in turn.
156711766×
    fn change_bytes(
156811766×
        &self,
156911766×
        h: &ChangeHash,
157011766×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
157111766×
        let mut cache = self.last_change.borrow_mut();
157220328×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
15739151×
            let hit = cache.remove(i);
15749151×
            let b = hit.1.clone();
15759151×
            cache.push(hit);
15769151×
            return Ok(b);
15772615×
        }
15782615×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
15790×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
15800×
        })?);
15812615×
        cache.push((*h, b.clone()));
1582
        // The last few, within a memory budget; the newest always stays.
15834206×
        while cache.len() > CHANGE_CACHE_COUNT
15842615×
            || (cache.len() > 1
15857867×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15861591×
        {
15871591×
            cache.remove(0);
15881591×
        }
15892615×
        Ok(b)
159011766×
    }
1591
1592
    /// Load the dependency closure of `heads` change by change.
1593257×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1594257×
        self.load_state_replayed(heads, State::new())
1595257×
    }
1596
15973406×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
15983406×
        let history = state.is_history_only();
15993406×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
16003406×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1601
        {
16023406×
            let _t = crate::timing::phase("load: read and add changes");
16033406×
            let (mut read, mut add, mut fetch) = (
16043406×
                std::time::Duration::ZERO,
16053406×
                std::time::Duration::ZERO,
16063406×
                std::time::Duration::ZERO,
16073406×
            );
160814167×
            while let Some(h) = stack.pop() {
1609
                // A change the state holds brings its history with it.
161010764×
                if !seen.insert(h) || state.contains(&h) {
16112690×
                    continue;
16128074×
                }
16138074×
                let t0 = std::time::Instant::now();
1614
                // A history-only state reads text only for the graphs it
1615
                // builds; either way the hash is the one asked for.
16168074×
                let (c, texts) = if history {
16176610×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
16186609×
                    fetch += t0.elapsed();
16196609×
                    Change::decode_skeleton(&bytes, h)
16206609×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1621
                } else {
16221464×
                    (self.store.get_change(&h)?, Vec::new())
1623
                };
16248071×
                read += t0.elapsed();
16258071×
                stack.extend(c.deps.iter().copied());
16268071×
                let t1 = std::time::Instant::now();
16278071×
                state.add_known(h, c, texts);
16288071×
                add += t1.elapsed();
1629
            }
16303403×
            crate::timing::record("load:   of which reading", read);
16313403×
            crate::timing::record("load:     of which fetching", fetch);
16323403×
            crate::timing::record("load:   of which applying", add);
1633
        }
16343403×
        let _t = crate::timing::phase("load: validate");
16353403×
        state.validate()?;
16363403×
        Ok(state)
16373406×
    }
1638
16392432×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
16402432×
        if self.bare {
16412×
            return fail("this is a bare repository: it has no working copy");
16422430×
        }
16432430×
        let view = self.view()?;
16442430×
        let h = *view
16452430×
            .workspaces
16462430×
            .get(&self.workspace)
16472430×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
16482429×
        Ok((h, self.store.get_change(&h)?))
16492432×
    }
1650
1651
    /// Heads of a bookmark's state (spec §10.1).
16521869×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
16531869×
        match view.bookmarks.get(bookmark) {
16541869×
            Some(st) => Ok(self.store.get_state(st)?.heads),
16550×
            None => Ok(vec![]),
1656
        }
16571869×
    }
1658
1659530×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1660530×
        self.heads_of(&self.view()?, &self.config.bookmark)
1661530×
    }
1662
1663
    // ------------------------------------------------------------ blobs
1664
1665399×
    fn blob_for(content: &[u8]) -> Blob {
1666399×
        Blob::of(content)
1667399×
    }
1668
1669246×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1670246×
        Self::blob_for(content).hash()
1671246×
    }
1672
1673151×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1674194×
        for c in crate::chunk::chunks(content) {
1675194×
            self.store.put_chunk(c)?;
1676
        }
1677151×
        Ok(self
1678151×
            .store
1679151×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1680151×
    }
1681
1682
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1683
    /// all their chunks, are read in parallel; a blob the store lacks goes
1684
    /// through [`Repo::read_blob`], which may fetch it lazily.
1685447×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1686447×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1687447×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
168880×
            blobs.push(match got {
168975×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
16900×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
16915×
                Err(crate::store::StoreError::NotFound(_)) => None,
16920×
                Err(e) => return Err(e.into()),
1693
            });
1694
        }
1695447×
        let chunk_refs: Vec<ObjectRef> = blobs
1696447×
            .iter()
1697447×
            .flatten()
1698447×
            .flat_map(|b| b.chunks.iter().copied())
1699447×
            .collect();
1700447×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1701447×
        let mut out = Vec::with_capacity(refs.len());
1702447×
        for (r, blob) in refs.iter().zip(blobs) {
170380×
            match blob {
17045×
                None => out.push(self.read_blob(r)?),
170575×
                Some(b) => {
170675×
                    let mut content = Vec::with_capacity(b.length as usize);
1707114×
                    for c in &b.chunks {
1708114×
                        match chunks.next() {
1709114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
17100×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
17110×
                            Some(Err(e)) => return Err(e.into()),
17120×
                            None => return fail("chunk list ended early"),
1713
                        }
1714
                    }
171575×
                    out.push(content);
1716
                }
1717
            }
1718
        }
1719442×
        Ok(out)
1720447×
    }
1721
1722
    /// Read a blob's content, fetching it from the remote that withheld it
1723
    /// when it is lazily absent (spec §13.5).
1724113×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1725113×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
17264×
            self.fetch_lazy_blob(r)?;
1727109×
        }
1728113×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1729108×
        let mut out = Vec::with_capacity(blob.length as usize);
1730135×
        for c in &blob.chunks {
1731135×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1732
        }
1733108×
        Ok(out)
1734113×
    }
1735
1736
    // ------------------------------------------------------------ working copy
1737
1738
    /// Attributes from the `.oxyattributes` files in the working directory.
17392×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1740
        // Nested repositories and ignored paths are left out, as in a walk.
17418×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
17422×
        let files: Vec<(String, Vec<u8>)> = listing
17432×
            .files
17442×
            .into_iter()
17452×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
17462×
            .collect();
17472×
        crate::attributes::Attributes::from_files(
17482×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1749
        )
17502×
    }
1751
1752
    /// Folders holding a repository of their own that the last look at the
1753
    /// working copy left out, not being subrepos (oxygen#43).
175429×
    pub fn untracked_nested(&self) -> Vec<String> {
175529×
        self.untracked_nested.borrow().clone()
175629×
    }
1757
1758
    /// New untracked files the last snapshot left out for being larger than
1759
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
176033×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
176133×
        self.skipped_large.borrow().clone()
176233×
    }
1763
1764
    /// Attributes from a materialized state's `.oxyattributes` files.
17653×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
17666×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
17676×
            match &f.content {
17686×
                FileContent::Text { bytes, .. }
17696×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1770
                {
17710×
                    Some((p.as_str(), bytes.as_slice()))
1772
                }
17736×
                _ => None,
1774
            }
17756×
        }))
17763×
    }
1777
1778
    /// Store a blob, raw when the path is `nocompress`.
1779132×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1780132×
        if !nocompress {
1781130×
            return self.store_blob(content);
17822×
        }
17832×
        for c in crate::chunk::chunks(content) {
17842×
            self.store.put_chunk_nocompress(c)?;
1785
        }
17862×
        Ok(self
17872×
            .store
17882×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1789132×
    }
1790
1791
    /// This workspace's state index (oxygen#41): its working copy's base,
1792
    /// saved so a snapshot reads it rather than replaying history.
1793
    /// The state index of the state with these heads: this workspace keeps
1794
    /// the last few it used, named by their heads, so moving between two
1795
    /// states finds both.
17962525×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
17972525×
        let mut heads = heads.to_vec();
17982525×
        heads.sort();
17992525×
        let mut h = blake3::Hasher::new();
18002558×
        for c in &heads {
18012558×
            h.update(&c.0);
18022558×
        }
18032525×
        self.oxy.join("index").join(format!(
18042525×
            "{}{}",
18052525×
            self.state_index_prefix(),
18062525×
            &h.finalize().to_hex()[..16]
18072525×
        ))
18082525×
    }
1809
18104961×
    fn state_index_prefix(&self) -> String {
18114961×
        format!("state-{}-", self.workspace.to_hex())
18124961×
    }
1813
1814
    /// This workspace's state indexes, newest first.
18152436×
    fn state_indexes(&self) -> Vec<PathBuf> {
18162436×
        let prefix = self.state_index_prefix();
18172436×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
18182436×
            .into_iter()
18192436×
            .flatten()
18202436×
            .flatten()
18212436×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
18222436×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
18232436×
            .collect();
18242436×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
18252436×
        found.into_iter().map(|(_, p)| p).collect()
18262436×
    }
1827
1828
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1829
    /// from this workspace's state index when it holds that history: every
1830
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1831
    /// is loaded from history and indexed for next time.
18322108×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
18332108×
        if let Some((st, heads)) = self.read_state_index(deps) {
18341699×
            let mut have = st.maximal(deps);
18351699×
            have.sort();
18361699×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1837
                // Re-encoding reads every history: one found damaged is
1838
                // left to the build that reads it, which reports it.
1839
                #[cfg(test)]
1840161×
                if let Some(mine) = st.write_index() {
1841158×
                    assert_eq!(
1842158×
                        Some(mine),
1843158×
                        self.load_state_history(deps)?.write_index(),
1844
                        "a state index holds the state history gives"
1845
                    );
18463×
                }
1847274×
                return Ok(st);
18481425×
            }
1849
            // An index a few changes behind (a commit, a pull since): add
1850
            // what it lacks, as long as all it holds is history of `deps`.
1851
            // Anything amiss (a change beyond a shallow boundary) takes the
1852
            // long way instead.
18531425×
            let (indexed, started) = (st.len(), std::time::Instant::now());
18541425×
            if let Ok(st) = self.load_state_replayed(deps, st) {
18551424×
                let mut all = deps.to_vec();
18561424×
                all.extend(heads.iter().copied());
18571424×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
18581424×
                within.sort();
18591424×
                want.sort();
18601424×
                if within == want {
1861
                    #[cfg(test)]
1862711×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1863
                    // Writing the index costs far more than replaying a
1864
                    // few small changes: it is rewritten once it falls
1865
                    // behind, or when replaying took long (large changes).
18661422×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
18671422×
                        || started.elapsed() > INDEX_REPLAY_TIME
18684×
                    {
18694×
                        self.write_state_index(deps, &st);
18701418×
                    }
18711422×
                    return Ok(st);
18722×
                }
18731×
            }
1874409×
        }
1875412×
        let st = self.load_state_history(deps)?;
1876412×
        self.write_state_index(deps, &st);
1877412×
        Ok(st)
18782108×
    }
1879
1880
    /// Two history-only states hold the same changes and render the same
1881
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1882
    /// the checkpoint's graphs as the bases of its files' histories.
1883
    #[cfg(test)]
1884711×
    fn assert_same_state(&self, a: &State, b: &State) {
18851422×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1886711×
        assert_eq!(ids(a), ids(b), "the same changes");
18871422×
        let files = |s: &State| {
18881422×
            let mut s = s.clone();
18891422×
            self.load_all_graphs(&mut s).unwrap();
18901422×
            s.materialize().files
18911422×
        };
1892711×
        assert_eq!(files(a), files(b), "the same files");
1893711×
    }
1894
1895
    /// The state index file: its heads, a hash of its changes block and one
1896
    /// of the rest, then the body [`State::write_index`] gives, whose first
1897
    /// block is the changes. Hashed in two parts so the log can read and
1898
    /// check the changes alone.
1899
    /// The index of `deps` if there is one, else the newest, which the
1900
    /// caller may bring up to date.
19012108×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1902
        use std::io::Read;
19032108×
        let _t = crate::timing::phase("load: state index");
19042108×
        let exact = self.state_index_path(deps);
19052108×
        let reading = crate::timing::phase("load:   of which reading the file");
19062108×
        let mut f = match fs::File::open(&exact) {
1907274×
            Ok(f) => {
1908
                // Used now: the newest, so the last to be dropped.
1909274×
                let _ = fs::File::options()
1910274×
                    .write(true)
1911274×
                    .open(&exact)
1912274×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1913274×
                f
1914
            }
19151834×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1916
        };
19171699×
        let total = f.metadata().ok()?.len();
19181699×
        let mut word = [0u8; 4];
19191699×
        f.read_exact(&mut word).ok()?;
19201699×
        let n = u32::from_le_bytes(word) as usize;
19211699×
        let mut head = vec![0u8; 32 * n + 64 + 8];
19221699×
        f.read_exact(&mut head).ok()?;
19231699×
        let heads: Vec<ChangeHash> = head[..32 * n]
19241699×
            .chunks_exact(32)
19251699×
            .map(|c| ObjectRef(c.try_into().unwrap()))
19261699×
            .collect();
19271699×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
19281699×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
19291699×
        let at = (4 + head.len()) as u64;
19301699×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
19310×
            return None;
19321699×
        }
1933
        // The front only: the files' histories after it are read, each
1934
        // checked by its own hash, when a command builds that file.
19351699×
        let mut front = vec![0u8; front_len as usize];
19361699×
        f.read_exact(&mut front).ok()?;
19371699×
        drop(reading);
19381699×
        let checking = crate::timing::phase("load:   of which checking the file");
19391699×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
19401699×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
19413398×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
19421699×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
19430×
            return None;
19441699×
        }
19451699×
        drop(checking);
19461699×
        let histories = crate::state::Histories::File(
19471699×
            std::sync::Arc::new(f),
19481699×
            at + front_len,
19491699×
            total - at - front_len,
19501699×
        );
19511699×
        Some((State::read_index_front(&front, histories).ok()?, heads))
19522108×
    }
1953
1954
    /// The changes of this workspace's state index (the closure of its
1955
    /// heads), read without the rest of the index.
1956
    #[allow(clippy::type_complexity)]
1957183×
    pub(crate) fn read_state_index_changes(
1958183×
        &self,
1959183×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1960
        use std::io::Read;
1961183×
        let _t = crate::timing::phase("load: state index changes");
1962183×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1963166×
        let mut word = [0u8; 4];
1964166×
        f.read_exact(&mut word).ok()?;
1965166×
        let n = u32::from_le_bytes(word) as usize;
1966
        // Heads, the two sums, the front's length, then the changes block.
1967166×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1968166×
        f.read_exact(&mut head).ok()?;
1969166×
        let heads: Vec<ChangeHash> = head[..32 * n]
1970166×
            .chunks_exact(32)
1971166×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1972166×
            .collect();
1973166×
        let sum = &head[32 * n..32 * n + 32];
1974166×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1975166×
        let mut changes = vec![0u8; 4 + len];
1976166×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1977166×
        f.read_exact(&mut changes[4..]).ok()?;
1978166×
        let checking = crate::timing::phase("load:   of which checking");
1979166×
        let mut h = blake3::Hasher::new();
1980166×
        h.update_rayon(&changes);
1981166×
        if h.finalize().as_bytes() != sum {
19820×
            return None;
1983166×
        }
1984166×
        drop(checking);
1985166×
        let _decoding = crate::timing::phase("load:   of which decoding");
1986166×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
1987183×
    }
1988
1989
    /// Save `st`, the history-only state of `deps`, as this workspace's
1990
    /// state index; quietly nothing when it cannot be (it is only a cache).
1991417×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1992417×
        let _t = crate::timing::phase("write: state index");
1993417×
        let encoding = crate::timing::phase("write:   of which encoding");
1994417×
        let Some(body) = st.write_index() else {
19950×
            return;
1996
        };
1997417×
        drop(encoding);
1998
        #[cfg(test)]
1999225×
        assert_eq!(
2000225×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
2001225×
            Some(body.clone()),
2002
            "a state index reads back as written"
2003
        );
2004417×
        let mut heads = st.maximal(deps);
2005417×
        heads.sort();
2006417×
        let mut w = crate::flat::Writer::default();
2007417×
        w.count(heads.len());
2008417×
        for h in &heads {
200918×
            w.object(h);
201018×
        }
2011
        // The body is the front's length, the front, then the files'
2012
        // histories, which carry their own hashes: the sums cover the
2013
        // front's changes block and the rest of the front.
2014417×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
2015417×
        let front = &body[8..8 + front_len];
2016417×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
2017834×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
2018417×
        w.fixed(&sum(&front[..split]));
2019417×
        w.fixed(&sum(&front[split..]));
2020417×
        w.fixed(&body);
2021417×
        let path = self.state_index_path(&heads);
2022417×
        let _ = fs::create_dir_all(self.oxy.join("index"));
2023417×
        let _ = write_cache(&path, &w.0);
2024
        // The last two used: the index of a state moved away from stays for
2025
        // a move back. Older ones (and the unnamed one of before) go.
2026417×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
20271×
            let _ = fs::remove_file(old);
20281×
        }
2029417×
        let _ = fs::remove_file(
2030417×
            self.oxy
2031417×
                .join("index")
2032417×
                .join(format!("state-{}", self.workspace.to_hex())),
2033417×
        );
2034417×
    }
2035
20366×
    fn locks_dir(&self) -> PathBuf {
20376×
        self.oxy.join("locks")
20386×
    }
2039
2040
    /// Whether `path` is locked locally for editing (spec §18, advisory).
20413×
    pub fn is_locked(&self, path: &str) -> bool {
20423×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
20433×
    }
2044
2045
    /// Take the advisory local lock on a `lockable` file and make it writable.
20462×
    pub fn lock_path(&self, path: &str) -> Result<()> {
20472×
        let attrs = self.disk_attributes();
20482×
        if !attrs.lookup(path).lockable {
20491×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
20501×
        }
20511×
        fs::create_dir_all(self.locks_dir())?;
20521×
        write_atomic(
20531×
            &self.locks_dir().join(path.replace('/', "%2F")),
20541×
            std::process::id().to_string().as_bytes(),
20550×
        )?;
20561×
        set_readonly(&self.root.join(path), false)?;
20571×
        Ok(())
20582×
    }
2059
2060
    /// Release the local lock and make the file read-only again.
20611×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
20621×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
20631×
        if self.root.join(path).exists() {
20641×
            set_readonly(&self.root.join(path), true)?;
20650×
        }
20661×
        Ok(())
20671×
    }
2068
2069
    /// Whether a repository path is inside the sparse filter (spec §17).
207024616×
    pub fn in_scope(&self, path: &str) -> bool {
207124616×
        self.config.sparse_paths.is_empty()
207282×
            || self
207382×
                .config
207482×
                .sparse_paths
207582×
                .iter()
207699×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
207724616×
    }
2078
20791×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
20801×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
20811×
    }
2082
2083
    /// Walk the working copy; with a manifest, a file whose size and mtime
2084
    /// match it is not read: an opaque file yields its known blob, and a
2085
    /// text file whose recorded graph key equals its base graph's key in
2086
    /// `keys` (path → key) is marked unchanged; other text files are read
2087
    /// but keep their known hash. Files modified within two seconds of the
2088
    /// manifest are never trusted (a racy stat).
2089
    ///
2090
    /// `.oxyattributes` files are always read, since their content is
2091
    /// needed; and when any of them is not known unchanged (added, removed,
2092
    /// edited, or changed in the base), no text file is taken as unchanged,
2093
    /// because attributes decide how a file compares with the base.
2094
    ///
2095
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2096
    /// (the base state's files) that exists on disk is included even when
2097
    /// an ignore rule matches it, as in Git.
20981343×
    fn walk_working_copy_with(
20991343×
        &self,
21001343×
        cache: Option<&prompt::Manifest>,
21011343×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
21021343×
        keys: Option<&KeyOf>,
21031343×
    ) -> Result<BTreeMap<String, FsEntry>> {
2104
        let mut out: BTreeMap<String, FsEntry>;
21051343×
        let sparse = &self.config.sparse_paths;
21069236×
        let in_scope = |p: &str| {
21079236×
            sparse.is_empty()
21087×
                || sparse
21097×
                    .iter()
21107×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
21119236×
        };
21121343×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2113
        let walk::Listing {
21141343×
            files,
21151343×
            symlinks,
21161343×
            nested,
21171343×
            dirs,
21181343×
        } = match self.listing_cache.take() {
2119180×
            Some(l) => l,
2120
            // Ignore rules apply to untracked paths only, so the base's
2121
            // files are not matched against them (an added file is: a rule
2122
            // written after it was snapshotted leaves it out again).
21239248×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2124
        };
2125
        // A new file larger than the limit is left out and named, not taken
2126
        // in unseen (oxygen#98): a build's output or a downloaded image
2127
        // would otherwise be stored by the next status, kept by the
2128
        // operation log. Files tracked, or already in the working copy, stay.
21291343×
        let limit = self.config.max_new_file;
21301343×
        let mut skipped = Vec::new();
21311343×
        let files: Vec<_> = files
21321343×
            .into_iter()
213312235×
            .filter(|(rel, _, meta)| {
213412235×
                let new = !tracked.contains_key(rel)
21353133×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
213612235×
                if limit > 0 && new && meta.size > limit {
21373×
                    skipped.push((rel.clone(), meta.size));
21383×
                    return false;
213912232×
                }
214012232×
                true
214112235×
            })
21421343×
            .collect();
21431343×
        *self.skipped_large.borrow_mut() = skipped;
21441343×
        let keys = keys.filter(|k| {
214512220×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
21461340×
            let attrs_unchanged =
21471340×
                files
21481340×
                    .iter()
214912201×
                    .filter(|(r, _, _)| is_attributes(r))
21501340×
                    .all(|(rel, _, meta)| {
21519×
                        stat_cached(rel, meta, cache)
21529×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
21539×
                    });
21541340×
            let none_removed = tracked
21551340×
                .keys()
21569195×
                .filter(|r| is_attributes(r))
21571340×
                .all(|r| on_disk.contains(r.as_str()));
21581340×
            attrs_unchanged && none_removed
21591340×
        });
21601343×
        *self.walked_dirs.borrow_mut() =
21611343×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
21621343×
        drop(walk_phase);
21631343×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2164
        // Reading files is most of a walk's cost; do it in parallel.
2165
        {
2166
            use rayon::prelude::*;
21671343×
            let mut read: Vec<(String, FsEntry)> = files
21681343×
                .par_iter()
216912232×
                .map(|(rel, path, meta)| {
2170
                    // A key is worked out only for a file the manifest
2171
                    // knows with the same stat and a key of its own.
217212232×
                    let key = keys
217312232×
                        .filter(|_| !is_attributes(rel))
217412232×
                        .filter(|_| {
217512192×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
217612192×
                        })
217712232×
                        .and_then(|k| k(rel));
217812232×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
217912232×
                })
21801343×
                .collect::<Result<Vec<_>>>()?;
218112230×
            for (rel, e) in read.iter_mut() {
2182
                // A cached blob the store lost (gc, a partial clone): read the file after all.
218312230×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
21840×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
21850×
                    e.blob = None;
218612230×
                }
2187
            }
2188
            // The listing is in path order, so the map is built without
2189
            // searching.
21901342×
            out = read.into_iter().collect();
21911342×
            for (rel, target) in symlinks {
21922×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
21932×
            }
2194
        }
21951342×
        drop(_read_phase);
21961342×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2197
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2198
        // already tracked as subrepo nodes, they contribute their pin;
2199
        // unregistered ones are left alone.
22001342×
        let modules = self.modules_on_disk();
22011342×
        let removed = self.removed_subrepos();
22021342×
        for rel in &removed {
22033×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
22041×
                self.clear_removed_subrepo(rel);
22052×
            }
2206
        }
22071342×
        let mut untracked_nested = Vec::new();
22081342×
        for dir in nested {
220931×
            let rel = self.rel_path(&dir);
221031×
            if !self.in_scope(&rel) || removed.contains(&rel) {
22113×
                continue;
221228×
            }
221328×
            let registered = modules.entries.get(&rel);
221428×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2215
            {
22161×
                untracked_nested.push(rel);
22171×
                continue;
221827×
            }
221927×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
222027×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2221
        }
22221342×
        untracked_nested.sort();
22231342×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2224
        // Tracked paths the ignore rules hid.
22251342×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
222684×
            if !self.in_scope(rel) {
222710×
                continue;
222874×
            }
222974×
            let path = self.root.join(rel);
223074×
            if *kind == NodeKind::Subrepo {
22314×
                if removed.contains(rel) {
22322×
                    continue;
22332×
                }
22342×
                let present =
22352×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
22362×
                if present {
22370×
                    let pin = subrepos::read_pin(
22380×
                        &path,
22390×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
22400×
                    )?;
22410×
                    out.insert(
22420×
                        rel.clone(),
22430×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2244
                    );
22452×
                } else if let Some(b) = blob {
22462×
                    // Not cloned (or emptied): the pin stays as recorded, as a
22472×
                    // Git gitlink does when its directory is absent.
22482×
                    out.insert(
22492×
                        rel.clone(),
22502×
                        FsEntry {
22512×
                            blob: Some(*b),
22522×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
22532×
                        },
22542×
                    );
22552×
                }
22562×
                continue;
225770×
            }
225870×
            let Ok(meta) = fs::symlink_metadata(&path) else {
225970×
                continue;
2260
            };
22610×
            let ft = meta.file_type();
22620×
            if ft.is_symlink() {
22630×
                let target = fs::read_link(&path)?;
22640×
                out.insert(
22650×
                    rel.clone(),
22660×
                    FsEntry::new(
22670×
                        NodeKind::Symlink,
2268
                        false,
22690×
                        target.to_string_lossy().as_bytes().to_vec(),
2270
                    ),
2271
                );
22720×
            } else if ft.is_file() {
22730×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
22740×
                out.insert(rel.clone(), e);
22750×
            }
2276
        }
22771342×
        Ok(out)
22781343×
    }
2279
2280
    /// The entry for one regular file, read or served from the stat cache.
22810×
    fn file_entry(
22820×
        &self,
22830×
        rel: &str,
22840×
        path: &Path,
22850×
        meta: &walk::Stat,
22860×
        cache: Option<&prompt::Manifest>,
22870×
    ) -> Result<FsEntry> {
22880×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
22890×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
22900×
            e.content = std::sync::Arc::new(fs::read(path)?);
22910×
            e.blob = None;
22920×
        }
22930×
        Ok(e)
22940×
    }
2295
2296
    /// The non-directory paths of a snapshot with their kinds, for the
2297
    /// walker's `tracked` set.
22982×
    pub(crate) fn tracked_kinds(
22992×
        snapshot: &Snapshot,
23002×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
23012×
        snapshot
23022×
            .files
23032×
            .iter()
230412×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
23058×
            .map(|(p, f)| {
23068×
                let blob = match &f.content {
23074×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
23084×
                    _ => None,
2309
                };
23108×
                (p.clone(), (f.kind, blob))
23118×
            })
23122×
            .collect()
23132×
    }
2314
2315
    /// A path under the root as a `/`-separated relative string.
231670×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
231770×
        path.strip_prefix(&self.root)
231870×
            .unwrap_or(path)
231970×
            .components()
2320134×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
232170×
            .collect::<Vec<_>>()
232270×
            .join("/")
232370×
    }
2324
}
2325
2326
impl Repo {
2327
    /// Changes reachable from the bookmark and the working copy, newest first.
2328101×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
2329101×
        let heads = self.bookmark_heads()?;
2330101×
        if self.bare {
23311×
            return self.log_state(&heads);
2332100×
        }
2333100×
        let (wc_hash, wc) = self.working_copy()?;
2334100×
        let mut all = heads.clone();
2335100×
        all.push(wc_hash);
2336100×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
2337100×
        let mut entries: Vec<LogEntry> = Vec::new();
2338
        // A shallow clone knows changes beyond its boundary from a
2339
        // checkpoint's metadata only: its log comes from the state.
2340100×
        let metas = if self.is_shallow() {
23411×
            self.load_state_history(&all)?
23421×
                .changes()
23439×
                .map(|(h, m)| (*h, m.clone()))
23441×
                .collect()
2345
        } else {
2346
            // The working copy's change is in hand, and is never in the
2347
            // state index: its metadata is not looked up again.
234899×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
234999×
            below.extend(wc.deps.iter().copied());
235099×
            let _t = crate::timing::phase("log: metadata");
235199×
            let mut metas = self.metas_of(&below)?;
2352346×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
235399×
                // First, where the log puts it, so the order may hold.
235499×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
235599×
            }
235699×
            metas
2357
        };
2358100×
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2359454×
            hash: h,
2360454×
            change: meta,
2361454×
            is_working_copy: h == wc_hash,
2362454×
            is_head: head_set.contains(&h),
2363454×
        }));
2364100×
        let _sorting = crate::timing::phase("log: sort");
2365
        // The hash makes the order total, so an unstable sort gives the same.
2366
        // From the state index the order already holds (oxygen#94).
2367849×
        let order = |a: &LogEntry, b: &LogEntry| {
2368849×
            b.is_working_copy
2369849×
                .cmp(&a.is_working_copy)
2370849×
                .then(crate::state::log_order(
2371849×
                    (&a.hash, &a.change.hlc),
2372849×
                    (&b.hash, &b.change.hlc),
2373
                ))
2374849×
        };
2375250×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
237653×
            entries.sort_unstable_by(order);
237753×
        }
2378100×
        Ok(entries)
2379101×
    }
2380
2381
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2382
    /// count, for paginated views.
23830×
    pub fn log_window(
23840×
        &self,
23850×
        heads: &[ChangeHash],
23860×
        offset: usize,
23870×
        limit: usize,
23880×
    ) -> Result<(Vec<LogEntry>, usize)> {
23890×
        let all = self.log_state(heads)?;
23900×
        let total = all.len();
23910×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
23920×
    }
2393
2394
    /// The log of the state with these heads, newest first, with no working
2395
    /// copy involved (for hosted repositories and any explicit state).
239610×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2397
        // The log needs change metadata only: neither graphs nor the tree.
239810×
        if self.is_shallow() {
23990×
            return Ok(self.log_of(&self.load_state_history(heads)?));
240010×
        }
240110×
        let metas = self.metas_of(heads)?;
240210×
        let depended: BTreeSet<ChangeHash> = metas
240310×
            .iter()
240430×
            .flat_map(|(_, m)| m.deps.iter().copied())
240510×
            .collect();
240610×
        let mut entries: Vec<LogEntry> = metas
240710×
            .into_iter()
240810×
            .map(|(h, meta)| LogEntry {
240930×
                hash: h,
241030×
                is_head: !depended.contains(&h),
241130×
                change: meta,
2412
                is_working_copy: false,
241330×
            })
241410×
            .collect();
241538×
        let order = |a: &LogEntry, b: &LogEntry| {
241638×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
241738×
        };
241811×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
24193×
            entries.sort_unstable_by(order);
24207×
        }
242110×
        Ok(entries)
242210×
    }
2423
2424
    /// Every change of the state with these heads and its metadata, read
2425
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2426
    /// a shallow clone's boundary is left out.
2427183×
    pub fn metas_of(
2428183×
        &self,
2429183×
        heads: &[ChangeHash],
2430183×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2431183×
        let boundary = self.boundary();
2432
        // The state index holds the metadata of its heads' closure: a
2433
        // change found there is not read from the store (a change object
2434
        // can be as large as the tree it adds).
2435183×
        let read = self.read_state_index_changes();
2436
        // Every one of `heads` in the index, and every head of the index
2437
        // among them: their closure is the index's changes, all of them
2438
        // (it is closed), and no walk is needed to find it.
2439183×
        if let Some((index_heads, all)) = &read {
2440166×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2441166×
            let in_index = || {
2442166×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2443166×
                    index_heads.iter().collect();
2444
                // Usually the heads asked are the index's: no set of all.
2445166×
                heads.iter().all(|h| index_heads.contains(h)) || {
2446166×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2447166×
                        all.iter().map(|(h, _)| h).collect();
2448166×
                    heads.iter().all(|h| all.contains(h))
2449
                }
2450166×
            };
2451166×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
24520×
                let (_, all) = read.expect("matched above");
2453
                #[cfg(test)]
2454
                {
2455
                    // The walk the shortcut saves finds the same changes.
24560×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
24570×
                    let mut stack = heads.to_vec();
24580×
                    while let Some(h) = stack.pop() {
24590×
                        if seen.insert(h) {
24600×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
24610×
                        }
2462
                    }
24630×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2464
                }
24650×
                return Ok(all);
2466166×
            }
246717×
        }
2468183×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2469183×
            read.map(|(_, all)| all.into_iter().collect());
2470183×
        let _walk = crate::timing::phase("metadata: walk");
2471183×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2472183×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2473183×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2474183×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
24751323×
        while let Some(h) = stack.pop() {
24761140×
            if !seen.insert(h) {
2477480×
                continue;
2478660×
            }
2479
            // Taken out of the index's map, each once: not copied.
2480660×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2481
                #[cfg(test)]
24820×
                assert_eq!(
2483
                    meta,
24840×
                    self.store.get_change_meta(&h)?,
2485
                    "the state index holds a change's metadata"
2486
                );
24870×
                stack.extend(meta.deps.iter().copied());
24880×
                out.push((h, meta));
24890×
                continue;
2490660×
            }
2491660×
            let started = std::time::Instant::now();
2492660×
            let meta = match self.store.get_change_meta(&h) {
2493660×
                Ok(m) => m,
24940×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
24950×
                Err(e) => return Err(e.into()),
2496
            };
2497660×
            stored += 1;
2498660×
            from_store += started.elapsed();
2499660×
            stack.extend(meta.deps.iter().copied());
2500660×
            out.push((h, meta));
2501
        }
2502183×
        if stored > 0 && crate::timing::enabled() {
25030×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2504183×
        }
2505183×
        Ok(out)
2506183×
    }
2507
2508
    /// The log of a state already loaded, newest first.
2509
    /// The history of lines `first..=last` (1-based) of `path` in the
2510
    /// state `heads` make (spec §27): every change that inserted or
2511
    /// deleted one of their atoms, or an atom deleted from between them,
2512
    /// newest first. Exact, as atoms keep their identity across edits.
25136×
    pub fn line_history(
25146×
        &self,
25156×
        heads: &[ChangeHash],
25166×
        path: &str,
25176×
        first: usize,
25186×
        last: usize,
25196×
    ) -> Result<Vec<LogEntry>> {
25206×
        if first == 0 || last < first {
25211×
            return fail(format!(
2522
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2523
            ));
25245×
        }
25255×
        let mut state = self.load_state_history(heads)?;
25265×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
25271×
            return fail(format!("{path} is not in that state"));
2528
        };
25294×
        self.load_graphs_of(&mut state, &[node])?;
25304×
        let live = state.live_lines(&node);
25314×
        if last > live.len() {
25321×
            return fail(format!(
2533
                "{path} has {} lines; asked for {first},{last}",
25341×
                live.len()
2535
            ));
25363×
        }
25373×
        let Some(g) = state.file(&node) else {
25380×
            return fail(format!("{path} is not a text file"));
2539
        };
25403×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
25413×
        let touched = g.touching(&atoms);
25423×
        Ok(self
25433×
            .log_of(&state)
25443×
            .into_iter()
254513×
            .filter(|e| touched.contains(&e.hash))
25463×
            .collect())
25476×
    }
2548
25498×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
25508×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
25518×
        let mut entries: Vec<LogEntry> = state
25528×
            .changes()
25538×
            .map(|(h, meta)| LogEntry {
255431×
                hash: *h,
255531×
                change: meta.clone(),
2556
                is_working_copy: false,
255731×
                is_head: head_set.contains(h),
255831×
            })
25598×
            .collect();
256048×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
25618×
        entries
25628×
    }
2563
2564
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2565
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2566
    /// (`resolve_change`).
256767×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
256867×
        let view = self.view()?;
256967×
        if let Some(st) = view.bookmarks.get(spec) {
257039×
            return Ok(self.store.get_state(st)?.heads);
257128×
        }
257228×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
25732×
            return Ok(self.store.get_state(&st)?.heads);
257426×
        }
257526×
        if let Some(heads) = self.tag_heads(spec)? {
25762×
            return Ok(heads);
257724×
        }
257824×
        Ok(vec![self.resolve_change(spec)?])
257967×
    }
2580
2581
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2582
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
258337×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
258437×
        if spec == "@" {
25850×
            return Ok(self.working_copy()?.0);
258637×
        }
258737×
        let view = self.view()?;
258837×
        let named = match view.bookmarks.get(spec) {
25891×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
259036×
            None => match remote_bookmark(&view, spec) {
25911×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
259235×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2593
            },
2594
        };
259537×
        if let Some((kind, heads)) = named {
25963×
            return match heads.len() {
25973×
                1 => Ok(heads[0]),
25980×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2599
            };
260034×
        }
260134×
        if spec.is_empty() || spec == "#" {
26020×
            return fail("empty change specifier");
260334×
        }
260434×
        let entries = self.log()?;
2605
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2606
        // cannot be a ChangeId, which has 32 (oxygen#103).
260734×
        let full_hash =
2608128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
260934×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
261028×
            entries
261128×
                .iter()
2612112×
                .filter(|e| e.hash.starts_with_hex(hp))
261328×
                .collect()
2614
        } else {
26156×
            entries
26166×
                .iter()
261721×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
26186×
                .collect()
2619
        };
262034×
        match matches.len() {
262129×
            1 => Ok(matches[0].hash),
26225×
            0 => match self.resolve_in_remotes(spec)? {
26231×
                Some(h) => Ok(h),
26244×
                None => fail(format!("no change matches {spec:?}")),
2625
            },
2626
            _ => {
26270×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
26280×
                if ids.len() == 1 {
26290×
                    fail(format!(
2630
                        "change {spec} is divergent: {} variants",
26310×
                        matches.len()
2632
                    ))
2633
                } else {
26340×
                    fail(format!("{spec:?} is ambiguous"))
2635
                }
2636
            }
2637
        }
263837×
    }
2639
2640
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2641
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2642
    /// `None` when none matches, or more than one.
26435×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
26445×
        let view = self.view()?;
26455×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
26465×
        for bookmarks in view.remotes.values() {
26473×
            for st in bookmarks.values() {
26483×
                let heads = self.store.get_state(st)?.heads;
26497×
                for e in self.log_state(&heads)? {
26507×
                    let hit = match spec.strip_prefix('#') {
26512×
                        Some(hp) => e.hash.starts_with_hex(hp),
26525×
                        None => e.change.change_id.starts_with_hex(spec),
2653
                    };
26547×
                    if hit {
26551×
                        found.insert(e.hash);
26566×
                    }
2657
                }
2658
            }
2659
        }
26605×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
26615×
    }
2662
2663
    /// Where a change is when no local bookmark or the working copy holds
2664
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2665
    /// it is held locally, or nowhere.
26664×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
26678×
        if self.log()?.iter().any(|e| e.hash == *hash) {
26683×
            return Ok(None);
26691×
        }
26701×
        let view = self.view()?;
26711×
        for (remote, bookmarks) in &view.remotes {
26721×
            for (name, st) in bookmarks {
26731×
                let heads = self.store.get_state(st)?.heads;
26741×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
26751×
                    return Ok(Some(format!("{remote}/{name}")));
26760×
                }
2677
            }
2678
        }
26790×
        Ok(None)
26804×
    }
2681
2682
    /// Human-readable description of what a change does, with line content.
26833×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
26843×
        let change = self.store.get_change(hash)?;
26853×
        let (base, base_snapshot) = self.change_base(&change)?;
26863×
        Ok(render_change(&change, &base, &base_snapshot))
26873×
    }
2688
2689
    /// The base state of `change` (its dependencies) and its rendering, as
2690
    /// much as showing the change needs: the whole tree, and the graphs and
2691
    /// contents of the files the change edits. Other text files are left
2692
    /// unrendered ([`Snapshot::unrendered`]).
26937×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
26947×
        let base = self.load_state_history(&change.deps)?;
26957×
        self.render_base_for(change, base)
26967×
    }
2697
2698
    /// The base for showing `change` alone: the graphs of the files it
2699
    /// edits built, and the base's tree with no file rendered, which is
2700
    /// all [`render_change`](snapshot::render_change) and
2701
    /// [`diff_files_of`](snapshot::diff_files_of) read.
27023×
    pub(crate) fn tree_base_for(
27033×
        &self,
27043×
        change: &Change,
27053×
        mut base: State,
27063×
    ) -> Result<(State, Snapshot)> {
27073×
        let _t = crate::timing::phase("diff: the base's tree");
27083×
        let edited: std::collections::HashSet<NodeId> =
27098×
            change.edits.iter().map(|e| e.node()).collect();
27103×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
27113×
        self.load_graphs_of(&mut base, &nodes)?;
27123×
        let snapshot = Snapshot {
27133×
            tree: base.tree().view(),
27143×
            files: BTreeMap::new(),
27153×
            unrendered: BTreeSet::new(),
27163×
        };
27173×
        Ok((base, snapshot))
27183×
    }
2719
2720
    /// [`Repo::change_base`] with the base already loaded (the working
2721
    /// copy's comes from the state index).
2722239×
    pub(crate) fn render_base_for(
2723239×
        &self,
2724239×
        change: &Change,
2725239×
        mut base: State,
2726239×
    ) -> Result<(State, Snapshot)> {
2727239×
        let _t = crate::timing::phase("diff: render the base");
2728239×
        let edited: std::collections::HashSet<NodeId> =
2729482×
            change.edits.iter().map(|e| e.node()).collect();
2730239×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2731239×
        self.load_graphs_of(&mut base, &nodes)?;
2732239×
        let snapshot = {
2733239×
            let _t = crate::timing::phase("diff:   of which materialize");
2734239×
            base.materialize_nodes(&edited)
2735
        };
2736239×
        Ok((base, snapshot))
2737239×
    }
2738
}
2739
27400×
fn remove_any(path: &Path) -> std::io::Result<()> {
27410×
    let m = fs::symlink_metadata(path)?;
27420×
    if m.is_dir() {
27430×
        fs::remove_dir_all(path)
2744
    } else {
27450×
        fs::remove_file(path)
2746
    }
27470×
}
2748
27495×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
27505×
    let mut perms = fs::metadata(path)?.permissions();
27515×
    perms.set_readonly(readonly);
27525×
    fs::set_permissions(path, perms)
27535×
}
2754
2755
#[cfg(unix)]
27565925×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2757
    use std::os::unix::fs::PermissionsExt;
27585925×
    let mut perms = fs::metadata(path)?.permissions();
27595925×
    let mode = perms.mode();
27605925×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
27615925×
    if want != mode {
27624×
        perms.set_mode(want);
27634×
        fs::set_permissions(path, perms)?;
27645921×
    }
27655925×
    Ok(())
27665925×
}
2767
#[cfg(not(unix))]
2768
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2769
    Ok(())
2770
}
2771
2772
#[cfg(unix)]
277316583×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2774
    use std::os::unix::fs::PermissionsExt;
277516583×
    m.permissions().mode() & 0o111 != 0
277616583×
}
2777
#[cfg(not(unix))]
2778
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2779
    false
2780
}
2781
278213002×
fn op_ref(k: OpKey) -> OpRef {
278313002×
    OpRef {
278413002×
        change: k.0,
278513002×
        index: k.1,
278613002×
    }
278713002×
}
2788
27896070×
fn split_path(path: &str) -> (&str, &str) {
27906070×
    match path.rfind('/') {
27915059×
        Some(i) => (&path[..i], &path[i + 1..]),
27921011×
        None => ("", path),
2793
    }
27946070×
}
2795
2796
/// Whether `rel` is an attributes file (spec §7.6).
279768163×
fn is_attributes(rel: &str) -> bool {
279868163×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
279968163×
}
2800
2801
/// The manifest entry for `rel` when its size and mtime match it outside
2802
/// the racy window.
280324433×
fn stat_cached<'m>(
280424433×
    rel: &str,
280524433×
    meta: &walk::Stat,
280624433×
    cache: Option<&'m prompt::Manifest>,
280724433×
) -> Option<&'m prompt::ManifestEntry> {
280824433×
    let m = cache?;
280919479×
    let e = m.entries.get(rel)?;
281018102×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
281118102×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
281224433×
}
2813
2814
/// Read one working-copy file, or serve it from the stat cache (spec
2815
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2816
/// an opaque file is not read at all (its stored blob stands in), and a
2817
/// text file the manifest recorded equal to a base graph whose key is
2818
/// `key`, the key the base has now, is not read either: equal keys mean
2819
/// equal renderings, so it still equals the base. Touches no repository
2820
/// state, so the walk runs it in parallel; the caller checks that a cached
2821
/// blob is still in the store.
282212232×
fn read_file_entry(
282312232×
    rel: &str,
282412232×
    path: &Path,
282512232×
    meta: &walk::Stat,
282612232×
    cache: Option<&prompt::Manifest>,
282712232×
    key: Option<[u8; 32]>,
282812232×
) -> Result<FsEntry> {
282912232×
    let exec = meta.exec;
283012232×
    let stat = Some((meta.size, meta.mtime_ns));
283112232×
    let mut e = match stat_cached(rel, meta, cache) {
28324247×
        Some(e) if e.blob.is_some() => FsEntry {
28331×
            blob: e.blob,
28341×
            content_hash: Some(e.hash),
28351×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28361×
        },
28374246×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
28384241×
            content_hash: Some(e.hash),
28394241×
            unchanged: true,
28404241×
            graph_key: e.graph,
28414241×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28424241×
        },
28435×
        Some(e) => FsEntry {
28445×
            content_hash: Some(e.hash),
28455×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2846
        },
28477985×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2848
    };
2849
    // The stat the manifest records: taken before the read, so a file that
2850
    // changes meanwhile is read again next time.
285112231×
    e.stat = stat;
285212231×
    Ok(e)
285312232×
}
2854
2855
/// Two maps side by side in key order: each key of either, with its value
2856
/// in each. Linear, with no lookups, for maps of a whole tree.
28572641×
pub(crate) fn join<'a, A, B>(
28582641×
    a: &'a BTreeMap<String, A>,
28592641×
    b: &'a BTreeMap<String, B>,
28602641×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
28612641×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
286235799×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
28632641×
        (None, None) => None,
28642948×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
28655843×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
286624367×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2867330×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2868302×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2869
            std::cmp::Ordering::Equal => {
287023735×
                let (k, va) = a.next()?;
287123735×
                let (_, vb) = b.next()?;
287223735×
                Some((k, Some(va), Some(vb)))
2873
            }
2874
        },
287535799×
    })
28762641×
}
2877
2878
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2879
/// lookups.
28801343×
pub(crate) fn missing_from<'a, A, B>(
28811343×
    a: &'a BTreeMap<String, A>,
28821343×
    b: &BTreeMap<String, B>,
28831343×
) -> Vec<(&'a String, &'a A)> {
28841343×
    let mut keys = b.keys().peekable();
28851343×
    a.iter()
28869205×
        .filter(|(k, _)| {
288717694×
            while keys.next_if(|kb| *kb < *k).is_some() {}
28889205×
            keys.peek() != Some(k)
28899205×
        })
28901343×
        .collect()
28911343×
}