OXYGENHUB

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

1873 of 2110 lines run, 440 of 713 functions · run #388 on main · run missed

1
//! A repository on disk: the `.oxy` directory, one workspace, the operation
2
//! log, and the working-copy change (spec §12, §13.1).
3
//!
4
//! Not yet implemented from the spec: packs, checkpoints, multiple
5
//! workspaces, multi-signer policy updates, and the `objects`/`checkpoint`
6
//! endpoints. A repository without a policy is unverified and accepts
7
//! unsigned pushes; with one, everything received is checked (spec §14.5). Changes are signed individually when `core.sign` is
8
//! `change`; the default `seal` leaves them unsigned until push exists.
9
10
use crate::attest::{Attest, AttestBody};
11
use crate::diff::{ranges, split_lines, text_edits};
12
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
13
use crate::identity::{
14
    verify as verify_signature, Delegate, Domain, Identity, Scope, SecretKey, Signature,
15
};
16
use crate::ids::{ChangeId, NodeId, WorkspaceId};
17
use crate::objects::{
18
    Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp,
19
};
20
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
21
use crate::protocol::{
22
    open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef,
23
    SignedAttest, SignedPolicy,
24
};
25
use crate::state::{FileContent, Snapshot, State};
26
use crate::store::{Store, StoreError};
27
#[allow(unused_imports)]
28
use crate::subrepo::Pin;
29
use crate::tree::OpKey;
30
use rand::RngCore;
31
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
32
use std::fs;
33
use std::io::Write;
34
use std::path::{Path, PathBuf};
35
36
pub const OXY_DIR: &str = ".oxy";
37
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
38
const FORMAT1_LINE: &str = "oxy repository format 1\n";
39
const BINARY_SNIFF: usize = 8 * 1024;
40
/// Loose objects tolerated before a commit packs them (spec §13.4).
41
pub const AUTOPACK_THRESHOLD: usize = 4096;
42
43
#[derive(Debug, thiserror::Error)]
44
pub enum RepoError {
45
    #[error("io: {0}")]
46
    Io(#[from] std::io::Error),
47
    #[error(transparent)]
48
    Store(#[from] StoreError),
49
    #[error(transparent)]
50
    Object(#[from] crate::objects::ObjectError),
51
    #[error(transparent)]
52
    State(#[from] crate::state::StateError),
53
    #[error("{0}")]
54
    Msg(String),
55
    /// The operation would leave a conflict where none may be (a rebased
56
    /// change cannot hold one); the caller may offer another way.
57
    #[error("{0}")]
58
    Conflicted(String),
59
}
60
61
pub type Result<T> = std::result::Result<T, RepoError>;
62
63
/// The operation head's reference record on a store that is not this
64
/// disk's directory (oxygen#68).
65
pub const HEAD_RECORD: &str = "ops/head";
66
67
/// How often recording an operation reads the head again when other
68
/// processes keep moving it.
69
const HEAD_TRIES: usize = 8;
70
71
/// The object store of the repository directory `oxy`: `.oxy/objects`,
72
/// or the store `storage.url` names behind a cache of `storage.cache`
73
/// bytes in `.oxy/cache` (oxygen#68). `.oxy/objects` is then only
74
/// scratch space: packs being written, and derived caches.
752838×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762838×
    let Some(url) = &config.storage_url else {
772833×
        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×
    )?)
1002838×
}
101
102176×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103176×
    Err(RepoError::Msg(s.into()))
104176×
}
105
106
mod bookmarks;
107
mod checkout;
108
mod checkpoint;
109
mod config;
110
mod doctor;
111
mod fsck;
112
mod gc;
113
mod git;
114
mod history;
115
mod hooks;
116
mod hosted;
117
mod identity;
118
mod inspect;
119
mod keyless;
120
mod ops;
121
mod policy;
122
mod prompt;
123
mod receipts;
124
mod revset;
125
mod snapshot;
126
pub mod strata;
127
mod subrepos;
128
mod sync;
129
mod tags;
130
#[cfg(test)]
131
mod tests;
132
mod touched;
133
mod transparency;
134
mod walk;
135
mod workspace;
136
137
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
138
pub use checkout::CheckoutReport;
139
pub use config::{parse_size, read_config_file, Config};
140
pub use doctor::{Check, DoctorReport, Health};
141
pub use fsck::{FsckReport, Problem, Severity};
142
pub use gc::GcReport;
143
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
144
pub use hooks::{json_array, json_str, HookOutcome};
145
pub use hosted::FileEdit;
146
pub use identity::{Rotation, SignatureStatus};
147
pub use inspect::{BisectStep, BlameLine, Description};
148
pub use keyless::home_key;
149
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
150
pub use policy::PolicyUpdate;
151
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
152
pub use receipts::ReceiptInfo;
153
pub use revset::{Revset, REVSET_BUDGET};
154
pub use snapshot::{
155
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
156
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, KeptBoth,
157
    PathStatus, 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.
1685484×
pub(crate) fn name_file(name: &str) -> String {
1695484×
    name.replace('%', "%25").replace('/', "%2F")
1705484×
}
171
172
/// The name a [`name_file`] file name stands for.
17358×
pub(crate) fn file_name_to_name(file: &str) -> String {
17458×
    file.replace("%2F", "/").replace("%25", "%")
17558×
}
176
1778521×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1788521×
    Ok(crate::durable::write_atomic(path, data)?)
1798521×
}
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
1953316×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1963316×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1973316×
    fs::write(&tmp, data)?;
1983316×
    fs::rename(&tmp, path)?;
1993316×
    Ok(())
2003316×
}
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 {
24023339×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
24123339×
        FsEntry {
24223339×
            kind,
24323339×
            exec,
24423339×
            content: std::sync::Arc::new(content),
24523339×
            blob: None,
24623339×
            content_hash: None,
24723339×
            unchanged: false,
24823339×
            graph_key: None,
24923339×
            stat: None,
25023339×
        }
25123339×
    }
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/`.
3178794×
pub fn default_home() -> PathBuf {
3188794×
    if let Ok(h) = std::env::var("OXY_HOME") {
3198767×
        return PathBuf::from(h);
32027×
    }
32127×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3220×
        return PathBuf::from(x).join("oxy");
32327×
    }
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
    }
33027×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
33127×
    PathBuf::from(home).join(".config").join("oxy")
3328794×
}
333
3342839×
pub fn default_keys_dir() -> PathBuf {
3352839×
    default_home().join("keys")
3362839×
}
337
3385676×
pub fn default_user_config() -> PathBuf {
3395676×
    default_home().join("config.toml")
3405676×
}
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
354268×
    pub fn init(root: &Path) -> Result<Repo> {
355268×
        let mut id = [0u8; 16];
356268×
        rand::rngs::OsRng.fill_bytes(&mut id);
357268×
        Self::init_with_id(root, id)
358268×
    }
359
360
    /// Initialize a repository with a given repository ID (clones share the
361
    /// ID of their origin, spec §14.4).
362556×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
363556×
        Self::init_on(root, id, None)
364556×
    }
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`.
380571×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
381571×
        fs::create_dir_all(root)?;
382571×
        let root = crate::portable::canonical(root).unwrap_or_else(|_| root.to_path_buf());
383571×
        let oxy = root.join(OXY_DIR);
384571×
        if oxy.exists() {
3851×
            return fail(format!("{} is already an oxy repository", root.display()));
386570×
        }
387570×
        fs::create_dir_all(oxy.join("ops"))?;
388570×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
389570×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
390570×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
391570×
        if let Some(url) = storage {
3923×
            config.set("storage.url", url)?;
393567×
        }
394570×
        config.save(&oxy.join("config"))?;
395570×
        let workspace = WorkspaceId::random();
396570×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
397570×
        let store = open_objects(&oxy, &config)?;
398569×
        let repo = Repo {
399569×
            acceptor: None,
400569×
            keyless_key: Default::default(),
401569×
            last_change: Default::default(),
402569×
            at_op: None,
403569×
            head_seen: Default::default(),
404569×
            walked_dirs: Default::default(),
405569×
            listed_dirs: Default::default(),
406569×
            git_export_skipped: Default::default(),
407569×
            manifest_cache: Default::default(),
408569×
            listing_cache: Default::default(),
409569×
            untracked_nested: Default::default(),
410569×
            skipped_large: Default::default(),
411569×
            root,
412569×
            oxy,
413569×
            store,
414569×
            workspace,
415569×
            bare: false,
416569×
            keys_dir: default_keys_dir(),
417569×
            platform: crate::portable::Platform::current(),
418569×
            user_config: default_user_config(),
419569×
            config,
420569×
        };
421569×
        repo.register_workspace(&workspace, &repo.root)?;
422
423569×
        let wc = repo.new_working_copy(vec![], "");
424569×
        let wc_hash = repo.store.put_change(&wc)?;
425569×
        let mut view = View::default();
426569×
        view.bookmarks.insert(
427569×
            repo.config.bookmark.clone(),
428569×
            repo.store.put_state(&StateObject::new(vec![]))?,
429
        );
430569×
        view.workspaces.insert(workspace, wc_hash);
431569×
        repo.record_op(&[], "oxy init", view)?;
432567×
        Ok(repo)
433571×
    }
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
44445×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
44545×
        Self::init_bare_on(root, id, None)
44645×
    }
447
448
    /// [`Repo::init_on`] for a bare repository.
44945×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
45045×
        fs::create_dir_all(root)?;
45145×
        let root = crate::portable::canonical(root).unwrap_or_else(|_| root.to_path_buf());
