OXYGENHUB

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

1865 of 2098 lines run, 436 of 705 functions · run #350 on proposal/125 · 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.
752529×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762529×
    let Some(url) = &config.storage_url else {
772524×
        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×
    )?)
1002529×
}
101
102173×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103173×
    Err(RepoError::Msg(s.into()))
104173×
}
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.
1684365×
pub(crate) fn name_file(name: &str) -> String {
1694365×
    name.replace('%', "%25").replace('/', "%2F")
1704365×
}
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
1777523×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1787523×
    Ok(crate::durable::write_atomic(path, data)?)
1797523×
}
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
1953032×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1963032×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1973032×
    fs::write(&tmp, data)?;
1983032×
    fs::rename(&tmp, path)?;
1993032×
    Ok(())
2003032×
}
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 {
24022882×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
24122882×
        FsEntry {
24222882×
            kind,
24322882×
            exec,
24422882×
            content: std::sync::Arc::new(content),
24522882×
            blob: None,
24622882×
            content_hash: None,
24722882×
            unchanged: false,
24822882×
            graph_key: None,
24922882×
            stat: None,
25022882×
        }
25122882×
    }
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/`.
3177838×
pub fn default_home() -> PathBuf {
3187838×
    if let Ok(h) = std::env::var("OXY_HOME") {
3197832×
        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")
3327838×
}
333
3342530×
pub fn default_keys_dir() -> PathBuf {
3352530×
    default_home().join("keys")
3362530×
}
337
3385058×
pub fn default_user_config() -> PathBuf {
3395058×
    default_home().join("config.toml")
3405058×
}
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
354243×
    pub fn init(root: &Path) -> Result<Repo> {
355243×
        let mut id = [0u8; 16];
356243×
        rand::rngs::OsRng.fill_bytes(&mut id);
357243×
        Self::init_with_id(root, id)
358243×
    }
359
360
    /// Initialize a repository with a given repository ID (clones share the
361
    /// ID of their origin, spec §14.4).
362501×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
363501×
        Self::init_on(root, id, None)
364501×
    }
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`.
380516×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
381516×
        fs::create_dir_all(root)?;
382516×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
383516×
        let oxy = root.join(OXY_DIR);
384516×
        if oxy.exists() {
3851×
            return fail(format!("{} is already an oxy repository", root.display()));
386515×
        }
387515×
        fs::create_dir_all(oxy.join("ops"))?;
388515×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
389515×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
390515×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
391515×
        if let Some(url) = storage {
3923×
            config.set("storage.url", url)?;
393512×
        }
394515×
        config.save(&oxy.join("config"))?;
395515×
        let workspace = WorkspaceId::random();
396515×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
397515×
        let store = open_objects(&oxy, &config)?;
398514×
        let repo = Repo {
399514×
            acceptor: None,
400514×
            keyless_key: Default::default(),
401514×
            last_change: Default::default(),
402514×
            at_op: None,
403514×
            head_seen: Default::default(),
404514×
            walked_dirs: Default::default(),
405514×
            listed_dirs: Default::default(),
406514×
            git_export_skipped: Default::default(),
407514×
            manifest_cache: Default::default(),
408514×
            listing_cache: Default::default(),
409514×
            untracked_nested: Default::default(),
410514×
            skipped_large: Default::default(),
411514×
            root,
412514×
            oxy,
413514×
            store,
414514×
            workspace,
415514×
            bare: false,
416514×
            keys_dir: default_keys_dir(),
417514×
            platform: crate::portable::Platform::current(),
418514×
            user_config: default_user_config(),
419514×
            config,
420514×
        };
421514×
        repo.register_workspace(&workspace, &repo.root)?;
422
423514×
        let wc = repo.new_working_copy(vec![], "");
424514×
        let wc_hash = repo.store.put_change(&wc)?;
425514×
        let mut view = View::default();
426514×
        view.bookmarks.insert(
427514×
            repo.config.bookmark.clone(),
428514×
            repo.store.put_state(&StateObject::new(vec![]))?,
429
        );
430514×
        view.workspaces.insert(workspace, wc_hash);
431514×
        repo.record_op(&[], "oxy init", view)?;
432512×
        Ok(repo)