45245×
        let oxy = root.join(OXY_DIR);
45345×
        if oxy.exists() {
4540×
            return fail(format!("{} is already an oxy repository", root.display()));
45545×
        }
45645×
        fs::create_dir_all(oxy.join("ops"))?;
45745×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
45845×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
45945×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
46045×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
46145×
        if let Some(url) = storage {
4620×
            config.set("storage.url", url)?;
46345×
        }
46445×
        config.save(&oxy.join("config"))?;
46545×
        let store = open_objects(&oxy, &config)?;
46645×
        let repo = Repo {
46745×
            acceptor: None,
46845×
            keyless_key: Default::default(),
46945×
            last_change: Default::default(),
47045×
            at_op: None,
47145×
            head_seen: Default::default(),
47245×
            walked_dirs: Default::default(),
47345×
            listed_dirs: Default::default(),
47445×
            git_export_skipped: Default::default(),
47545×
            manifest_cache: Default::default(),
47645×
            listing_cache: Default::default(),
47745×
            untracked_nested: Default::default(),
47845×
            skipped_large: Default::default(),
47945×
            root,
48045×
            oxy,
48145×
            store,
48245×
            workspace: WorkspaceId::ZERO,
48345×
            bare: true,
48445×
            keys_dir: default_keys_dir(),
48545×
            platform: crate::portable::Platform::current(),
48645×
            user_config: default_user_config(),
48745×
            config,
48845×
        };
48945×
        let mut view = View::default();
49045×
        view.bookmarks.insert(
49145×
            repo.config.bookmark.clone(),
49245×
            repo.store.put_state(&StateObject::new(vec![]))?,
493
        );
49445×
        repo.record_op(&[], "oxy init --bare", view)?;
49545×
        Ok(repo)
49645×
    }
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.
50119×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
50219×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
50319×
        fs::remove_file(repo.oxy.join("id"))?;
50419×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
50519×
        Ok(repo)
50619×
    }
507
5084253×
    pub fn is_unbound(&self) -> bool {
5094253×
        self.oxy.join(UNBOUND_MARKER).is_file()
5104253×
    }
511
512
    /// Give an unbound repository its id.
51318×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
51418×
        if !self.is_unbound() {
5150×
            return fail("this repository already has an id");
51618×
        }
51718×
        if id == [0; 16] {
5180×
            return fail("a repository id cannot be all zero");
51918×
        }
52018×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
52118×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
52218×
        Ok(())
52318×
    }
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).
5312223×
    pub fn open(start: &Path) -> Result<Repo> {
5322223×
        let start = crate::portable::canonical(start)?;
5332223×
        let mut dir: Option<&Path> = Some(&start);
5342223×
        while let Some(d) = dir {
5352223×
            let oxy = d.join(OXY_DIR);
5362223×
            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);
5732214×
            }
5742214×
            if oxy.is_dir() {
5752214×
                let format = fs::read_to_string(oxy.join("format"))?;
5762214×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5772214×
                let bare = oxy.join(BARE_MARKER).is_file();
5782214×
                let workspace = if bare {
579189×
                    WorkspaceId::ZERO
580
                } else {
5812025×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5822025×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
583
                };
5842214×
                let store = open_objects(&oxy, &config)?;
5852214×
                let mut repo = Repo {
5862214×
                    acceptor: None,
5872214×
                    keyless_key: Default::default(),
5882214×
                    last_change: Default::default(),
5892214×
                    at_op: None,
5902214×
                    head_seen: Default::default(),
5912214×
                    walked_dirs: Default::default(),
5922214×
                    listed_dirs: Default::default(),
5932214×
                    git_export_skipped: Default::default(),
5942214×
                    manifest_cache: Default::default(),
5952214×
                    listing_cache: Default::default(),
5962214×
                    untracked_nested: Default::default(),
5972214×
                    skipped_large: Default::default(),
5982214×
                    root: d.to_path_buf(),
5992214×
                    oxy,
6002214×
                    store,
6012214×
                    workspace,
6022214×
                    bare,
6032214×
                    keys_dir: default_keys_dir(),
6042214×
                    platform: crate::portable::Platform::current(),
6052214×
                    user_config: default_user_config(),
6062214×
                    config,
6072214×
                };
6082214×
                if !bare {
6092025×
                    repo.apply_workspace_bookmark();
6102025×
                }
6112214×
                if format == FORMAT1_LINE {
6121×
                    repo.migrate_format1()?;
6132213×
                } else if format != FORMAT_LINE {
6140×
                    return fail(format!("unsupported repository format: {}", format.trim()));
6152213×
                }
6162214×
                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
        ))
6242223×
    }
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).
669759×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
670759×
        self.store
671759×
            .expire_retired(crate::store::RETIRED_FOR, &mut |_| {})?;
672759×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6730×
            self.store.pack_loose()?;
6740×
            self.store.merge_packs()?;
675759×
        }
676759×
        Ok(())
677759×
    }
678
679
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6803910×
    pub fn id(&self) -> Result<[u8; 16]> {
6813910×
        if self.is_unbound() {
68227×
            return Ok([0; 16]);
6833883×
        }
6843883×
        let path = self.oxy.join("id");
6853883×
        match fs::read_to_string(&path) {
6863883×
            Ok(h) => hex::decode(h.trim())
6873883×
                .ok()
6883883×
                .and_then(|v| v.try_into().ok())
6893883×
                .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
        }
6983910×
    }
699
70069×
    pub fn root(&self) -> &Path {
70169×
        &self.root
70269×
    }
703577×
    pub fn store(&self) -> &Store {
704577×
        &self.store
705577×
    }
70611×
    pub fn workspace(&self) -> WorkspaceId {
70711×
        self.workspace
70811×
    }
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).
71648×
    pub fn with_acceptor(mut self, identity: Identity, sk: crate::identity::SecretKey) -> Repo {
71748×
        self.acceptor = Some(std::sync::Arc::new((identity, sk)));
71848×
        self
71948×
    }
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
730206×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
731206×
        let dir = dir.into();
732206×
        self.keys_dir = dir.join("keys");
733206×
        self.user_config = dir.join("config.toml");
734206×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
735206×
            self.config = c;
736206×
        }
737206×
        self.apply_workspace_bookmark();
738206×
        self
739206×
    }
740
741
    /// The workspace's current bookmark (spec §10.1) overrides the
742
    /// configured default when `oxy bookmark switch` has recorded one.
7432240×
    fn apply_workspace_bookmark(&mut self) {
7442240×
        if let Ok(b) = fs::read_to_string(
7452240×
            self.oxy
7462240×
                .join("workspaces")
7472240×
                .join(self.workspace.to_hex())
7482240×
                .join("bookmark"),
7492240×
        ) {
75035×
            let b = b.trim();
75135×
            if !b.is_empty() {
75235×
                self.config.bookmark = b.to_string();
75335×
            }
7542205×
        }
7552240×
    }
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.
76228×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
76328×
        Config::set_user(&self.user_config, key, value)?;
76427×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
76527×
        Ok(())
76628×
    }
767
768418×
    pub fn save_config(&self) -> Result<()> {
769418×
        self.config.save(&self.oxy.join("config"))
770418×
    }
771
7725064×
    fn author(&self) -> KeyId {
7735064×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7745064×
    }
775
}
776
777
impl Repo {
7781924×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7791924×
        let mut c = Change {
7801924×
            version: crate::objects::CHANGE_VERSION,
7811924×
            change_id: ChangeId::random(),
7821924×
            deps,
7831924×
            author: self.author(),
7841924×
            hlc: Hlc::now(),
7851924×
            message: message.into(),
7861924×
            tree_ops: vec![],
7871924×
            edits: vec![],
7881924×
            kind: ChangeKind::WorkingCopy,
7891924×
        };
7901924×
        c.normalize();
7911924×
        c
7921924×
    }
793
794
    // ------------------------------------------------------------ operation log
795
79616954×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
79716954×
        if let Some(r) = self.at_op {
7985×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
79916949×
        }
80016949×
        let r = self.head_ref()?;
80116947×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
80216947×
        Ok((r, op))
80316954×
    }
804
80511435×
    pub fn view(&self) -> Result<View> {
80611435×
        Ok(self.head_op()?.1.view)
80711435×
    }
808
8093952×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
8103952×
        self.record_op_undoing(parents, command, view, None)
8113952×
    }
812
813
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
8143955×
    fn record_op_undoing(
8153955×
        &self,
8163955×
        parents: &[ObjectRef],
8173955×
        command: &str,
8183955×
        view: View,
8193955×
        undoes: Option<ObjectRef>,
8203955×
    ) -> Result<ObjectRef> {
8213955×
        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
            );
8253954×
        }
8263954×
        let op = Op {
8273954×
            parents: parents.to_vec(),
8283954×
            hlc: Hlc::now(),
8293954×
            command: command.into(),
8303954×
            view,
8313954×
            workspace: Some(self.workspace),
8323954×
            undoes,
8333954×
        };
8343954×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
835
        // The head is the commit point: everything it names must be on disk first.
8363952×
        let flushing = crate::timing::phase("op: flush the store");
8373952×
        self.store.flush()?;
8383950×
        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.
8443950×
        let _lock = if self.store.is_local() {
8453938×
            Some(self.lock_ops()?)
846
        } else {
84712×
            None
848
        };
8493950×
        let Some(parent) = parents.first() else {
850
            // The first operation (init): there is no head yet.
851614×
            if !self.swap_head(&r, None)? {
8522×
                return fail(format!(
853
                    "{} already holds a repository's operation log",
8542×
                    self.store.backend().describe()
855
                ));
856612×
            }
857612×
            return Ok(r);
858
        };
8593336×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8603336×
        for _ in 0..HEAD_TRIES {
8613336×
            let (current, version) = self.read_head()?;
8623336×
            let to = if current == *parent {
8633314×
                r
864
            } else {
86522×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
86621×
                let merged = Op {
86722×
                    parents: vec![current, r],
86822×
                    hlc: Hlc::now(),
86922×
                    command: format!("{command} (merged with a concurrent operation)"),
87022×
                    view: self.merge_views(&base, &op.view, &theirs)?,
87121×
                    workspace: Some(self.workspace),
87221×
                    undoes: None,
873
                };
87421×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
87521×
                self.store.flush()?;
87621×
                m
877
            };
8783335×
            if self.swap_head(&to, version.as_ref())? {
8793329×
                return Ok(to);
8800×
            }
881
        }
8820×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8833955×
    }
884
885
    /// The operation head's lock, held only while the head pointer moves.
8863948×
    fn lock_ops(&self) -> Result<FileLock> {
8873948×
        fs::create_dir_all(self.oxy.join("ops"))?;
8883948×
        FileLock::acquire(
8893948×
            self.oxy.join("ops").join("lock"),
8903948×
            "another oxy process holds the operation log",
891
        )
8923948×
    }
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`]).
89616951×
    fn head_ref(&self) -> Result<ObjectRef> {
89716951×
        if let Some(r) = self.head_seen.get() {
89813241×
            return Ok(r);
8993710×
        }
9003710×
        let r = self.read_head()?.0;
9013708×
        self.head_seen.set(Some(r));
9023708×
        Ok(r)
90316951×
    }
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.
912505×
    pub fn refresh(&self) -> Result<()> {
913505×
        self.forget_head();
914505×
        self.store.refresh()?;
915505×
        Ok(())
916505×
    }
917
918
    /// Read the operation head again on next use, as [`Repo::refresh`]
919
    /// does, leaving the packs as they are.
9202407×
    pub(crate) fn forget_head(&self) {
9212407×
        self.head_seen.set(None);
9222407×
    }
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).
9287137×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
9297137×
        if self.store.is_local() {
9307119×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
9317119×
            let r = ObjectRef::from_hex(hex.trim())
9327119×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
9337116×
            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
        }
9547137×
    }
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.
9613962×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
9623962×
        if self.store.is_local() {
9633948×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
9643942×
            self.head_seen.set(Some(*to));
9653942×
            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
        }
9793962×
    }
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).
98922×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
99077×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
99177×
            b: &BTreeMap<K, V>,
99277×
            o: &BTreeMap<K, V>,
99377×
            t: &BTreeMap<K, V>,
99477×
            mut both: impl FnMut(&V, &V) -> Result<V>,
99577×
        ) -> Result<BTreeMap<K, V>> {
99677×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
99777×
            let mut out = BTreeMap::new();
99880×
            for k in keys {
99980×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
100080×
                let v = if ov == tv || tv == bv {
100140×
                    ov.cloned()
100240×
                } else if ov == bv {
100324×
                    tv.cloned()
1004
                } else {
100516×
                    match (ov, tv) {
100616×
                        (Some(x), Some(y)) => Some(both(x, y)?),
10070×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
10080×
                        (None, None) => None,
1009
                    }
1010
                };
101179×
                if let Some(v) = v {
101279×
                    out.insert(k.clone(), v);
101379×
                }
1014
            }
101576×
            Ok(out)
101677×
        }
101722×
        let bookmarks = pick(
101822×
            &base.bookmarks,
101922×
            &ours.bookmarks,
102022×
            &theirs.bookmarks,
102115×
            |x, y| {
102215×
                let mut heads = self.store.get_state(x)?.heads;
102315×
                heads.extend(self.store.get_state(y)?.heads);
102415×
                let heads = self.load_state(&heads)?.maximal(&heads);
102515×
                Ok(self.store.put_state(&StateObject::new(heads))?)
102615×
            },
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.
103222×
        let workspaces = pick(
103322×
            &base.workspaces,
103422×
            &ours.workspaces,
103522×
            &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×
        )?;
104321×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
104421×
        let empty = BTreeMap::new();
104521×
        let names: BTreeSet<&String> = base
104621×
            .remotes
104721×
            .keys()
104821×
            .chain(ours.remotes.keys())
104921×
            .chain(theirs.remotes.keys())
105021×
            .collect();
105121×
        let mut remotes = BTreeMap::new();
105221×
        for n in names {
105312×
            let m = pick(
105412×
                base.remotes.get(n).unwrap_or(&empty),
105512×
                ours.remotes.get(n).unwrap_or(&empty),
105612×
                theirs.remotes.get(n).unwrap_or(&empty),
10570×
                |x, _| Ok(*x),
10580×
            )?;
105912×
            if !m.is_empty() {
106012×
                remotes.insert(n.clone(), m);
106112×
            }
1062
        }
106321×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
106421×
            ours.policy
10650×
        } else if ours.policy == base.policy {
10660×
            theirs.policy
1067
        } else {
10680×
            ours.policy.or(theirs.policy)
1069
        };
107021×
        self.store.flush()?;
107121×
        Ok(View {
107221×
            bookmarks,
107321×
            workspaces,
107421×
            remotes,
107521×
            policy,
107621×
            tags,
107721×
        })
107822×
    }
1079
108056×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
108156×
        let mut out = Vec::new();
108256×
        let (mut r, mut op) = self.head_op()?;
1083
        loop {
1084297×
            let next = op.parents.first().copied();
1085297×
            out.push((r, op));
1086297×
            match next {
1087241×
                Some(p) => {
1088241×
                    r = p;
1089241×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1090
                }
109156×
                None => break,
1092
            }
1093
        }
109456×
        Ok(out)
109556×
    }
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();
112539×
        let load = |r: &ObjectRef| -> Result<Op> {
112639×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
112739×
        };
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 {
113340×
            let parent = match op.parents.first() {
113439×
                Some(p) => Some((*p, load(p)?)),
11351×
                None => None,
1136
            };
113740×
            if skip.contains(&r) {
11381×
                pending_checkout = None;
113939×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
11409×
                // A push cannot be taken back: undoing it would only make
11419×
                // 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
            }
115524×
            match parent {
115624×
                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.
1445216×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1446216×
        if let Some(st) = self.load_state_checkpointed(heads)? {
14474×
            return Ok(st);
1448211×
        }
1449211×
        self.load_state_full(heads)
1450216×
    }
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`].
14562113×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
14572113×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
145844×
            return Ok(st);
14592069×
        }
14602069×
        self.load_state_replayed(heads, State::new_history_only())
14612113×
    }
1462
1463
    /// Build these file graphs in a history-only state.
14642203×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
14652203×
        state
14662203×
            .load_graphs(
14672203×
                nodes,
146854×
                |refs| {
146954×
                    self.read_blobs(refs).map_err(|e| {
14703×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14713×
                    })
147254×
                },
14732387×
                |h| self.change_bytes(h),
1474
            )
14752203×
            .map_err(|e| self.index_damage(e))
14762203×
    }
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.
14812463×
    pub fn tree_view(&self, state: &mut State) -> Result<crate::tree::TreeView> {
14822463×
        let need = state.unify_candidates();
14832463×
        if !need.is_empty() {
1484101×
            self.load_graphs_of(state, &need)?;
14852362×
        }
14862463×
        Ok(state.view())
14872463×
    }
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.
1529428×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1530
        use crate::objects::TextRef;
1531428×
        let refs: Vec<ObjectRef> = texts
1532428×
            .iter()
15335566×
            .filter_map(|t| match t {
15341×
                TextRef::Blob(r, _, _) => Some(*r),
15355565×
                TextRef::Inline { .. } => None,
15365566×
            })
1537428×
            .collect();
1538428×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1539428×
        let mut out = Vec::with_capacity(texts.len());
15405566×
        for t in texts {
15415566×
            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
                }
15485565×
                TextRef::Inline { change, start, end } => {
15495565×
                    let bytes = self.change_bytes(change)?;
15505565×
                    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×
                    })?;
15535565×
                    crate::objects::inline_lines(range)?
1554
                }
1555
            };
15565566×
            out.push(lines.bytes().to_vec());
1557
        }
1558428×
        Ok(out)
1559428×
    }
1560
1561
    /// Build every graph a history-only state still lacks, making it full.
15622461×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
15632461×
        state
15642461×
            .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×
                },
15705156×
                |h| self.change_bytes(h),
1571
            )
15722461×
            .map_err(|e| self.index_damage(e))
15732461×
    }
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.
157813191×
    fn change_bytes(
157913191×
        &self,
158013191×
        h: &ChangeHash,
158113191×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
158213191×
        let mut cache = self.last_change.borrow_mut();
158322460×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
158410340×
            let hit = cache.remove(i);
158510340×
            let b = hit.1.clone();
158610340×
            cache.push(hit);
158710340×
            return Ok(b);
15882851×
        }
15892851×
        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×
        })?);
15922851×
        cache.push((*h, b.clone()));
1593
        // The last few, within a memory budget; the newest always stays.
15944613×
        while cache.len() > CHANGE_CACHE_COUNT
15952851×
            || (cache.len() > 1
15968576×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15971762×
        {
15981762×
            cache.remove(0);
15991762×
        }
16002851×
        Ok(b)
160113191×
    }
1602
1603
    /// Load the dependency closure of `heads` change by change.
1604265×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1605265×
        self.load_state_replayed(heads, State::new())