433516×
    }
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
5083663×
    pub fn is_unbound(&self) -> bool {
5093663×
        self.oxy.join(UNBOUND_MARKER).is_file()
5103663×
    }
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`).
52678×
    pub fn is_bare(&self) -> bool {
52778×
        self.bare
52878×
    }
529
530
    /// Open the repository containing `start` (searching upwards).
5311974×
    pub fn open(start: &Path) -> Result<Repo> {
5321974×
        let start = start.canonicalize()?;
5331974×
        let mut dir: Option<&Path> = Some(&start);
5341974×
        while let Some(d) = dir {
5351974×
            let oxy = d.join(OXY_DIR);
5361974×
            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);
5731965×
            }
5741965×
            if oxy.is_dir() {
5751965×
                let format = fs::read_to_string(oxy.join("format"))?;
5761965×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5771965×
                let bare = oxy.join(BARE_MARKER).is_file();
5781965×
                let workspace = if bare {
579148×
                    WorkspaceId::ZERO
580
                } else {
5811817×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5821817×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
583
                };
5841965×
                let store = open_objects(&oxy, &config)?;
5851965×
                let mut repo = Repo {
5861965×
                    acceptor: None,
5871965×
                    keyless_key: Default::default(),
5881965×
                    last_change: Default::default(),
5891965×
                    at_op: None,
5901965×
                    head_seen: Default::default(),
5911965×
                    walked_dirs: Default::default(),
5921965×
                    listed_dirs: Default::default(),
5931965×
                    git_export_skipped: Default::default(),
5941965×
                    manifest_cache: Default::default(),
5951965×
                    listing_cache: Default::default(),
5961965×
                    untracked_nested: Default::default(),
5971965×
                    skipped_large: Default::default(),
5981965×
                    root: d.to_path_buf(),
5991965×
                    oxy,
6001965×
                    store,
6011965×
                    workspace,
6021965×
                    bare,
6031965×
                    keys_dir: default_keys_dir(),
6041965×
                    platform: crate::portable::Platform::current(),
6051965×
                    user_config: default_user_config(),
6061965×
                    config,
6071965×
                };
6081965×
                if !bare {
6091817×
                    repo.apply_workspace_bookmark();
6101817×
                }
6111965×
                if format == FORMAT1_LINE {
6121×
                    repo.migrate_format1()?;
6131964×
                } else if format != FORMAT_LINE {
6140×
                    return fail(format!("unsupported repository format: {}", format.trim()));
6151964×
                }
6161965×
                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
        ))
6241974×
    }
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).
669702×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
670702×
        self.store
671702×
            .expire_retired(crate::store::RETIRED_FOR, &mut |_| {})?;
672702×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6730×
            self.store.pack_loose()?;
6740×
            self.store.merge_packs()?;
675702×
        }
676702×
        Ok(())
677702×
    }
678
679
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6803369×
    pub fn id(&self) -> Result<[u8; 16]> {
6813369×
        if self.is_unbound() {
68219×
            return Ok([0; 16]);
6833350×
        }
6843350×
        let path = self.oxy.join("id");
6853350×
        match fs::read_to_string(&path) {
6863350×
            Ok(h) => hex::decode(h.trim())
6873350×
                .ok()
6883350×
                .and_then(|v| v.try_into().ok())
6893350×
                .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
        }
6983369×
    }
699
70062×
    pub fn root(&self) -> &Path {
70162×
        &self.root
70262×
    }
703535×
    pub fn store(&self) -> &Store {
704535×
        &self.store
705535×
    }
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
730180×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
731180×
        let dir = dir.into();
732180×
        self.keys_dir = dir.join("keys");
733180×
        self.user_config = dir.join("config.toml");
734180×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
735180×
            self.config = c;
736180×
        }
737180×
        self.apply_workspace_bookmark();
738180×
        self
739180×
    }
740
741
    /// The workspace's current bookmark (spec §10.1) overrides the
742
    /// configured default when `oxy bookmark switch` has recorded one.
7432006×
    fn apply_workspace_bookmark(&mut self) {
7442006×
        if let Ok(b) = fs::read_to_string(
7452006×
            self.oxy
7462006×
                .join("workspaces")
7472006×
                .join(self.workspace.to_hex())
7482006×
                .join("bookmark"),
7492006×
        ) {
75035×
            let b = b.trim();
75135×
            if !b.is_empty() {
75235×
                self.config.bookmark = b.to_string();
75335×
            }
7541971×
        }
7552006×
    }
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
768379×
    pub fn save_config(&self) -> Result<()> {
769379×
        self.config.save(&self.oxy.join("config"))
770379×
    }
771
7724600×
    fn author(&self) -> KeyId {
7734600×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7744600×
    }
775
}
776
777
impl Repo {
7781758×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7791758×
        let mut c = Change {
7801758×
            version: crate::objects::CHANGE_VERSION,
7811758×
            change_id: ChangeId::random(),
7821758×
            deps,
7831758×
            author: self.author(),
7841758×
            hlc: Hlc::now(),
7851758×
            message: message.into(),
7861758×
            tree_ops: vec![],
7871758×
            edits: vec![],
7881758×
            kind: ChangeKind::WorkingCopy,
7891758×
        };
7901758×
        c.normalize();
7911758×
        c
7921758×
    }
793
794
    // ------------------------------------------------------------ operation log
795
79614607×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
79714607×
        if let Some(r) = self.at_op {
7985×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
79914602×
        }
80014602×
        let r = self.head_ref()?;
80114600×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
80214600×
        Ok((r, op))
80314607×
    }
804
80510061×
    pub fn view(&self) -> Result<View> {
80610061×
        Ok(self.head_op()?.1.view)
80710061×
    }
808
8093579×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
8103579×
        self.record_op_undoing(parents, command, view, None)
8113579×
    }
812
813
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
8143582×
    fn record_op_undoing(
8153582×
        &self,
8163582×
        parents: &[ObjectRef],
8173582×
        command: &str,
8183582×
        view: View,
8193582×
        undoes: Option<ObjectRef>,
8203582×
    ) -> Result<ObjectRef> {
8213582×
        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
            );
8253581×
        }
8263581×
        let op = Op {
8273581×
            parents: parents.to_vec(),
8283581×
            hlc: Hlc::now(),
8293581×
            command: command.into(),
8303581×
            view,
8313581×
            workspace: Some(self.workspace),
8323581×
            undoes,
8333581×
        };
8343581×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
835
        // The head is the commit point: everything it names must be on disk first.
8363579×
        let flushing = crate::timing::phase("op: flush the store");
8373579×
        self.store.flush()?;
8383577×
        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.
8443577×
        let _lock = if self.store.is_local() {
8453565×
            Some(self.lock_ops()?)
846
        } else {
84712×
            None
848
        };
8493577×
        let Some(parent) = parents.first() else {
850
            // The first operation (init): there is no head yet.
851554×
            if !self.swap_head(&r, None)? {
8522×
                return fail(format!(
853
                    "{} already holds a repository's operation log",
8542×
                    self.store.backend().describe()
855
                ));
856552×
            }
857552×
            return Ok(r);
858
        };
8593023×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8603023×
        for _ in 0..HEAD_TRIES {
8613023×
            let (current, version) = self.read_head()?;
8623023×
            let to = if current == *parent {
8632999×
                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
            };
8783022×
            if self.swap_head(&to, version.as_ref())? {
8793016×
                return Ok(to);
8800×
            }
881
        }
8820×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8833582×
    }
884
885
    /// The operation head's lock, held only while the head pointer moves.
8863575×
    fn lock_ops(&self) -> Result<FileLock> {
8873575×
        fs::create_dir_all(self.oxy.join("ops"))?;
8883575×
        FileLock::acquire(
8893575×
            self.oxy.join("ops").join("lock"),
8903575×
            "another oxy process holds the operation log",
891
        )
8923575×
    }
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`]).
89614604×
    fn head_ref(&self) -> Result<ObjectRef> {
89714604×
        if let Some(r) = self.head_seen.get() {
89811281×
            return Ok(r);
8993323×
        }
9003323×
        let r = self.read_head()?.0;
9013321×
        self.head_seen.set(Some(r));
9023321×
        Ok(r)
90314604×
    }
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.
912454×
    pub fn refresh(&self) -> Result<()> {
913454×
        self.forget_head();
914454×
        self.store.refresh()?;
915454×
        Ok(())
916454×
    }
917
918
    /// Read the operation head again on next use, as [`Repo::refresh`]
919
    /// does, leaving the packs as they are.
9202217×
    pub(crate) fn forget_head(&self) {
9212217×
        self.head_seen.set(None);
9222217×
    }
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).
9286435×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
9296435×
        if self.store.is_local() {
9306417×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
9316417×
            let r = ObjectRef::from_hex(hex.trim())
9326417×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
9336414×
            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
        }
9546435×
    }
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.
9613589×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
9623589×
        if self.store.is_local() {
9633575×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
9643569×
            self.head_seen.set(Some(*to));
9653569×
            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
        }