1606265×
    }
1607
16084021×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
16094021×
        let history = state.is_history_only();
16104021×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
16114021×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1612
        {
16134021×
            let _t = crate::timing::phase("load: read and add changes");
16144021×
            let (mut read, mut add, mut fetch) = (
16154021×
                std::time::Duration::ZERO,
16164021×
                std::time::Duration::ZERO,
16174021×
                std::time::Duration::ZERO,
16184021×
            );
161916152×
            while let Some(h) = stack.pop() {
1620
                // A change the state holds brings its history with it.
162112136×
                if !seen.insert(h) || state.contains(&h) {
16222818×
                    continue;
16239318×
                }
16249318×
                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.
16279318×
                let (c, texts) = if history {
16287840×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
16297837×
                    fetch += t0.elapsed();
16307837×
                    Change::decode_skeleton(&bytes, h)
16317837×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1632
                } else {
16331478×
                    (self.store.get_change(&h)?, Vec::new())
1634
                };
16359313×
                read += t0.elapsed();
16369313×
                stack.extend(c.deps.iter().copied());
16379313×
                let t1 = std::time::Instant::now();
16389313×
                state.add_known(h, c, texts);
16399313×
                add += t1.elapsed();
1640
            }
16414016×
            crate::timing::record("load:   of which reading", read);
16424016×
            crate::timing::record("load:     of which fetching", fetch);
16434016×
            crate::timing::record("load:   of which applying", add);
1644
        }
16454016×
        let _t = crate::timing::phase("load: validate");
16464016×
        state.validate()?;
16474016×
        Ok(state)
16484021×
    }
1649
16502778×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
16512778×
        if self.bare {
16522×
            return fail("this is a bare repository: it has no working copy");
16532776×
        }
16542776×
        let view = self.view()?;
16552776×
        let h = *view
16562776×
            .workspaces
16572776×
            .get(&self.workspace)
16582776×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
16592775×
        Ok((h, self.store.get_change(&h)?))
16602778×
    }
1661
1662
    /// Heads of a bookmark's state (spec §10.1).
16632033×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
16642033×
        match view.bookmarks.get(bookmark) {
16652033×
            Some(st) => Ok(self.store.get_state(st)?.heads),
16660×
            None => Ok(vec![]),
1667
        }
16682033×
    }
1669
1670573×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1671573×
        self.heads_of(&self.view()?, &self.config.bookmark)
1672573×
    }
1673
1674
    // ------------------------------------------------------------ blobs
1675
1676494×
    fn blob_for(content: &[u8]) -> Blob {
1677494×
        Blob::of(content)
1678494×
    }
1679
1680296×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1681296×
        Self::blob_for(content).hash()
1682296×
    }
1683
1684196×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1685279×
        for c in crate::chunk::chunks(content) {
1686279×
            self.store.put_chunk(c)?;
1687
        }
1688196×
        Ok(self
1689196×
            .store
1690196×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1691196×
    }
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.
1696502×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1697502×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1698502×
        let t = crate::timing::phase("blobs: get_many blobs");
1699502×
        let got_all = self.store.get_many(refs);
1700502×
        drop(t);
1701502×
        for (r, got) in refs.iter().zip(got_all) {
170280×
            blobs.push(match got {
170375×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
17040×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
17055×
                Err(crate::store::StoreError::NotFound(_)) => None,
17060×
                Err(e) => return Err(e.into()),
1707
            });
1708
        }
1709502×
        let chunk_refs: Vec<ObjectRef> = blobs
1710502×
            .iter()
1711502×
            .flatten()
1712502×
            .flat_map(|b| b.chunks.iter().copied())
1713502×
            .collect();
1714502×
        let t = crate::timing::phase("blobs: get_many chunks");
1715502×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1716502×
        drop(t);
1717502×
        if crate::timing::enabled() {
17180×
            eprintln!(
1719
                "timing blobs: {} blobs, {} chunks, {} one by one",
17200×
                refs.len(),
17210×
                chunk_refs.len(),
17220×
                blobs.iter().filter(|b| b.is_none()).count()
1723
            );
1724502×
        }
1725502×
        let mut out = Vec::with_capacity(refs.len());
1726502×
        for (r, blob) in refs.iter().zip(blobs) {
172780×
            match blob {
17285×
                None => out.push(self.read_blob(r)?),
172975×
                Some(b) => {
173075×
                    let mut content = Vec::with_capacity(b.length as usize);
1731114×
                    for c in &b.chunks {
1732114×
                        match chunks.next() {
1733114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
17340×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
17350×
                            Some(Err(e)) => return Err(e.into()),
17360×
                            None => return fail("chunk list ended early"),
1737
                        }
1738
                    }
173975×
                    out.push(content);
1740
                }
1741
            }
1742
        }
1743497×
        Ok(out)
1744502×
    }
1745
1746
    /// Read a blob's content, fetching it from the remote that withheld it
1747
    /// when it is lazily absent (spec §13.5).
1748151×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1749151×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
17505×
            self.fetch_lazy_blob(r)?;
1751146×
        }
1752151×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1753146×
        let mut out = Vec::with_capacity(blob.length as usize);
1754212×
        for c in &blob.chunks {
1755212×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1756
        }
1757146×
        Ok(out)
1758151×
    }
1759
1760
    // ------------------------------------------------------------ working copy
1761
1762
    /// Attributes from the `.oxyattributes` files in the working directory.
17632×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1764
        // Nested repositories and ignored paths are left out, as in a walk.
17658×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
17662×
        let files: Vec<(String, Vec<u8>)> = listing
17672×
            .files
17682×
            .into_iter()
17692×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
17702×
            .collect();
17712×
        crate::attributes::Attributes::from_files(
17722×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1773
        )
17742×
    }
1775
1776
    /// Folders holding a repository of their own that the last look at the
1777
    /// working copy left out, not being subrepos (oxygen#43).
177829×
    pub fn untracked_nested(&self) -> Vec<String> {
177929×
        self.untracked_nested.borrow().clone()
178029×
    }
1781
1782
    /// New untracked files the last snapshot left out for being larger than
1783
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
178433×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
178533×
        self.skipped_large.borrow().clone()
178633×
    }
1787
1788
    /// Attributes from a materialized state's `.oxyattributes` files.
17895×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
179012×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
179112×
            match &f.content {
179212×
                FileContent::Text { bytes, .. }
179312×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1794
                {
17952×
                    Some((p.as_str(), bytes.as_slice()))
1796
                }
179710×
                _ => None,
1798
            }
179912×
        }))
18005×
    }
1801
1802
    /// Store a blob, raw when the path is `nocompress`.
1803176×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1804176×
        if !nocompress {
1805174×
            return self.store_blob(content);
18062×
        }
18072×
        for c in crate::chunk::chunks(content) {
18082×
            self.store.put_chunk_nocompress(c)?;
1809
        }
18102×
        Ok(self
18112×
            .store
18122×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1813176×
    }
1814
1815
    /// This workspace's state index (oxygen#41): its working copy's base,
1816
    /// saved so a snapshot reads it rather than replaying history.
1817
    /// The state index of the state with these heads: this workspace keeps
1818
    /// the last few it used, named by their heads, so moving between two
1819
    /// states finds both.
18202914×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
18212914×
        let mut heads = heads.to_vec();
18222914×
        heads.sort();
18232914×
        let mut h = blake3::Hasher::new();
18243016×
        for c in &heads {
18253016×
            h.update(&c.0);
18263016×
        }
18272914×
        self.oxy.join("index").join(format!(
18282914×
            "{}{}",
18292914×
            self.state_index_prefix(),
18302914×
            &h.finalize().to_hex()[..16]
18312914×
        ))
18322914×
    }
1833
18345727×
    fn state_index_prefix(&self) -> String {
18355727×
        format!("state-{}-", self.workspace.to_hex())
18365727×
    }
1837
1838
    /// This workspace's state indexes, newest first.
18392813×
    fn state_indexes(&self) -> Vec<PathBuf> {
18402813×
        let prefix = self.state_index_prefix();
18412813×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
18422813×
            .into_iter()
18432813×
            .flatten()
18442813×
            .flatten()
18452813×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
18462813×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
18472813×
            .collect();
18482813×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
18492813×
        found.into_iter().map(|(_, p)| p).collect()
18502813×
    }
1851
1852
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1853
    /// from this workspace's state index when it holds that history: every
1854
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1855
    /// is loaded from history and indexed for next time.
18562440×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
18572440×
        if let Some((st, heads)) = self.read_state_index(deps) {
18581974×
            let mut have = st.maximal(deps);
18591974×
            have.sort();
18601974×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1861
                // Re-encoding reads every history: one found damaged is
1862
                // left to the build that reads it, which reports it.
1863
                #[cfg(test)]
1864166×
                if let Some(mine) = st.write_index() {
1865165×
                    assert_eq!(
1866165×
                        Some(mine),
1867165×
                        self.load_state_history(deps)?.write_index(),
1868
                        "a state index holds the state history gives"
1869
                    );
18701×
                }
1871287×
                return Ok(st);
18721687×
            }
1873
            // An index a few changes behind (a commit, a pull since): add
1874
            // what it lacks, as long as all it holds is history of `deps`.
1875
            // Anything amiss (a change beyond a shallow boundary) takes the
1876
            // long way instead.
18771687×
            let (indexed, started) = (st.len(), std::time::Instant::now());
18781687×
            if let Ok(st) = self.load_state_replayed(deps, st) {
18791684×
                let mut all = deps.to_vec();
18801684×
                all.extend(heads.iter().copied());
18811684×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
18821684×
                within.sort();
18831684×
                want.sort();
18841684×
                if within == want {
1885
                    #[cfg(test)]
1886954×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1887
                    // Writing the index costs far more than replaying a
1888
                    // few small changes: it is rewritten once it falls
1889
                    // behind, or when replaying took long (large changes).
18901683×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
18911683×
                        || started.elapsed() > INDEX_REPLAY_TIME
18923×
                    {
18933×
                        self.write_state_index(deps, &st);
18941680×
                    }
18951683×
                    return Ok(st);
18961×
                }
18973×
            }
1898466×
        }
1899470×
        let st = self.load_state_history(deps)?;
1900470×
        self.write_state_index(deps, &st);
1901470×
        Ok(st)
19022440×
    }
1903
1904
    /// Two history-only states hold the same changes and render the same
1905
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1906
    /// the checkpoint's graphs as the bases of its files' histories.
1907
    #[cfg(test)]
1908954×
    fn assert_same_state(&self, a: &State, b: &State) {
19091908×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1910954×
        assert_eq!(ids(a), ids(b), "the same changes");
19111908×
        let files = |s: &State| {
19121908×
            let mut s = s.clone();
19131908×
            self.load_all_graphs(&mut s).unwrap();
19141908×
            s.materialize().files
19151908×
        };
1916954×
        assert_eq!(files(a), files(b), "the same files");
1917954×
    }
1918
1919
    /// The state index file: its heads, a hash of its changes block and one
1920
    /// of the rest, then the body [`State::write_index`] gives, whose first
1921
    /// block is the changes. Hashed in two parts so the log can read and
1922
    /// check the changes alone.
1923
    /// The index of `deps` if there is one, else the newest, which the
1924
    /// caller may bring up to date.
19252440×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1926
        use std::io::Read;
19272440×
        let _t = crate::timing::phase("load: state index");
19282440×
        let exact = self.state_index_path(deps);
19292440×
        let reading = crate::timing::phase("load:   of which reading the file");
19302440×
        let mut f = match fs::File::open(&exact) {
1931287×
            Ok(f) => {
1932
                // Used now: the newest, so the last to be dropped.
1933287×
                let _ = fs::File::options()
1934287×
                    .write(true)
1935287×
                    .open(&exact)
1936287×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1937287×
                f
1938
            }
19392153×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1940
        };
19411974×
        let total = f.metadata().ok()?.len();
19421974×
        let mut word = [0u8; 4];
19431974×
        f.read_exact(&mut word).ok()?;
19441974×
        let n = u32::from_le_bytes(word) as usize;
19451974×
        let mut head = vec![0u8; 32 * n + 64 + 8];
19461974×
        f.read_exact(&mut head).ok()?;
19471974×
        let heads: Vec<ChangeHash> = head[..32 * n]
19481974×
            .chunks_exact(32)
19491974×
            .map(|c| ObjectRef(c.try_into().unwrap()))
19501974×
            .collect();
19511974×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
19521974×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
19531974×
        let at = (4 + head.len()) as u64;
19541974×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
19550×
            return None;
19561974×
        }
1957
        // The front only: the files' histories after it are read, each
1958
        // checked by its own hash, when a command builds that file.
19591974×
        let mut front = vec![0u8; front_len as usize];
19601974×
        f.read_exact(&mut front).ok()?;
19611974×
        drop(reading);
19621974×
        let checking = crate::timing::phase("load:   of which checking the file");
19631974×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
19641974×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
19653948×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
19661974×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
19670×
            return None;
19681974×
        }
19691974×
        drop(checking);
19701974×
        let histories = crate::state::Histories::File(
19711974×
            std::sync::Arc::new(f),
19721974×
            at + front_len,
19731974×
            total - at - front_len,
19741974×
        );
19751974×
        Some((State::read_index_front(&front, histories).ok()?, heads))
19762440×
    }
1977
1978
    /// The changes of this workspace's state index (the closure of its
1979
    /// heads), read without the rest of the index.
1980
    #[allow(clippy::type_complexity)]
1981184×
    pub(crate) fn read_state_index_changes(
1982184×
        &self,
1983184×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1984
        use std::io::Read;
1985184×
        let _t = crate::timing::phase("load: state index changes");
1986184×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1987167×
        let mut word = [0u8; 4];
1988167×
        f.read_exact(&mut word).ok()?;
1989167×
        let n = u32::from_le_bytes(word) as usize;
1990
        // Heads, the two sums, the front's length, then the changes block.
1991167×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1992167×
        f.read_exact(&mut head).ok()?;
1993167×
        let heads: Vec<ChangeHash> = head[..32 * n]
1994167×
            .chunks_exact(32)
1995167×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1996167×
            .collect();
1997167×
        let sum = &head[32 * n..32 * n + 32];
1998167×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1999167×
        let mut changes = vec![0u8; 4 + len];
2000167×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
2001167×
        f.read_exact(&mut changes[4..]).ok()?;
2002167×
        let checking = crate::timing::phase("load:   of which checking");
2003167×
        let mut h = blake3::Hasher::new();
2004167×
        h.update_rayon(&changes);
2005167×
        if h.finalize().as_bytes() != sum {
20060×
            return None;
2007167×
        }
2008167×
        drop(checking);
2009167×
        let _decoding = crate::timing::phase("load:   of which decoding");
2010167×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
2011184×
    }
2012
2013
    /// Save `st`, the history-only state of `deps`, as this workspace's
2014
    /// state index; quietly nothing when it cannot be (it is only a cache).
2015474×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
2016474×
        let _t = crate::timing::phase("write: state index");
2017474×
        let encoding = crate::timing::phase("write:   of which encoding");
2018474×
        let Some(body) = st.write_index() else {
20190×
            return;
2020
        };
2021474×
        drop(encoding);
2022
        #[cfg(test)]
2023277×
        assert_eq!(
2024277×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
2025277×
            Some(body.clone()),
2026
            "a state index reads back as written"
2027
        );
2028474×
        let mut heads = st.maximal(deps);
2029474×
        heads.sort();
2030474×
        let mut w = crate::flat::Writer::default();
2031474×
        w.count(heads.len());
2032474×
        for h in &heads {
203310×
            w.object(h);
203410×
        }
2035
        // The body is the front's length, the front, then the files'
2036
        // histories, which carry their own hashes: the sums cover the
2037
        // front's changes block and the rest of the front.
2038474×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
2039474×
        let front = &body[8..8 + front_len];
2040474×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
2041948×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
2042474×
        w.fixed(&sum(&front[..split]));
2043474×
        w.fixed(&sum(&front[split..]));
2044474×
        w.fixed(&body);
2045474×
        let path = self.state_index_path(&heads);
2046474×
        let _ = fs::create_dir_all(self.oxy.join("index"));
2047474×
        let _ = write_cache(&path, &w.0);
2048
        // The last two used: the index of a state moved away from stays for
2049
        // a move back. Older ones (and the unnamed one of before) go.
2050474×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
20511×
            let _ = fs::remove_file(old);
20521×
        }
2053474×
        let _ = fs::remove_file(
2054474×
            self.oxy
2055474×
                .join("index")
2056474×
                .join(format!("state-{}", self.workspace.to_hex())),
2057474×
        );
2058474×
    }
2059
20606×
    fn locks_dir(&self) -> PathBuf {
20616×
        self.oxy.join("locks")
20626×
    }
2063
2064
    /// Whether `path` is locked locally for editing (spec §18, advisory).
20653×
    pub fn is_locked(&self, path: &str) -> bool {
20663×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
20673×
    }
2068
2069
    /// Take the advisory local lock on a `lockable` file and make it writable.
20702×
    pub fn lock_path(&self, path: &str) -> Result<()> {
20712×
        let attrs = self.disk_attributes();
20722×
        if !attrs.lookup(path).lockable {
20731×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
20741×
        }
20751×
        fs::create_dir_all(self.locks_dir())?;
20761×
        write_atomic(
20771×
            &self.locks_dir().join(path.replace('/', "%2F")),
20781×
            std::process::id().to_string().as_bytes(),
20790×
        )?;
20801×
        set_readonly(&self.root.join(path), false)?;
20811×
        Ok(())
20822×
    }
2083
2084
    /// Release the local lock and make the file read-only again.
20851×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
20861×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
20871×
        if self.root.join(path).exists() {
20881×
            set_readonly(&self.root.join(path), true)?;
20890×
        }
20901×
        Ok(())
20911×
    }
2092
2093
    /// Whether a repository path is inside the sparse filter (spec §17).
209425240×
    pub fn in_scope(&self, path: &str) -> bool {
209525240×
        self.config.sparse_paths.is_empty()
209682×
            || self
209782×
                .config
209882×
                .sparse_paths
209982×
                .iter()
210099×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
210125240×
    }
2102
21031×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
21041×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
21051×
    }
2106
2107
    /// Walk the working copy; with a manifest, a file whose size and mtime
2108
    /// match it is not read: an opaque file yields its known blob, and a
2109
    /// text file whose recorded graph key equals its base graph's key in
2110
    /// `keys` (path → key) is marked unchanged; other text files are read
2111
    /// but keep their known hash. Files modified within two seconds of the
2112
    /// manifest are never trusted (a racy stat).
2113
    ///
2114
    /// `.oxyattributes` files are always read, since their content is
2115
    /// needed; and when any of them is not known unchanged (added, removed,
2116
    /// edited, or changed in the base), no text file is taken as unchanged,
2117
    /// because attributes decide how a file compares with the base.
2118
    ///