9793589×
    }
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 {
100144×
                    ov.cloned()
100245×
                } else if ov == bv {
100326×
                    tv.cloned()
1004
                } else {
100519×
                    match (ov, tv) {
100619×
                        (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,
102118×
            |x, y| {
102218×
                let mut heads = self.store.get_state(x)?.heads;
102318×
                heads.extend(self.store.get_state(y)?.heads);
102418×
                let heads = self.load_state(&heads)?.maximal(&heads);
102518×
                Ok(self.store.put_state(&StateObject::new(heads))?)
102618×
            },
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.
1445229×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1446229×
        if let Some(st) = self.load_state_checkpointed(heads)? {
14474×
            return Ok(st);
1448224×
        }
1449224×
        self.load_state_full(heads)
1450229×
    }
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`].
14561884×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
14571884×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
145831×
            return Ok(st);
14591853×
        }
14601853×
        self.load_state_replayed(heads, State::new_history_only())
14611884×
    }
1462
1463
    /// Build these file graphs in a history-only state.
14642005×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
14652005×
        state
14662005×
            .load_graphs(
14672005×
                nodes,
146854×
                |refs| {
146954×
                    self.read_blobs(refs).map_err(|e| {
14703×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14713×
                    })
147254×
                },
14732292×
                |h| self.change_bytes(h),
1474
            )
14752005×
            .map_err(|e| self.index_damage(e))
14762005×
    }
1477
1478
    /// The tree of `state` as every reader sees it ([`State::view`]), with
1479
    /// the graphs built that it compares: same-path additions with
1480
    /// identical content are one entry, not a name conflict.
14812192×
    pub fn tree_view(&self, state: &mut State) -> Result<crate::tree::TreeView> {
14822192×
        let need = state.unify_candidates();
14832192×
        if !need.is_empty() {
148470×
            self.load_graphs_of(state, &need)?;
14852122×
        }
14862192×
        Ok(state.view())
14872192×
    }
1488
1489
    /// An error building graphs, and when it is a state index found
1490
    /// damaged (a file's history that does not match its hash), the
1491
    /// workspace's state indexes removed: they are rebuilt from history by
1492
    /// the next command.
14934×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
14944×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
14953×
            return e.into();
1496
        };
14972×
        for path in self.state_indexes() {
14982×
            let _ = fs::remove_file(path);
14992×
        }
15001×
        RepoError::Msg(format!(
15011×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
15021×
        ))
15034×
    }
1504
1505
    /// The graphs of `nodes` of a history-only state, built beside it (see
1506
    /// [`State::build_graphs_detached`]).
150777×
    pub fn build_graphs_detached(
150877×
        &self,
150977×
        state: &State,
151077×
        nodes: &[crate::ids::NodeId],
151177×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
151277×
        Ok(state
151377×
            .build_graphs_detached(
151477×
                nodes,
15150×
                |refs| {
15160×
                    self.read_blobs(refs).map_err(|e| {
15170×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15180×
                    })
15190×
                },
152083×
                |h| self.change_bytes(h),
1521
            )
152277×
            .map_err(|e| self.index_damage(e))?
152377×
            .into_iter()
152477×
            .collect())
152577×
    }
1526
1527
    /// The contents of texts [`State::single_text`] gave: blobs read in
1528
    /// one go, inline ones from their changes.
1529389×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1530
        use crate::objects::TextRef;
1531389×
        let refs: Vec<ObjectRef> = texts
1532389×
            .iter()
15335544×
            .filter_map(|t| match t {
15341×
                TextRef::Blob(r, _, _) => Some(*r),
15355543×
                TextRef::Inline { .. } => None,
15365544×
            })
1537389×
            .collect();
1538389×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1539389×
        let mut out = Vec::with_capacity(texts.len());
15405544×
        for t in texts {
15415544×
            let lines = match t {
15421×
                TextRef::Blob(_, count, form) => {
15431×
                    let content = blobs
15441×
                        .next()
15451×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
15461×
                    crate::objects::text_lines(&content, *count, *form)?
1547
                }
15485543×
                TextRef::Inline { change, start, end } => {
15495543×
                    let bytes = self.change_bytes(change)?;
15505543×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
15510×
                        RepoError::Msg("an inline insert lies outside its change".into())
15520×
                    })?;
15535543×
                    crate::objects::inline_lines(range)?
1554
                }
1555
            };
15565544×
            out.push(lines.bytes().to_vec());
1557
        }
1558389×
        Ok(out)
1559389×
    }
1560
1561
    /// Build every graph a history-only state still lacks, making it full.
15622082×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
15632082×
        state
15642082×
            .load_all_graphs(
156516×
                |refs| {
156616×
                    self.read_blobs(refs).map_err(|e| {
15670×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15680×
                    })
156916×
                },
15704384×
                |h| self.change_bytes(h),
1571
            )
15722082×
            .map_err(|e| self.index_damage(e))
15732082×
    }
1574
1575
    /// A change's encoding, for building graphs of its inline inserts. The
1576
    /// last few read are kept: a checkout building graphs a batch at a
1577
    /// time reads the same large changes for every batch, often in turn.
157812302×
    fn change_bytes(
157912302×
        &self,
158012302×
        h: &ChangeHash,
158112302×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
158212302×
        let mut cache = self.last_change.borrow_mut();
158320938×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
15849684×
            let hit = cache.remove(i);
15859684×
            let b = hit.1.clone();
15869684×
            cache.push(hit);
15879684×
            return Ok(b);
15882618×
        }
15892618×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
15900×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
15910×
        })?);
15922618×
        cache.push((*h, b.clone()));
1593
        // The last few, within a memory budget; the newest always stays.
15944199×
        while cache.len() > CHANGE_CACHE_COUNT
15952618×
            || (cache.len() > 1
15967822×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15971581×
        {
15981581×
            cache.remove(0);
15991581×
        }
16002618×
        Ok(b)
160112302×
    }
1602
1603
    /// Load the dependency closure of `heads` change by change.
1604278×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1605278×
        self.load_state_replayed(heads, State::new())
1606278×
    }
1607
16083604×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
16093604×
        let history = state.is_history_only();
16103604×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
16113604×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1612
        {
16133604×
            let _t = crate::timing::phase("load: read and add changes");
16143604×
            let (mut read, mut add, mut fetch) = (
16153604×
                std::time::Duration::ZERO,
16163604×
                std::time::Duration::ZERO,
16173604×
                std::time::Duration::ZERO,
16183604×
            );
161914598×
            while let Some(h) = stack.pop() {
1620
                // A change the state holds brings its history with it.
162110997×
                if !seen.insert(h) || state.contains(&h) {
16222605×
                    continue;
16238392×
                }
16248392×
                let t0 = std::time::Instant::now();
1625
                // A history-only state reads text only for the graphs it
1626
                // builds; either way the hash is the one asked for.
16278392×
                let (c, texts) = if history {
16286881×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
16296880×
                    fetch += t0.elapsed();
16306880×
                    Change::decode_skeleton(&bytes, h)
16316880×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1632
                } else {
16331511×
                    (self.store.get_change(&h)?, Vec::new())
1634
                };
16358389×
                read += t0.elapsed();
16368389×
                stack.extend(c.deps.iter().copied());
16378389×
                let t1 = std::time::Instant::now();
16388389×
                state.add_known(h, c, texts);
16398389×
                add += t1.elapsed();
1640
            }
16413601×
            crate::timing::record("load:   of which reading", read);
16423601×
            crate::timing::record("load:     of which fetching", fetch);
16433601×
            crate::timing::record("load:   of which applying", add);
1644
        }
16453601×
        let _t = crate::timing::phase("load: validate");
16463601×
        state.validate()?;
16473601×
        Ok(state)
16483604×
    }
1649
16502517×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
16512517×
        if self.bare {
16522×
            return fail("this is a bare repository: it has no working copy");
16532515×
        }
16542515×
        let view = self.view()?;
16552515×
        let h = *view
16562515×
            .workspaces
16572515×
            .get(&self.workspace)
16582515×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
16592514×
        Ok((h, self.store.get_change(&h)?))
16602517×
    }
1661
1662
    /// Heads of a bookmark's state (spec §10.1).
16631899×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
16641899×
        match view.bookmarks.get(bookmark) {
16651899×
            Some(st) => Ok(self.store.get_state(st)?.heads),
16660×
            None => Ok(vec![]),
1667
        }
16681899×
    }
1669
1670543×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1671543×
        self.heads_of(&self.view()?, &self.config.bookmark)
1672543×
    }
1673
1674
    // ------------------------------------------------------------ blobs
1675
1676412×
    fn blob_for(content: &[u8]) -> Blob {
1677412×
        Blob::of(content)
1678412×
    }
1679
1680254×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1681254×
        Self::blob_for(content).hash()
1682254×
    }
1683
1684156×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1685199×
        for c in crate::chunk::chunks(content) {
1686199×
            self.store.put_chunk(c)?;
1687
        }
1688156×
        Ok(self
1689156×
            .store
1690156×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1691156×
    }
1692
1693
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1694
    /// all their chunks, are read in parallel; a blob the store lacks goes
1695
    /// through [`Repo::read_blob`], which may fetch it lazily.
1696463×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1697463×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1698463×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
169980×
            blobs.push(match got {
170075×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
17010×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
17025×
                Err(crate::store::StoreError::NotFound(_)) => None,
17030×
                Err(e) => return Err(e.into()),
1704
            });
1705
        }
1706463×
        let chunk_refs: Vec<ObjectRef> = blobs
1707463×
            .iter()
1708463×
            .flatten()
1709463×
            .flat_map(|b| b.chunks.iter().copied())
1710463×
            .collect();
1711463×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1712463×
        let mut out = Vec::with_capacity(refs.len());
1713463×
        for (r, blob) in refs.iter().zip(blobs) {
171480×
            match blob {
17155×
                None => out.push(self.read_blob(r)?),
171675×
                Some(b) => {
171775×
                    let mut content = Vec::with_capacity(b.length as usize);
1718114×
                    for c in &b.chunks {
1719114×
                        match chunks.next() {
1720114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
17210×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
17220×
                            Some(Err(e)) => return Err(e.into()),
17230×
                            None => return fail("chunk list ended early"),
1724
                        }
1725
                    }
172675×
                    out.push(content);
1727
                }
1728
            }
1729
        }
1730458×
        Ok(out)
1731463×
    }
1732
1733
    /// Read a blob's content, fetching it from the remote that withheld it
1734
    /// when it is lazily absent (spec §13.5).
1735115×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1736115×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
17374×
            self.fetch_lazy_blob(r)?;
1738111×
        }
1739115×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1740110×
        let mut out = Vec::with_capacity(blob.length as usize);
1741137×
        for c in &blob.chunks {
1742137×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1743
        }
1744110×
        Ok(out)
1745115×
    }
1746
1747
    // ------------------------------------------------------------ working copy
1748
1749
    /// Attributes from the `.oxyattributes` files in the working directory.
17502×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1751
        // Nested repositories and ignored paths are left out, as in a walk.
17528×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
17532×
        let files: Vec<(String, Vec<u8>)> = listing
17542×
            .files
17552×
            .into_iter()
17562×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
17572×
            .collect();
17582×
        crate::attributes::Attributes::from_files(
17592×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1760
        )
17612×
    }
1762
1763
    /// Folders holding a repository of their own that the last look at the
1764
    /// working copy left out, not being subrepos (oxygen#43).
176529×
    pub fn untracked_nested(&self) -> Vec<String> {
176629×
        self.untracked_nested.borrow().clone()
176729×
    }
1768
1769
    /// New untracked files the last snapshot left out for being larger than
1770
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
177133×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
177233×
        self.skipped_large.borrow().clone()
177333×
    }
1774
1775
    /// Attributes from a materialized state's `.oxyattributes` files.
17763×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
17776×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
17786×
            match &f.content {
17796×
                FileContent::Text { bytes, .. }
17806×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1781
                {
17820×
                    Some((p.as_str(), bytes.as_slice()))
1783
                }
17846×
                _ => None,
1785
            }
17866×
        }))
17873×
    }
1788
1789
    /// Store a blob, raw when the path is `nocompress`.
1790137×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1791137×
        if !nocompress {
1792135×
            return self.store_blob(content);
17932×
        }
17942×
        for c in crate::chunk::chunks(content) {
17952×
            self.store.put_chunk_nocompress(c)?;
1796
        }
17972×
        Ok(self
17982×
            .store
17992×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1800137×
    }
1801
1802
    /// This workspace's state index (oxygen#41): its working copy's base,
1803
    /// saved so a snapshot reads it rather than replaying history.
1804
    /// The state index of the state with these heads: this workspace keeps
1805
    /// the last few it used, named by their heads, so moving between two
1806
    /// states finds both.
18072598×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
18082598×
        let mut heads = heads.to_vec();
18092598×
        heads.sort();
18102598×
        let mut h = blake3::Hasher::new();
18112620×
        for c in &heads {
18122620×
            h.update(&c.0);
18132620×
        }
18142598×
        self.oxy.join("index").join(format!(
18152598×
            "{}{}",
18162598×
            self.state_index_prefix(),
18172598×
            &h.finalize().to_hex()[..16]
18182598×
        ))
18192598×
    }
1820
18215106×
    fn state_index_prefix(&self) -> String {
18225106×
        format!("state-{}-", self.workspace.to_hex())
18235106×
    }
1824
1825
    /// This workspace's state indexes, newest first.
18262508×
    fn state_indexes(&self) -> Vec<PathBuf> {
18272508×
        let prefix = self.state_index_prefix();
18282508×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
18292508×
            .into_iter()
18302508×
            .flatten()
18312508×
            .flatten()
18322508×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
18332508×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
18342508×
            .collect();
18352508×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
18362508×
        found.into_iter().map(|(_, p)| p).collect()
18372508×
    }
1838
1839
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1840
    /// from this workspace's state index when it holds that history: every
1841
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1842
    /// is loaded from history and indexed for next time.
18432170×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
18442170×
        if let Some((st, heads)) = self.read_state_index(deps) {
18451749×
            let mut have = st.maximal(deps);
18461749×
            have.sort();
18471749×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1848
                // Re-encoding reads every history: one found damaged is
1849
                // left to the build that reads it, which reports it.
1850
                #[cfg(test)]
1851163×
                if let Some(mine) = st.write_index() {
1852158×
                    assert_eq!(
1853158×
                        Some(mine),
1854158×
                        self.load_state_history(deps)?.write_index(),
1855
                        "a state index holds the state history gives"
1856
                    );
18575×
                }
1858276×
                return Ok(st);
18591473×
            }
1860
            // An index a few changes behind (a commit, a pull since): add
1861
            // what it lacks, as long as all it holds is history of `deps`.
1862
            // Anything amiss (a change beyond a shallow boundary) takes the
1863
            // long way instead.
18641473×
            let (indexed, started) = (st.len(), std::time::Instant::now());
18651473×
            if let Ok(st) = self.load_state_replayed(deps, st) {
18661472×
                let mut all = deps.to_vec();
18671472×
                all.extend(heads.iter().copied());
18681472×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
18691472×
                within.sort();
18701472×
                want.sort();
18711472×
                if within == want {
1872
                    #[cfg(test)]
1873812×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1874
                    // Writing the index costs far more than replaying a
1875
                    // few small changes: it is rewritten once it falls
1876
                    // behind, or when replaying took long (large changes).
18771470×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
18781470×
                        || started.elapsed() > INDEX_REPLAY_TIME
18793×
                    {
18803×
                        self.write_state_index(deps, &st);
18811467×
                    }
18821470×
                    return Ok(st);
18832×
                }
18841×
            }
1885421×
        }
1886424×
        let st = self.load_state_history(deps)?;
1887424×
        self.write_state_index(deps, &st);
1888424×
        Ok(st)
18892170×
    }
1890
1891
    /// Two history-only states hold the same changes and render the same
1892
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1893
    /// the checkpoint's graphs as the bases of its files' histories.
1894
    #[cfg(test)]
1895812×
    fn assert_same_state(&self, a: &State, b: &State) {
18961624×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1897812×
        assert_eq!(ids(a), ids(b), "the same changes");
18981624×
        let files = |s: &State| {
18991624×
            let mut s = s.clone();
19001624×
            self.load_all_graphs(&mut s).unwrap();
19011624×
            s.materialize().files
19021624×
        };
1903812×
        assert_eq!(files(a), files(b), "the same files");
1904812×
    }
1905
1906
    /// The state index file: its heads, a hash of its changes block and one
1907
    /// of the rest, then the body [`State::write_index`] gives, whose first
1908
    /// block is the changes. Hashed in two parts so the log can read and
1909
    /// check the changes alone.
1910
    /// The index of `deps` if there is one, else the newest, which the
1911
    /// caller may bring up to date.
19122170×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1913
        use std::io::Read;
19142170×
        let _t = crate::timing::phase("load: state index");
19152170×
        let exact = self.state_index_path(deps);
19162170×
        let reading = crate::timing::phase("load:   of which reading the file");
19172170×
        let mut f = match fs::File::open(&exact) {
1918276×
            Ok(f) => {
1919
                // Used now: the newest, so the last to be dropped.
1920276×
                let _ = fs::File::options()
1921276×
                    .write(true)
1922276×
                    .open(&exact)
1923276×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1924276×
                f
1925
            }
19261894×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1927
        };
19281749×
        let total = f.metadata().ok()?.len();
19291749×
        let mut word = [0u8; 4];
19301749×
        f.read_exact(&mut word).ok()?;
19311749×
        let n = u32::from_le_bytes(word) as usize;
19321749×
        let mut head = vec![0u8; 32 * n + 64 + 8];
19331749×
        f.read_exact(&mut head).ok()?;
19341749×
        let heads: Vec<ChangeHash> = head[..32 * n]
19351749×
            .chunks_exact(32)
19361749×
            .map(|c| ObjectRef(c.try_into().unwrap()))
19371749×
            .collect();
19381749×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
19391749×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
19401749×
        let at = (4 + head.len()) as u64;
19411749×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
19420×
            return None;
19431749×
        }
1944
        // The front only: the files' histories after it are read, each
1945
        // checked by its own hash, when a command builds that file.
19461749×
        let mut front = vec![0u8; front_len as usize];
19471749×
        f.read_exact(&mut front).ok()?;
19481749×
        drop(reading);
19491749×
        let checking = crate::timing::phase("load:   of which checking the file");
19501749×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
19511749×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
19523498×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
19531749×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
19540×
            return None;
19551749×
        }
19561749×
        drop(checking);
19571749×
        let histories = crate::state::Histories::File(
19581749×
            std::sync::Arc::new(f),
19591749×
            at + front_len,
19601749×
            total - at - front_len,
19611749×
        );
19621749×
        Some((State::read_index_front(&front, histories).ok()?, heads))
19632170×
    }
1964
1965
    /// The changes of this workspace's state index (the closure of its
1966
    /// heads), read without the rest of the index.
1967
    #[allow(clippy::type_complexity)]
1968184×
    pub(crate) fn read_state_index_changes(
1969184×
        &self,
1970184×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1971
        use std::io::Read;
1972184×
        let _t = crate::timing::phase("load: state index changes");
1973184×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1974167×
        let mut word = [0u8; 4];
1975167×
        f.read_exact(&mut word).ok()?;
1976167×
        let n = u32::from_le_bytes(word) as usize;
1977
        // Heads, the two sums, the front's length, then the changes block.
1978167×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1979167×
        f.read_exact(&mut head).ok()?;
1980167×
        let heads: Vec<ChangeHash> = head[..32 * n]
1981167×
            .chunks_exact(32)
1982167×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1983167×
            .collect();
1984167×
        let sum = &head[32 * n..32 * n + 32];
1985167×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1986167×
        let mut changes = vec![0u8; 4 + len];
1987167×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1988167×
        f.read_exact(&mut changes[4..]).ok()?;
1989167×
        let checking = crate::timing::phase("load:   of which checking");
1990167×
        let mut h = blake3::Hasher::new();
1991167×
        h.update_rayon(&changes);
1992167×
        if h.finalize().as_bytes() != sum {
19930×
            return None;
1994167×
        }
1995167×
        drop(checking);
1996167×
        let _decoding = crate::timing::phase("load:   of which decoding");
1997167×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
1998184×
    }
1999
2000
    /// Save `st`, the history-only state of `deps`, as this workspace's
2001
    /// state index; quietly nothing when it cannot be (it is only a cache).
2002428×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
2003428×
        let _t = crate::timing::phase("write: state index");
2004428×
        let encoding = crate::timing::phase("write:   of which encoding");
2005428×
        let Some(body) = st.write_index() else {
20060×
            return;
2007
        };
2008428×
        drop(encoding);
2009
        #[cfg(test)]
2010238×
        assert_eq!(
2011238×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
2012238×
            Some(body.clone()),
2013
            "a state index reads back as written"
2014
        );
2015428×
        let mut heads = st.maximal(deps);
2016428×
        heads.sort();
2017428×
        let mut w = crate::flat::Writer::default();
2018428×
        w.count(heads.len());
2019428×
        for h in &heads {
202017×
            w.object(h);
202117×
        }
2022
        // The body is the front's length, the front, then the files'
2023
        // histories, which carry their own hashes: the sums cover the
2024
        // front's changes block and the rest of the front.
2025428×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
2026428×
        let front = &body[8..8 + front_len];
2027428×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
2028856×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
2029428×
        w.fixed(&sum(&front[..split]));
2030428×
        w.fixed(&sum(&front[split..]));
2031428×
        w.fixed(&body);
2032428×
        let path = self.state_index_path(&heads);
2033428×
        let _ = fs::create_dir_all(self.oxy.join("index"));
2034428×
        let _ = write_cache(&path, &w.0);
2035
        // The last two used: the index of a state moved away from stays for
2036
        // a move back. Older ones (and the unnamed one of before) go.
2037428×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
20381×
            let _ = fs::remove_file(old);
20391×
        }
2040428×
        let _ = fs::remove_file(
2041428×
            self.oxy
2042428×
                .join("index")
2043428×
                .join(format!("state-{}", self.workspace.to_hex())),
2044428×
        );
2045428×
    }
2046
20476×
    fn locks_dir(&self) -> PathBuf {
20486×
        self.oxy.join("locks")
20496×
    }
2050
2051
    /// Whether `path` is locked locally for editing (spec §18, advisory).
20523×
    pub fn is_locked(&self, path: &str) -> bool {
20533×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
20543×
    }
2055
2056
    /// Take the advisory local lock on a `lockable` file and make it writable.
20572×
    pub fn lock_path(&self, path: &str) -> Result<()> {
20582×
        let attrs = self.disk_attributes();
20592×
        if !attrs.lookup(path).lockable {
20601×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
20611×
        }
20621×
        fs::create_dir_all(self.locks_dir())?;
20631×
        write_atomic(
20641×
            &self.locks_dir().join(path.replace('/', "%2F")),
20651×
            std::process::id().to_string().as_bytes(),
20660×
        )?;
20671×
        set_readonly(&self.root.join(path), false)?;
20681×
        Ok(())
20692×
    }
2070
2071
    /// Release the local lock and make the file read-only again.
20721×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
20731×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
20741×
        if self.root.join(path).exists() {
20751×
            set_readonly(&self.root.join(path), true)?;
20760×
        }
20771×
        Ok(())
20781×
    }
2079
2080
    /// Whether a repository path is inside the sparse filter (spec §17).
208124665×
    pub fn in_scope(&self, path: &str) -> bool {
208224665×
        self.config.sparse_paths.is_empty()
208382×
            || self
208482×
                .config
208582×
                .sparse_paths
208682×
                .iter()
208799×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
208824665×
    }
2089
20901×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
20911×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
20921×
    }
2093
2094
    /// Walk the working copy; with a manifest, a file whose size and mtime
2095
    /// match it is not read: an opaque file yields its known blob, and a
2096
    /// text file whose recorded graph key equals its base graph's key in
2097
    /// `keys` (path → key) is marked unchanged; other text files are read
2098
    /// but keep their known hash. Files modified within two seconds of the
2099
    /// manifest are never trusted (a racy stat).
2100
    ///
2101
    /// `.oxyattributes` files are always read, since their content is
2102
    /// needed; and when any of them is not known unchanged (added, removed,
2103
    /// edited, or changed in the base), no text file is taken as unchanged,
2104
    /// because attributes decide how a file compares with the base.
2105
    ///
2106
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2107
    /// (the base state's files) that exists on disk is included even when
2108
    /// an ignore rule matches it, as in Git.
21091391×
    fn walk_working_copy_with(
21101391×
        &self,
21111391×
        cache: Option<&prompt::Manifest>,
21121391×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
21131391×
        keys: Option<&KeyOf>,
21141391×
    ) -> Result<BTreeMap<String, FsEntry>> {
2115
        let mut out: BTreeMap<String, FsEntry>;
21161391×
        let sparse = &self.config.sparse_paths;
21179264×
        let in_scope = |p: &str| {
21189264×
            sparse.is_empty()
21197×
                || sparse
21207×
                    .iter()
21217×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
21229264×
        };
21231391×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2124
        let walk::Listing {
21251391×
            files,
21261391×
            symlinks,
21271391×
            nested,
21281391×
            dirs,
21291391×
        } = match self.listing_cache.take() {
2130195×
            Some(l) => l,
2131
            // Ignore rules apply to untracked paths only, so the base's
2132
            // files are not matched against them (an added file is: a rule
2133
            // written after it was snapshotted leaves it out again).
21349276×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2135
        };
2136
        // A new file larger than the limit is left out and named, not taken
2137
        // in unseen (oxygen#98): a build's output or a downloaded image
2138
        // would otherwise be stored by the next status, kept by the
2139
        // operation log. Files tracked, or already in the working copy, stay.
21401391×
        let limit = self.config.max_new_file;
21411391×
        let mut skipped = Vec::new();
21421391×
        let files: Vec<_> = files
21431391×
            .into_iter()
214412292×
            .filter(|(rel, _, meta)| {
214512292×
                let new = !tracked.contains_key(rel)
21463167×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
214712292×
                if limit > 0 && new && meta.size > limit {
21483×
                    skipped.push((rel.clone(), meta.size));
21493×
                    return false;
215012289×
                }
215112289×
                true
215212292×
            })
21531391×
            .collect();
21541391×
        *self.skipped_large.borrow_mut() = skipped;
21551391×
        let keys = keys.filter(|k| {
215612277×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
21571388×
            let attrs_unchanged =
21581388×
                files
21591388×
                    .iter()
216012258×
                    .filter(|(r, _, _)| is_attributes(r))
21611388×
                    .all(|(rel, _, meta)| {
21629×
                        stat_cached(rel, meta, cache)
21639×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
21649×
                    });
21651388×
            let none_removed = tracked
21661388×
                .keys()
21679216×
                .filter(|r| is_attributes(r))
21681388×
                .all(|r| on_disk.contains(r.as_str()));
21691388×
            attrs_unchanged && none_removed
21701388×
        });
21711391×
        *self.walked_dirs.borrow_mut() =
21721391×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
21731391×
        drop(walk_phase);
21741391×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2175
        // Reading files is most of a walk's cost; do it in parallel.
2176
        {
2177
            use rayon::prelude::*;
21781391×
            let mut read: Vec<(String, FsEntry)> = files
21791391×
                .par_iter()
218012289×
                .map(|(rel, path, meta)| {
2181
                    // A key is worked out only for a file the manifest
2182
                    // knows with the same stat and a key of its own.
218312289×
                    let key = keys
218412289×
                        .filter(|_| !is_attributes(rel))
218512289×
                        .filter(|_| {
218612249×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
218712249×
                        })
218812289×
                        .and_then(|k| k(rel));
218912289×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
219012289×
                })
21911391×
                .collect::<Result<Vec<_>>>()?;
219212287×
            for (rel, e) in read.iter_mut() {
2193
                // A cached blob the store lost (gc, a partial clone): read the file after all.
219412287×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
21950×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
21960×
                    e.blob = None;
219712287×
                }
2198
            }
2199
            // The listing is in path order, so the map is built without
2200
            // searching.
22011390×
            out = read.into_iter().collect();
22021390×
            for (rel, target) in symlinks {
22032×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
22042×
            }
2205
        }
22061390×
        drop(_read_phase);
22071390×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2208
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2209
        // already tracked as subrepo nodes, they contribute their pin;
2210
        // unregistered ones are left alone.
22111390×
        let modules = self.modules_on_disk();
22121390×
        let removed = self.removed_subrepos();
22131390×
        for rel in &removed {
22143×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
22151×
                self.clear_removed_subrepo(rel);
22162×
            }
2217
        }
22181390×
        let mut untracked_nested = Vec::new();
22191390×
        for dir in nested {
222039×
            let rel = self.rel_path(&dir);
222139×
            if !self.in_scope(&rel) || removed.contains(&rel) {
22223×
                continue;
222336×
            }
222436×
            let registered = modules.entries.get(&rel);
222536×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2226
            {
22271×
                untracked_nested.push(rel);
22281×
                continue;
222935×
            }
223035×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
223135×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2232
        }
22331390×
        untracked_nested.sort();
22341390×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2235
        // Tracked paths the ignore rules hid.
22361390×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
223777×
            if !self.in_scope(rel) {
223810×
                continue;
223967×
            }
224067×
            let path = self.root.join(rel);
224167×
            if *kind == NodeKind::Subrepo {
22424×
                if removed.contains(rel) {
22432×
                    continue;
22442×
                }
22452×
                let present =
22462×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
22472×
                if present {
22480×
                    let pin = subrepos::read_pin(
22490×
                        &path,
22500×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
22510×
                    )?;
22520×
                    out.insert(
22530×
                        rel.clone(),
22540×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2255
                    );
22562×
                } else if let Some(b) = blob {
22572×
                    // Not cloned (or emptied): the pin stays as recorded, as a
22582×
                    // Git gitlink does when its directory is absent.
22592×
                    out.insert(
22602×
                        rel.clone(),
22612×
                        FsEntry {
22622×
                            blob: Some(*b),
22632×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
22642×
                        },
22652×
                    );
22662×
                }
22672×
                continue;
226863×
            }
226963×
            let Ok(meta) = fs::symlink_metadata(&path) else {
227063×
                continue;
2271
            };
22720×
            let ft = meta.file_type();
22730×
            if ft.is_symlink() {
22740×
                let target = fs::read_link(&path)?;
22750×
                out.insert(
22760×
                    rel.clone(),
22770×
                    FsEntry::new(
22780×
                        NodeKind::Symlink,
2279
                        false,
22800×
                        target.to_string_lossy().as_bytes().to_vec(),
2281
                    ),
2282
                );
22830×
            } else if ft.is_file() {
22840×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
22850×
                out.insert(rel.clone(), e);
22860×
            }
2287
        }
22881390×
        Ok(out)
22891391×
    }
2290
2291
    /// The entry for one regular file, read or served from the stat cache.
22920×
    fn file_entry(
22930×
        &self,
22940×
        rel: &str,
22950×
        path: &Path,
22960×
        meta: &walk::Stat,
22970×
        cache: Option<&prompt::Manifest>,
22980×
    ) -> Result<FsEntry> {
22990×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
23000×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
23010×
            e.content = std::sync::Arc::new(fs::read(path)?);
23020×
            e.blob = None;
23030×
        }
23040×
        Ok(e)
23050×
    }
2306
2307
    /// The non-directory paths of a snapshot with their kinds, for the
2308
    /// walker's `tracked` set.
23092×
    pub(crate) fn tracked_kinds(
23102×
        snapshot: &Snapshot,
23112×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
23122×
        snapshot
23132×
            .files
23142×
            .iter()
231512×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
23168×
            .map(|(p, f)| {
23178×
                let blob = match &f.content {
23184×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
23194×
                    _ => None,
2320
                };
23218×
                (p.clone(), (f.kind, blob))
23228×
            })
23232×
            .collect()
23242×
    }
2325
2326
    /// A path under the root as a `/`-separated relative string.
232786×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
232886×
        path.strip_prefix(&self.root)
232986×
            .unwrap_or(path)
233086×
            .components()
2331150×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
233286×
            .collect::<Vec<_>>()
233386×
            .join("/")
233486×
    }
2335
}
2336
2337
impl Repo {
2338
    /// Changes reachable from the bookmark and the working copy, newest first.
2339102×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
2340102×
        let heads = self.bookmark_heads()?;
2341102×
        if self.bare {
23421×
            return self.log_state(&heads);
2343101×
        }
2344101×
        let (wc_hash, wc) = self.working_copy()?;
2345101×
        let mut all = heads.clone();
2346101×
        all.push(wc_hash);
2347101×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
2348101×
        let mut entries: Vec<LogEntry> = Vec::new();
2349
        // A shallow clone knows changes beyond its boundary from a
2350
        // checkpoint's metadata only: its log comes from the state.
2351101×
        let metas = if self.is_shallow() {
23521×
            self.load_state_history(&all)?
23531×
                .changes()
23549×
                .map(|(h, m)| (*h, m.clone()))
23551×
                .collect()
2356
        } else {
2357
            // The working copy's change is in hand, and is never in the
2358
            // state index: its metadata is not looked up again.
2359100×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
2360100×
            below.extend(wc.deps.iter().copied());
2361100×
            let _t = crate::timing::phase("log: metadata");
2362100×
            let mut metas = self.metas_of(&below)?;
2363349×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
2364100×
                // First, where the log puts it, so the order may hold.
2365100×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
2366100×
            }
2367100×
            metas
2368
        };
2369101×
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2370458×
            hash: h,
2371458×
            change: meta,
2372458×
            is_working_copy: h == wc_hash,
2373458×
            is_head: head_set.contains(&h),
2374458×
        }));
2375101×
        let _sorting = crate::timing::phase("log: sort");
2376
        // The hash makes the order total, so an unstable sort gives the same.
2377
        // From the state index the order already holds (oxygen#94).
2378816×
        let order = |a: &LogEntry, b: &LogEntry| {
2379816×
            b.is_working_copy
2380816×
                .cmp(&a.is_working_copy)
2381816×
                .then(crate::state::log_order(
2382816×
                    (&a.hash, &a.change.hlc),
2383816×
                    (&b.hash, &b.change.hlc),
2384
                ))
2385816×
        };
2386223×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
238754×
            entries.sort_unstable_by(order);
238854×
        }
2389101×
        Ok(entries)
2390102×
    }
2391
2392
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2393
    /// count, for paginated views.
23940×
    pub fn log_window(
23950×
        &self,
23960×
        heads: &[ChangeHash],
23970×
        offset: usize,
23980×
        limit: usize,
23990×
    ) -> Result<(Vec<LogEntry>, usize)> {
24000×
        let all = self.log_state(heads)?;
24010×
        let total = all.len();
24020×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
24030×
    }
2404
2405
    /// The log of the state with these heads, newest first, with no working
2406
    /// copy involved (for hosted repositories and any explicit state).
240710×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2408
        // The log needs change metadata only: neither graphs nor the tree.
240910×
        if self.is_shallow() {
24100×
            return Ok(self.log_of(&self.load_state_history(heads)?));
241110×
        }
241210×
        let metas = self.metas_of(heads)?;
241310×
        let depended: BTreeSet<ChangeHash> = metas
241410×
            .iter()
241530×
            .flat_map(|(_, m)| m.deps.iter().copied())
241610×
            .collect();
241710×
        let mut entries: Vec<LogEntry> = metas
241810×
            .into_iter()
241910×
            .map(|(h, meta)| LogEntry {
242030×
                hash: h,
242130×
                is_head: !depended.contains(&h),
242230×
                change: meta,
2423
                is_working_copy: false,
242430×
            })
242510×
            .collect();
242644×
        let order = |a: &LogEntry, b: &LogEntry| {
242744×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
242844×
        };
242914×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
24304×
            entries.sort_unstable_by(order);
24316×
        }
243210×
        Ok(entries)
243310×
    }
2434
2435
    /// Every change of the state with these heads and its metadata, read
2436
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2437
    /// a shallow clone's boundary is left out.
2438184×
    pub fn metas_of(
2439184×
        &self,
2440184×
        heads: &[ChangeHash],
2441184×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2442184×
        let boundary = self.boundary();
2443
        // The state index holds the metadata of its heads' closure: a
2444
        // change found there is not read from the store (a change object
2445
        // can be as large as the tree it adds).
2446184×
        let read = self.read_state_index_changes();
2447
        // Every one of `heads` in the index, and every head of the index
2448
        // among them: their closure is the index's changes, all of them
2449
        // (it is closed), and no walk is needed to find it.
2450184×
        if let Some((index_heads, all)) = &read {
2451167×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2452167×
            let in_index = || {
2453167×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2454167×
                    index_heads.iter().collect();
2455
                // Usually the heads asked are the index's: no set of all.
2456167×
                heads.iter().all(|h| index_heads.contains(h)) || {
2457167×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2458167×
                        all.iter().map(|(h, _)| h).collect();
2459167×
                    heads.iter().all(|h| all.contains(h))
2460
                }
2461167×
            };
2462167×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
24630×
                let (_, all) = read.expect("matched above");
2464
                #[cfg(test)]
2465
                {
2466
                    // The walk the shortcut saves finds the same changes.
24670×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
24680×
                    let mut stack = heads.to_vec();
24690×
                    while let Some(h) = stack.pop() {
24700×
                        if seen.insert(h) {
24710×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
24720×
                        }
2473
                    }
24740×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2475
                }
24760×
                return Ok(all);
2477167×
            }
247817×
        }
2479184×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2480184×
            read.map(|(_, all)| all.into_iter().collect());
2481184×
        let _walk = crate::timing::phase("metadata: walk");
2482184×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2483184×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2484184×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2485184×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
24861330×
        while let Some(h) = stack.pop() {
24871146×
            if !seen.insert(h) {
2488483×
                continue;
2489663×
            }
2490
            // Taken out of the index's map, each once: not copied.
2491663×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2492
                #[cfg(test)]
24930×
                assert_eq!(
2494
                    meta,
24950×
                    self.store.get_change_meta(&h)?,
2496
                    "the state index holds a change's metadata"
2497
                );
24980×
                stack.extend(meta.deps.iter().copied());
24990×
                out.push((h, meta));
25000×
                continue;
2501663×
            }
2502663×
            let started = std::time::Instant::now();
2503663×
            let meta = match self.store.get_change_meta(&h) {
2504663×
                Ok(m) => m,
25050×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
25060×
                Err(e) => return Err(e.into()),
2507
            };
2508663×
            stored += 1;
2509663×
            from_store += started.elapsed();
2510663×
            stack.extend(meta.deps.iter().copied());
2511663×
            out.push((h, meta));
2512
        }
2513184×
        if stored > 0 && crate::timing::enabled() {
25140×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2515184×
        }
2516184×
        Ok(out)
2517184×
    }
2518
2519
    /// The log of a state already loaded, newest first.
2520
    /// The history of lines `first..=last` (1-based) of `path` in the
2521
    /// state `heads` make (spec §27): every change that inserted or
2522
    /// deleted one of their atoms, or an atom deleted from between them,
2523
    /// newest first. Exact, as atoms keep their identity across edits.
25246×
    pub fn line_history(
25256×
        &self,
25266×
        heads: &[ChangeHash],
25276×
        path: &str,
25286×
        first: usize,
25296×
        last: usize,
25306×
    ) -> Result<Vec<LogEntry>> {
25316×
        if first == 0 || last < first {
25321×
            return fail(format!(
2533
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2534
            ));
25355×
        }
25365×
        let mut state = self.load_state_history(heads)?;
25375×
        let Some(node) = self
25385×
            .tree_view(&mut state)?
2539
            .entries
25405×
            .get(path)
25415×
            .map(|e| e.node)
2542
        else {
25431×
            return fail(format!("{path} is not in that state"));
2544
        };
25454×
        self.load_graphs_of(&mut state, &[node])?;
25464×
        let live = state.live_lines(&node);
25474×
        if last > live.len() {
25481×
            return fail(format!(
2549
                "{path} has {} lines; asked for {first},{last}",
25501×
                live.len()
2551
            ));
25523×
        }
25533×
        let Some(g) = state.file(&node) else {
25540×
            return fail(format!("{path} is not a text file"));
2555
        };
25563×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
25573×
        let touched = g.touching(&atoms);
25583×
        Ok(self
25593×
            .log_of(&state)
25603×
            .into_iter()
256113×
            .filter(|e| touched.contains(&e.hash))
25623×
            .collect())
25636×
    }
2564
25658×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
25668×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
25678×
        let mut entries: Vec<LogEntry> = state
25688×
            .changes()
25698×
            .map(|(h, meta)| LogEntry {
257031×
                hash: *h,
257131×
                change: meta.clone(),
2572
                is_working_copy: false,
257331×
                is_head: head_set.contains(h),
257431×
            })
25758×
            .collect();
257642×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
25778×
        entries
25788×
    }
2579
2580
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2581
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2582
    /// (`resolve_change`).
258367×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
258467×
        let view = self.view()?;
258567×
        if let Some(st) = view.bookmarks.get(spec) {
258639×
            return Ok(self.store.get_state(st)?.heads);
258728×
        }
258828×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
25892×
            return Ok(self.store.get_state(&st)?.heads);
259026×
        }
259126×
        if let Some(heads) = self.tag_heads(spec)? {
25922×
            return Ok(heads);
259324×
        }
259424×
        Ok(vec![self.resolve_change(spec)?])
259567×
    }
2596
2597
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2598
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
259937×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
260037×
        if spec == "@" {
26010×
            return Ok(self.working_copy()?.0);
260237×
        }
260337×
        let view = self.view()?;
260437×
        let named = match view.bookmarks.get(spec) {
26051×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
260636×
            None => match remote_bookmark(&view, spec) {
26071×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
260835×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2609
            },
2610
        };
261137×
        if let Some((kind, heads)) = named {
26123×
            return match heads.len() {
26133×
                1 => Ok(heads[0]),
26140×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2615
            };
261634×
        }
261734×
        if spec.is_empty() || spec == "#" {
26180×
            return fail("empty change specifier");
261934×
        }
262034×
        let entries = self.log()?;
2621
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2622
        // cannot be a ChangeId, which has 32 (oxygen#103).
262334×
        let full_hash =
2624128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
262534×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
262628×
            entries
262728×
                .iter()
2628112×
                .filter(|e| e.hash.starts_with_hex(hp))
262928×
                .collect()
2630
        } else {
26316×
            entries
26326×
                .iter()
263321×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
26346×
                .collect()
2635
        };
263634×
        match matches.len() {
263729×
            1 => Ok(matches[0].hash),
26385×
            0 => match self.resolve_in_remotes(spec)? {
26391×
                Some(h) => Ok(h),
26404×
                None => fail(format!("no change matches {spec:?}")),
2641
            },
2642
            _ => {
26430×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
26440×
                if ids.len() == 1 {
26450×
                    fail(format!(
2646
                        "change {spec} is divergent: {} variants",
26470×
                        matches.len()
2648
                    ))
2649
                } else {
26500×
                    fail(format!("{spec:?} is ambiguous"))
2651
                }
2652
            }
2653
        }
265437×
    }
2655
2656
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2657
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2658
    /// `None` when none matches, or more than one.
26595×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
26605×
        let view = self.view()?;
26615×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
26625×
        for bookmarks in view.remotes.values() {
26633×
            for st in bookmarks.values() {
26643×
                let heads = self.store.get_state(st)?.heads;
26657×
                for e in self.log_state(&heads)? {
26667×
                    let hit = match spec.strip_prefix('#') {
26672×
                        Some(hp) => e.hash.starts_with_hex(hp),
26685×
                        None => e.change.change_id.starts_with_hex(spec),
2669
                    };
26707×
                    if hit {
26711×
                        found.insert(e.hash);
26726×
                    }
2673
                }
2674
            }
2675
        }
26765×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
26775×
    }
2678
2679
    /// Where a change is when no local bookmark or the working copy holds
2680
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2681
    /// it is held locally, or nowhere.
26824×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
26838×
        if self.log()?.iter().any(|e| e.hash == *hash) {
26843×
            return Ok(None);
26851×
        }
26861×
        let view = self.view()?;
26871×
        for (remote, bookmarks) in &view.remotes {
26881×
            for (name, st) in bookmarks {
26891×
                let heads = self.store.get_state(st)?.heads;
26901×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
26911×
                    return Ok(Some(format!("{remote}/{name}")));
26920×
                }
2693
            }
2694
        }
26950×
        Ok(None)
26964×
    }
2697
2698
    /// Human-readable description of what a change does, with line content.
26994×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
27004×
        let change = self.store.get_change(hash)?;
27014×
        let (base, base_snapshot) = self.change_base(&change)?;
27024×
        Ok(render_change(&change, &base, &base_snapshot))
27034×
    }
2704
2705
    /// The base state of `change` (its dependencies) and its rendering, as
2706
    /// much as showing the change needs: the whole tree, and the graphs and
2707
    /// contents of the files the change edits. Other text files are left
2708
    /// unrendered ([`Snapshot::unrendered`]).
27098×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
27108×
        let base = self.load_state_history(&change.deps)?;
27118×
        self.render_base_for(change, base)
27128×
    }
2713
2714
    /// The base for showing `change` alone: the graphs of the files it
2715
    /// edits built, and the base's tree with no file rendered, which is
2716
    /// all [`render_change`](snapshot::render_change) and
2717
    /// [`diff_files_of`](snapshot::diff_files_of) read.
27183×
    pub(crate) fn tree_base_for(
27193×
        &self,
27203×
        change: &Change,
27213×
        mut base: State,
27223×
    ) -> Result<(State, Snapshot)> {
27233×
        let _t = crate::timing::phase("diff: the base's tree");
27243×
        let edited: std::collections::HashSet<NodeId> =
27258×
            change.edits.iter().map(|e| e.node()).collect();
27263×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
27273×
        self.load_graphs_of(&mut base, &nodes)?;
27283×
        let snapshot = Snapshot {
27293×
            tree: self.tree_view(&mut base)?,
27303×
            files: BTreeMap::new(),
27313×
            unrendered: BTreeSet::new(),
2732
        };
27333×
        Ok((base, snapshot))
27343×
    }
2735
2736
    /// [`Repo::change_base`] with the base already loaded (the working
2737
    /// copy's comes from the state index).
2738226×
    pub(crate) fn render_base_for(
2739226×
        &self,
2740226×
        change: &Change,
2741226×
        mut base: State,
2742226×
    ) -> Result<(State, Snapshot)> {
2743226×
        let _t = crate::timing::phase("diff: render the base");
2744226×
        let edited: std::collections::HashSet<NodeId> =
2745451×
            change.edits.iter().map(|e| e.node()).collect();
2746226×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2747226×
        self.load_graphs_of(&mut base, &nodes)?;
2748226×
        self.tree_view(&mut base)?;
2749226×
        let snapshot = {
2750226×
            let _t = crate::timing::phase("diff:   of which materialize");
2751226×
            base.materialize_nodes(&edited)
2752
        };
2753226×
        Ok((base, snapshot))
2754226×
    }
2755
}
2756
27570×
fn remove_any(path: &Path) -> std::io::Result<()> {
27580×
    let m = fs::symlink_metadata(path)?;
27590×
    if m.is_dir() {
27600×
        fs::remove_dir_all(path)
2761
    } else {
27620×
        fs::remove_file(path)
2763
    }
27640×
}
2765
27665×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
27675×
    let mut perms = fs::metadata(path)?.permissions();
27685×
    perms.set_readonly(readonly);
27695×
    fs::set_permissions(path, perms)
27705×
}
2771
2772
#[cfg(unix)]
27735908×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2774
    use std::os::unix::fs::PermissionsExt;
27755908×
    let mut perms = fs::metadata(path)?.permissions();
27765908×
    let mode = perms.mode();
27775908×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
27785908×
    if want != mode {
27796×
        perms.set_mode(want);
27806×
        fs::set_permissions(path, perms)?;
27815902×
    }
27825908×
    Ok(())
27835908×
}
2784
#[cfg(not(unix))]
2785
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2786
    Ok(())
2787
}
2788
2789
#[cfg(unix)]
279016648×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2791
    use std::os::unix::fs::PermissionsExt;
279216648×
    m.permissions().mode() & 0o111 != 0
279316648×
}
2794
#[cfg(not(unix))]
2795
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2796
    false
2797
}
2798
279913088×
fn op_ref(k: OpKey) -> OpRef {
280013088×
    OpRef {
280113088×
        change: k.0,
280213088×
        index: k.1,
280313088×
    }
280413088×
}
2805
28066145×
fn split_path(path: &str) -> (&str, &str) {
28076145×
    match path.rfind('/') {
28085060×
        Some(i) => (&path[..i], &path[i + 1..]),
28091085×
        None => ("", path),
2810
    }
28116145×
}
2812
2813
/// Whether `rel` is an attributes file (spec §7.6).
281468320×
fn is_attributes(rel: &str) -> bool {
281568320×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
281668320×
}
2817
2818
/// The manifest entry for `rel` when its size and mtime match it outside
2819
/// the racy window.
282024547×
fn stat_cached<'m>(
282124547×
    rel: &str,
282224547×
    meta: &walk::Stat,
282324547×
    cache: Option<&'m prompt::Manifest>,
282424547×
) -> Option<&'m prompt::ManifestEntry> {
282524547×
    let m = cache?;
282619561×
    let e = m.entries.get(rel)?;
282718160×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
282818160×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
282924547×
}
2830
2831
/// Read one working-copy file, or serve it from the stat cache (spec
2832
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2833
/// an opaque file is not read at all (its stored blob stands in), and a
2834
/// text file the manifest recorded equal to a base graph whose key is
2835
/// `key`, the key the base has now, is not read either: equal keys mean
2836
/// equal renderings, so it still equals the base. Touches no repository
2837
/// state, so the walk runs it in parallel; the caller checks that a cached
2838
/// blob is still in the store.
283912289×
fn read_file_entry(
284012289×
    rel: &str,
284112289×
    path: &Path,
284212289×
    meta: &walk::Stat,
284312289×
    cache: Option<&prompt::Manifest>,
284412289×
    key: Option<[u8; 32]>,
284512289×
) -> Result<FsEntry> {
284612289×
    let exec = meta.exec;
284712289×
    let stat = Some((meta.size, meta.mtime_ns));
284812289×
    let mut e = match stat_cached(rel, meta, cache) {
28494247×
        Some(e) if e.blob.is_some() => FsEntry {
28501×
            blob: e.blob,
28511×
            content_hash: Some(e.hash),
28521×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28531×
        },
28544246×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
28554241×
            content_hash: Some(e.hash),
28564241×
            unchanged: true,
28574241×
            graph_key: e.graph,
28584241×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28594241×
        },
28605×
        Some(e) => FsEntry {
28615×
            content_hash: Some(e.hash),
28625×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2863
        },
28648042×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2865
    };
2866
    // The stat the manifest records: taken before the read, so a file that
2867
    // changes meanwhile is read again next time.
286812288×
    e.stat = stat;
286912288×
    Ok(e)
287012289×
}
2871
2872
/// Two maps side by side in key order: each key of either, with its value
2873
/// in each. Linear, with no lookups, for maps of a whole tree.
28742788×
pub(crate) fn join<'a, A, B>(
28752788×
    a: &'a BTreeMap<String, A>,
28762788×
    b: &'a BTreeMap<String, B>,
28772788×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
28782788×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
287936213×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
28802788×
        (None, None) => None,
28812985×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
28825911×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
288324529×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2884337×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2885313×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2886
            std::cmp::Ordering::Equal => {
288723879×
                let (k, va) = a.next()?;
288823879×
                let (_, vb) = b.next()?;
288923879×
                Some((k, Some(va), Some(vb)))
2890
            }
2891
        },
289236213×
    })
28932788×
}
2894
2895
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2896
/// lookups.
28971391×
pub(crate) fn missing_from<'a, A, B>(
28981391×
    a: &'a BTreeMap<String, A>,
28991391×
    b: &BTreeMap<String, B>,
29001391×
) -> Vec<(&'a String, &'a A)> {
29011391×
    let mut keys = b.keys().peekable();
29021391×
    a.iter()
29039226×
        .filter(|(k, _)| {
290417706×
            while keys.next_if(|kb| *kb < *k).is_some() {}
29059226×
            keys.peek() != Some(k)
29069226×
        })
29071391×
        .collect()
29081391×
}