2119
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2120
    /// (the base state's files) that exists on disk is included even when
2121
    /// an ignore rule matches it, as in Git.
21221574×
    fn walk_working_copy_with(
21231574×
        &self,
21241574×
        cache: Option<&prompt::Manifest>,
21251574×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
21261574×
        keys: Option<&KeyOf>,
21271574×
    ) -> Result<BTreeMap<String, FsEntry>> {
2128
        let mut out: BTreeMap<String, FsEntry>;
21291574×
        let sparse = &self.config.sparse_paths;
21309637×
        let in_scope = |p: &str| {
21319637×
            sparse.is_empty()
21327×
                || sparse
21337×
                    .iter()
21347×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
21359637×
        };
21361574×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2137
        let walk::Listing {
21381574×
            files,
21391574×
            symlinks,
21401574×
            nested,
21411574×
            dirs,
21421574×
        } = match self.listing_cache.take() {
2143205×
            Some(l) => l,
2144
            // Ignore rules apply to untracked paths only, so the base's
2145
            // files are not matched against them (an added file is: a rule
2146
            // written after it was snapshotted leaves it out again).
21479649×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2148
        };
2149
        // A new file larger than the limit is left out and named, not taken
2150
        // in unseen (oxygen#98): a build's output or a downloaded image
2151
        // would otherwise be stored by the next status, kept by the
2152
        // operation log. Files tracked, or already in the working copy, stay.
21531574×
        let limit = self.config.max_new_file;
21541574×
        let mut skipped = Vec::new();
21551574×
        let files: Vec<_> = files
21561574×
            .into_iter()
215712677×
            .filter(|(rel, _, meta)| {
215812677×
                let new = !tracked.contains_key(rel)
21593218×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
216012677×
                if limit > 0 && new && meta.size > limit {
21613×
                    skipped.push((rel.clone(), meta.size));
21623×
                    return false;
216312674×
                }
216412674×
                true
216512677×
            })
21661574×
            .collect();
21671574×
        *self.skipped_large.borrow_mut() = skipped;
21681574×
        let keys = keys.filter(|k| {
216912661×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
21701570×
            let attrs_unchanged =
21711570×
                files
21721570×
                    .iter()
217312624×
                    .filter(|(r, _, _)| is_attributes(r))
21741570×
                    .all(|(rel, _, meta)| {
217518×
                        stat_cached(rel, meta, cache)
217618×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
217718×
                    });
21781570×
            let none_removed = tracked
21791570×
                .keys()
21809562×
                .filter(|r| is_attributes(r))
21811570×
                .all(|r| on_disk.contains(r.as_str()));
21821570×
            attrs_unchanged && none_removed
21831570×
        });
21841574×
        *self.walked_dirs.borrow_mut() =
21851574×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
21861574×
        drop(walk_phase);
21871574×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2188
        // Reading files is most of a walk's cost; do it in parallel.
2189
        {
2190
            use rayon::prelude::*;
21911574×
            let mut read: Vec<(String, FsEntry)> = files
21921574×
                .par_iter()
219312674×
                .map(|(rel, path, meta)| {
2194
                    // A key is worked out only for a file the manifest
2195
                    // knows with the same stat and a key of its own.
219612674×
                    let key = keys
219712674×
                        .filter(|_| !is_attributes(rel))
219812674×
                        .filter(|_| {
219912606×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
220012606×
                        })
220112674×
                        .and_then(|k| k(rel));
220212674×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
220312674×
                })
22041574×
                .collect::<Result<Vec<_>>>()?;
220512672×
            for (rel, e) in read.iter_mut() {
2206
                // A cached blob the store lost (gc, a partial clone): read the file after all.
220712672×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
22080×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
22090×
                    e.blob = None;
221012672×
                }
2211
            }
2212
            // The listing is in path order, so the map is built without
2213
            // searching.
22141573×
            out = read.into_iter().collect();
22151573×
            for (rel, target) in symlinks {
22162×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
22172×
            }
2218
        }
22191573×
        drop(_read_phase);
22201573×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2221
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2222
        // already tracked as subrepo nodes, they contribute their pin;
2223
        // unregistered ones are left alone.
22241573×
        let modules = self.modules_on_disk();
22251573×
        let removed = self.removed_subrepos();
22261573×
        for rel in &removed {
22273×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
22281×
                self.clear_removed_subrepo(rel);
22292×
            }
2230
        }
22311573×
        let mut untracked_nested = Vec::new();
22321573×
        for dir in nested {
223350×
            let rel = self.rel_path(&dir);
223450×
            if !self.in_scope(&rel) || removed.contains(&rel) {
22353×
                continue;
223647×
            }
223747×
            let registered = modules.entries.get(&rel);
223847×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2239
            {
22401×
                untracked_nested.push(rel);
22411×
                continue;
224246×
            }
224346×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
224446×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2245
        }
22461573×
        untracked_nested.sort();
22471573×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2248
        // Tracked paths the ignore rules hid.
22491573×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
225079×
            if !self.in_scope(rel) {
225110×
                continue;
225269×
            }
225369×
            let path = self.root.join(rel);
225469×
            if *kind == NodeKind::Subrepo {
22553×
                if removed.contains(rel) {
22562×
                    continue;
22571×
                }
22581×
                let present =
22591×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
22601×
                if present {
22610×
                    let pin = subrepos::read_pin(
22620×
                        &path,
22630×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
22640×
                    )?;
22650×
                    out.insert(
22660×
                        rel.clone(),
22670×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2268
                    );
22691×
                } else if let Some(b) = blob {
22701×
                    // Not cloned (or emptied): the pin stays as recorded, as a
22711×
                    // Git gitlink does when its directory is absent.
22721×
                    out.insert(
22731×
                        rel.clone(),
22741×
                        FsEntry {
22751×
                            blob: Some(*b),
22761×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
22771×
                        },
22781×
                    );
22791×
                }
22801×
                continue;
228166×
            }
228266×
            let Ok(meta) = fs::symlink_metadata(&path) else {
228366×
                continue;
2284
            };
22850×
            let ft = meta.file_type();
22860×
            if ft.is_symlink() {
22870×
                let target = fs::read_link(&path)?;
22880×
                out.insert(
22890×
                    rel.clone(),
22900×
                    FsEntry::new(
22910×
                        NodeKind::Symlink,
2292
                        false,
22930×
                        target.to_string_lossy().as_bytes().to_vec(),
2294
                    ),
2295
                );
22960×
            } else if ft.is_file() {
22970×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
22980×
                out.insert(rel.clone(), e);
22990×
            }
2300
        }
23011573×
        Ok(out)
23021574×
    }
2303
2304
    /// The entry for one regular file, read or served from the stat cache.
23050×
    fn file_entry(
23060×
        &self,
23070×
        rel: &str,
23080×
        path: &Path,
23090×
        meta: &walk::Stat,
23100×
        cache: Option<&prompt::Manifest>,
23110×
    ) -> Result<FsEntry> {
23120×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
23130×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
23140×
            e.content = std::sync::Arc::new(fs::read(path)?);
23150×
            e.blob = None;
23160×
        }
23170×
        Ok(e)
23180×
    }
2319
2320
    /// The non-directory paths of a snapshot with their kinds, for the
2321
    /// walker's `tracked` set.
23223×
    pub(crate) fn tracked_kinds(
23233×
        snapshot: &Snapshot,
23243×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
23253×
        snapshot
23263×
            .files
23273×
            .iter()
232812×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
23298×
            .map(|(p, f)| {
23308×
                let blob = match &f.content {
23314×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
23324×
                    _ => None,
2333
                };
23348×
                (p.clone(), (f.kind, blob))
23358×
            })
23363×
            .collect()
23373×
    }
2338
2339
    /// A path under the root as a `/`-separated relative string.
2340108×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
2341108×
        path.strip_prefix(&self.root)
2342108×
            .unwrap_or(path)
2343108×
            .components()
2344194×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
2345108×
            .collect::<Vec<_>>()
2346108×
            .join("/")
2347108×
    }
2348
}
2349
2350
impl Repo {
2351
    /// Changes reachable from the bookmark and the working copy, newest first.
2352103×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
2353103×
        let heads = self.bookmark_heads()?;
2354103×
        if self.bare {
23551×
            return self.log_state(&heads);
2356102×
        }
2357102×
        let (wc_hash, wc) = self.working_copy()?;
2358102×
        let mut all = heads.clone();
2359102×
        all.push(wc_hash);
2360102×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
2361102×
        let mut entries: Vec<LogEntry> = Vec::new();
2362
        // A shallow clone knows changes beyond its boundary from a
2363
        // checkpoint's metadata only: its log comes from the state.
2364102×
        let metas = if self.is_shallow() {
23652×
            self.load_state_history(&all)?
23662×
                .changes()
236712×
                .map(|(h, m)| (*h, m.clone()))
23682×
                .collect()
2369
        } else {
2370
            // The working copy's change is in hand, and is never in the
2371
            // state index: its metadata is not looked up again.
2372100×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
2373100×
            below.extend(wc.deps.iter().copied());
2374100×
            let _t = crate::timing::phase("log: metadata");
2375100×
            let mut metas = self.metas_of(&below)?;
2376349×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
2377100×
                // First, where the log puts it, so the order may hold.
2378100×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
2379100×
            }
2380100×
            metas
2381
        };
2382102×
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2383461×
            hash: h,
2384461×
            change: meta,
2385461×
            is_working_copy: h == wc_hash,
2386461×
            is_head: head_set.contains(&h),
2387461×
        }));
2388102×
        let _sorting = crate::timing::phase("log: sort");
2389
        // The hash makes the order total, so an unstable sort gives the same.
2390
        // From the state index the order already holds (oxygen#94).
2391877×
        let order = |a: &LogEntry, b: &LogEntry| {
2392877×
            b.is_working_copy
2393877×
                .cmp(&a.is_working_copy)
2394877×
                .then(crate::state::log_order(
2395877×
                    (&a.hash, &a.change.hlc),
2396877×
                    (&b.hash, &b.change.hlc),
2397
                ))
2398877×
        };
2399221×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
240057×
            entries.sort_unstable_by(order);
240157×
        }
2402102×
        Ok(entries)
2403103×
    }
2404
2405
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2406
    /// count, for paginated views.
24070×
    pub fn log_window(
24080×
        &self,
24090×
        heads: &[ChangeHash],
24100×
        offset: usize,
24110×
        limit: usize,
24120×
    ) -> Result<(Vec<LogEntry>, usize)> {
24130×
        let all = self.log_state(heads)?;
24140×
        let total = all.len();
24150×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
24160×
    }
2417
2418
    /// The log of the state with these heads, newest first, with no working
2419
    /// copy involved (for hosted repositories and any explicit state).
242010×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2421
        // The log needs change metadata only: neither graphs nor the tree.
242210×
        if self.is_shallow() {
24230×
            return Ok(self.log_of(&self.load_state_history(heads)?));
242410×
        }
242510×
        let metas = self.metas_of(heads)?;
242610×
        let depended: BTreeSet<ChangeHash> = metas
242710×
            .iter()
242830×
            .flat_map(|(_, m)| m.deps.iter().copied())
242910×
            .collect();
243010×
        let mut entries: Vec<LogEntry> = metas
243110×
            .into_iter()
243210×
            .map(|(h, meta)| LogEntry {
243330×
                hash: h,
243430×
                is_head: !depended.contains(&h),
243530×
                change: meta,
2436
                is_working_copy: false,
243730×
            })
243810×
            .collect();
243943×
        let order = |a: &LogEntry, b: &LogEntry| {
244043×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
244143×
        };
244216×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
24433×
            entries.sort_unstable_by(order);
24447×
        }
244510×
        Ok(entries)
244610×
    }
2447
2448
    /// Every change of the state with these heads and its metadata, read
2449
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2450
    /// a shallow clone's boundary is left out.
2451184×
    pub fn metas_of(
2452184×
        &self,
2453184×
        heads: &[ChangeHash],
2454184×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2455184×
        let boundary = self.boundary();
2456
        // The state index holds the metadata of its heads' closure: a
2457
        // change found there is not read from the store (a change object
2458
        // can be as large as the tree it adds).
2459184×
        let read = self.read_state_index_changes();
2460
        // Every one of `heads` in the index, and every head of the index
2461
        // among them: their closure is the index's changes, all of them
2462
        // (it is closed), and no walk is needed to find it.
2463184×
        if let Some((index_heads, all)) = &read {
2464167×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2465167×
            let in_index = || {
2466167×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2467167×
                    index_heads.iter().collect();
2468
                // Usually the heads asked are the index's: no set of all.
2469167×
                heads.iter().all(|h| index_heads.contains(h)) || {
2470167×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2471167×
                        all.iter().map(|(h, _)| h).collect();
2472167×
                    heads.iter().all(|h| all.contains(h))
2473
                }
2474167×
            };
2475167×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
24760×
                let (_, all) = read.expect("matched above");
2477
                #[cfg(test)]
2478
                {
2479
                    // The walk the shortcut saves finds the same changes.
24800×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
24810×
                    let mut stack = heads.to_vec();
24820×
                    while let Some(h) = stack.pop() {
24830×
                        if seen.insert(h) {
24840×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
24850×
                        }
2486
                    }
24870×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2488
                }
24890×
                return Ok(all);
2490167×
            }
249117×
        }
2492184×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2493184×
            read.map(|(_, all)| all.into_iter().collect());
2494184×
        let _walk = crate::timing::phase("metadata: walk");
2495184×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2496184×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2497184×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2498184×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
24991330×
        while let Some(h) = stack.pop() {
25001146×
            if !seen.insert(h) {
2501483×
                continue;
2502663×
            }
2503
            // Taken out of the index's map, each once: not copied.
2504663×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2505
                #[cfg(test)]
25060×
                assert_eq!(
2507
                    meta,
25080×
                    self.store.get_change_meta(&h)?,
2509
                    "the state index holds a change's metadata"
2510
                );
25110×
                stack.extend(meta.deps.iter().copied());
25120×
                out.push((h, meta));
25130×
                continue;
2514663×
            }
2515663×
            let started = std::time::Instant::now();
2516663×
            let meta = match self.store.get_change_meta(&h) {
2517663×
                Ok(m) => m,
25180×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
25190×
                Err(e) => return Err(e.into()),
2520
            };
2521663×
            stored += 1;
2522663×
            from_store += started.elapsed();
2523663×
            stack.extend(meta.deps.iter().copied());
2524663×
            out.push((h, meta));
2525
        }
2526184×
        if stored > 0 && crate::timing::enabled() {
25270×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2528184×
        }
2529184×
        Ok(out)
2530184×
    }
2531
2532
    /// The log of a state already loaded, newest first.
2533
    /// The history of lines `first..=last` (1-based) of `path` in the
2534
    /// state `heads` make (spec §27): every change that inserted or
2535
    /// deleted one of their atoms, or an atom deleted from between them,
2536
    /// newest first. Exact, as atoms keep their identity across edits.
25376×
    pub fn line_history(
25386×
        &self,
25396×
        heads: &[ChangeHash],
25406×
        path: &str,
25416×
        first: usize,
25426×
        last: usize,
25436×
    ) -> Result<Vec<LogEntry>> {
25446×
        if first == 0 || last < first {
25451×
            return fail(format!(
2546
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2547
            ));
25485×
        }
25495×
        let mut state = self.load_state_history(heads)?;
25505×
        let Some(node) = self
25515×
            .tree_view(&mut state)?
2552
            .entries
25535×
            .get(path)
25545×
            .map(|e| e.node)
2555
        else {
25561×
            return fail(format!("{path} is not in that state"));
2557
        };
25584×
        self.load_graphs_of(&mut state, &[node])?;
25594×
        let live = state.live_lines(&node);
25604×
        if last > live.len() {
25611×
            return fail(format!(
2562
                "{path} has {} lines; asked for {first},{last}",
25631×
                live.len()
2564
            ));
25653×
        }
25663×
        let Some(g) = state.file(&node) else {
25670×
            return fail(format!("{path} is not a text file"));
2568
        };
25693×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
25703×
        let touched = g.touching(&atoms);
25713×
        Ok(self
25723×
            .log_of(&state)
25733×
            .into_iter()
257413×
            .filter(|e| touched.contains(&e.hash))
25753×
            .collect())
25766×
    }
2577
25788×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
25798×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
25808×
        let mut entries: Vec<LogEntry> = state
25818×
            .changes()
25828×
            .map(|(h, meta)| LogEntry {
258331×
                hash: *h,
258431×
                change: meta.clone(),
2585
                is_working_copy: false,
258631×
                is_head: head_set.contains(h),
258731×
            })
25888×
            .collect();
258944×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
25908×
        entries
25918×
    }
2592
2593
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2594
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2595
    /// (`resolve_change`).
259667×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
259767×
        let view = self.view()?;
259867×
        if let Some(st) = view.bookmarks.get(spec) {
259939×
            return Ok(self.store.get_state(st)?.heads);
260028×
        }
260128×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
26022×
            return Ok(self.store.get_state(&st)?.heads);
260326×
        }
260426×
        if let Some(heads) = self.tag_heads(spec)? {
26052×
            return Ok(heads);
260624×
        }
260724×
        Ok(vec![self.resolve_change(spec)?])
260867×
    }
2609
2610
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2611
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
261237×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
261337×
        if spec == "@" {
26140×
            return Ok(self.working_copy()?.0);
261537×
        }
261637×
        let view = self.view()?;
261737×
        let named = match view.bookmarks.get(spec) {
26181×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
261936×
            None => match remote_bookmark(&view, spec) {
26201×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
262135×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2622
            },
2623
        };
262437×
        if let Some((kind, heads)) = named {
26253×
            return match heads.len() {
26263×
                1 => Ok(heads[0]),
26270×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2628
            };
262934×
        }
263034×
        if spec.is_empty() || spec == "#" {
26310×
            return fail("empty change specifier");
263234×
        }
263334×
        let entries = self.log()?;
2634
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2635
        // cannot be a ChangeId, which has 32 (oxygen#103).
263634×
        let full_hash =
2637128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
263834×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
263928×
            entries
264028×
                .iter()
2641112×
                .filter(|e| e.hash.starts_with_hex(hp))
264228×
                .collect()
2643
        } else {
26446×
            entries
26456×
                .iter()
264621×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
26476×
                .collect()
2648
        };
264934×
        match matches.len() {
265029×
            1 => Ok(matches[0].hash),
26515×
            0 => match self.resolve_in_remotes(spec)? {
26521×
                Some(h) => Ok(h),
26534×
                None => fail(format!("no change matches {spec:?}")),
2654
            },
2655
            _ => {
26560×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
26570×
                if ids.len() == 1 {
26580×
                    fail(format!(
2659
                        "change {spec} is divergent: {} variants",
26600×
                        matches.len()
2661
                    ))
2662
                } else {
26630×
                    fail(format!("{spec:?} is ambiguous"))
2664
                }
2665
            }
2666
        }
266737×
    }
2668
2669
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2670
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2671
    /// `None` when none matches, or more than one.
26725×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
26735×
        let view = self.view()?;
26745×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
26755×
        for bookmarks in view.remotes.values() {
26763×
            for st in bookmarks.values() {
26773×
                let heads = self.store.get_state(st)?.heads;
26787×
                for e in self.log_state(&heads)? {
26797×
                    let hit = match spec.strip_prefix('#') {
26802×
                        Some(hp) => e.hash.starts_with_hex(hp),
26815×
                        None => e.change.change_id.starts_with_hex(spec),
2682
                    };
26837×
                    if hit {
26841×
                        found.insert(e.hash);
26856×
                    }
2686
                }
2687
            }
2688
        }
26895×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
26905×
    }
2691
2692
    /// Where a change is when no local bookmark or the working copy holds
2693
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2694
    /// it is held locally, or nowhere.
26954×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
26968×
        if self.log()?.iter().any(|e| e.hash == *hash) {
26973×
            return Ok(None);
26981×
        }
26991×
        let view = self.view()?;
27001×
        for (remote, bookmarks) in &view.remotes {
27011×
            for (name, st) in bookmarks {
27021×
                let heads = self.store.get_state(st)?.heads;
27031×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
27041×
                    return Ok(Some(format!("{remote}/{name}")));
27050×
                }
2706
            }
2707
        }
27080×
        Ok(None)
27094×
    }
2710
2711
    /// Human-readable description of what a change does, with line content.
27124×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
27134×
        let change = self.store.get_change(hash)?;
27144×
        let (base, base_snapshot) = self.change_base(&change)?;
27154×
        Ok(render_change(&change, &base, &base_snapshot))
27164×
    }
2717
2718
    /// The base state of `change` (its dependencies) and its rendering, as
2719
    /// much as showing the change needs: the whole tree, and the graphs and
2720
    /// contents of the files the change edits. Other text files are left
2721
    /// unrendered ([`Snapshot::unrendered`]).
27228×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
27238×
        let base = self.load_state_history(&change.deps)?;
27248×
        self.render_base_for(change, base)
27258×
    }
2726
2727
    /// The base for showing `change` alone: the graphs of the files it
2728
    /// edits built, and the base's tree with no file rendered, which is
2729
    /// all [`render_change`](snapshot::render_change) and
2730
    /// [`diff_files_of`](snapshot::diff_files_of) read.
27313×
    pub(crate) fn tree_base_for(
27323×
        &self,
27333×
        change: &Change,
27343×
        mut base: State,
27353×
    ) -> Result<(State, Snapshot)> {
27363×
        let _t = crate::timing::phase("diff: the base's tree");
27373×
        let edited: std::collections::HashSet<NodeId> =
27388×
            change.edits.iter().map(|e| e.node()).collect();
27393×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
27403×
        self.load_graphs_of(&mut base, &nodes)?;
27413×
        let snapshot = Snapshot {
27423×
            tree: self.tree_view(&mut base)?,
27433×
            files: BTreeMap::new(),
27443×
            unrendered: BTreeSet::new(),
2745
        };
27463×
        Ok((base, snapshot))
27473×
    }
2748
2749
    /// [`Repo::change_base`] with the base already loaded (the working
2750
    /// copy's comes from the state index).
2751232×
    pub(crate) fn render_base_for(
2752232×
        &self,
2753232×
        change: &Change,
2754232×
        mut base: State,
2755232×
    ) -> Result<(State, Snapshot)> {
2756232×
        let _t = crate::timing::phase("diff: render the base");
2757232×
        let edited: std::collections::HashSet<NodeId> =
2758437×
            change.edits.iter().map(|e| e.node()).collect();
2759232×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2760232×
        self.load_graphs_of(&mut base, &nodes)?;
2761232×
        self.tree_view(&mut base)?;
2762232×
        let snapshot = {
2763232×
            let _t = crate::timing::phase("diff:   of which materialize");
2764232×
            base.materialize_nodes(&edited)
2765
        };
2766232×
        Ok((base, snapshot))
2767232×
    }
2768
}
2769
27700×
fn remove_any(path: &Path) -> std::io::Result<()> {
27710×
    let m = fs::symlink_metadata(path)?;
27720×
    if m.is_dir() {
27730×
        fs::remove_dir_all(path)
2774
    } else {
27750×
        fs::remove_file(path)
2776
    }
27770×
}
2778
27795×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
27805×
    let mut perms = fs::metadata(path)?.permissions();
27815×
    perms.set_readonly(readonly);
27825×
    fs::set_permissions(path, perms)
27835×
}
2784
2785
#[cfg(unix)]
27865930×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2787
    use std::os::unix::fs::PermissionsExt;
27885930×
    let mut perms = fs::metadata(path)?.permissions();
27895930×
    let mode = perms.mode();
27905930×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
27915930×
    if want != mode {
27926×
        perms.set_mode(want);
27936×
        fs::set_permissions(path, perms)?;
27945924×
    }
27955930×
    Ok(())
27965930×
}
2797
#[cfg(not(unix))]
2798
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2799
    Ok(())
2800
}
2801
2802
#[cfg(unix)]
280317094×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2804
    use std::os::unix::fs::PermissionsExt;
280517094×
    m.permissions().mode() & 0o111 != 0
280617094×
}
2807
#[cfg(not(unix))]
2808
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2809
    false
2810
}
2811
281213487×
fn op_ref(k: OpKey) -> OpRef {
281313487×
    OpRef {
281413487×
        change: k.0,
281513487×
        index: k.1,
281613487×
    }
281713487×
}
2818
28196231×
fn split_path(path: &str) -> (&str, &str) {
28206231×
    match path.rfind('/') {
28215063×
        Some(i) => (&path[..i], &path[i + 1..]),
28221168×
        None => ("", path),
2823
    }
28246231×
}
2825
2826
/// Whether `rel` is an attributes file (spec §7.6).
282769809×
fn is_attributes(rel: &str) -> bool {
282869809×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
282969809×
}
2830
2831
/// The manifest entry for `rel` when its size and mtime match it outside
2832
/// the racy window.
283325298×
fn stat_cached<'m>(
283425298×
    rel: &str,
283525298×
    meta: &walk::Stat,
283625298×
    cache: Option<&'m prompt::Manifest>,
283725298×
) -> Option<&'m prompt::ManifestEntry> {
283825298×
    let m = cache?;
283920263×
    let e = m.entries.get(rel)?;
284018828×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
284118828×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
284225298×
}
2843
2844
/// Read one working-copy file, or serve it from the stat cache (spec
2845
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2846
/// an opaque file is not read at all (its stored blob stands in), and a
2847
/// text file the manifest recorded equal to a base graph whose key is
2848
/// `key`, the key the base has now, is not read either: equal keys mean
2849
/// equal renderings, so it still equals the base. Touches no repository
2850
/// state, so the walk runs it in parallel; the caller checks that a cached
2851
/// blob is still in the store.
285212674×
fn read_file_entry(
285312674×
    rel: &str,
285412674×
    path: &Path,
285512674×
    meta: &walk::Stat,
285612674×
    cache: Option<&prompt::Manifest>,
285712674×
    key: Option<[u8; 32]>,
285812674×
) -> Result<FsEntry> {
285912674×
    let exec = meta.exec;
286012674×
    let stat = Some((meta.size, meta.mtime_ns));
286112674×
    let mut e = match stat_cached(rel, meta, cache) {
28624247×
        Some(e) if e.blob.is_some() => FsEntry {
28631×
            blob: e.blob,
28641×
            content_hash: Some(e.hash),
28651×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28661×
        },
28674246×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
28684241×
            content_hash: Some(e.hash),
28694241×
            unchanged: true,
28704241×
            graph_key: e.graph,
28714241×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28724241×
        },
28735×
        Some(e) => FsEntry {
28745×
            content_hash: Some(e.hash),
28755×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2876
        },
28778427×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2878
    };
2879
    // The stat the manifest records: taken before the read, so a file that
2880
    // changes meanwhile is read again next time.
288112673×
    e.stat = stat;
288212673×
    Ok(e)
288312674×
}
2884
2885
/// Two maps side by side in key order: each key of either, with its value
2886
/// in each. Linear, with no lookups, for maps of a whole tree.
28873045×
pub(crate) fn join<'a, A, B>(
28883045×
    a: &'a BTreeMap<String, A>,
28893045×
    b: &'a BTreeMap<String, B>,
28903045×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
28913045×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
289236750×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
28933045×
        (None, None) => None,
28943006×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
28955978×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
289624721×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2897344×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2898316×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2899
            std::cmp::Ordering::Equal => {
290024061×
                let (k, va) = a.next()?;
290124061×
                let (_, vb) = b.next()?;
290224061×
                Some((k, Some(va), Some(vb)))
2903
            }
2904
        },
290536750×
    })
29063045×
}
2907
2908
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2909
/// lookups.
29101574×
pub(crate) fn missing_from<'a, A, B>(
29111574×
    a: &'a BTreeMap<String, A>,
29121574×
    b: &BTreeMap<String, B>,
29131574×
) -> Vec<(&'a String, &'a A)> {
29141574×
    let mut keys = b.keys().peekable();
29151574×
    a.iter()
29169572×
        .filter(|(k, _)| {
291718277×
            while keys.next_if(|kb| *kb < *k).is_some() {}
29189572×
            keys.peek() != Some(k)
29199572×
        })
29201574×
        .collect()
29211574×
}