OXYGENHUB

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

1899 of 2132 lines run, 445 of 721 functions · run #405 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.
752868×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762868×
    let Some(url) = &config.storage_url else {
772863×
        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×
    )?)
1002868×
}
101
102183×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103183×
    Err(RepoError::Msg(s.into()))
104183×
}
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::{create_user_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.
1685549×
pub(crate) fn name_file(name: &str) -> String {
1695549×
    name.replace('%', "%25").replace('/', "%2F")
1705549×
}
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
1778628×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1788628×
    Ok(crate::durable::write_atomic(path, data)?)
1798628×
}
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
1953377×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1963377×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1973377×
    fs::write(&tmp, data)?;
1983377×
    fs::rename(&tmp, path)?;
1993377×
    Ok(())
2003377×
}
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 {
24023422×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
24123422×
        FsEntry {
24223422×
            kind,
24323422×
            exec,
24423422×
            content: std::sync::Arc::new(content),
24523422×
            blob: None,
24623422×
            content_hash: None,
24723422×
            unchanged: false,
24823422×
            graph_key: None,
24923422×
            stat: None,
25023422×
        }
25123422×
    }
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/`.
3178889×
pub fn default_home() -> PathBuf {
3188889×
    if let Ok(h) = std::env::var("OXY_HOME") {
3198862×
        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")
3328889×
}
333
3342871×
pub fn default_keys_dir() -> PathBuf {
3352871×
    default_home().join("keys")
3362871×
}
337
3385738×
pub fn default_user_config() -> PathBuf {
3395738×
    default_home().join("config.toml")
3405738×
}
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
354272×
    pub fn init(root: &Path) -> Result<Repo> {
355272×
        let mut id = [0u8; 16];
356272×
        rand::rngs::OsRng.fill_bytes(&mut id);
357272×
        Self::init_with_id(root, id)
358272×
    }
359
360
    /// Initialize a repository with a given repository ID (clones share the
361
    /// ID of their origin, spec §14.4).
362562×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
363562×
        Self::init_on(root, id, None)
364562×
    }
365
366
    /// A new repository with a fresh id, bare or not, on `storage` or in
367
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
36813×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
36913×
        let mut id = [0u8; 16];
37013×
        rand::rngs::OsRng.fill_bytes(&mut id);
37113×
        if bare {
3720×
            Self::init_bare_on(root, id, storage)
373
        } else {
37413×
            Self::init_on(root, id, storage)
375
        }
37613×
    }
377
378
    /// Initialize a repository whose objects and operation head are kept
379
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
380578×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
381578×
        fs::create_dir_all(root)?;
382578×
        let root = crate::portable::canonical(root).unwrap_or_else(|_| root.to_path_buf());
383578×
        let oxy = root.join(OXY_DIR);
384578×
        if oxy.exists() {
3851×
            return fail(format!("{} is already an oxy repository", root.display()));
386577×
        }
387577×
        fs::create_dir_all(oxy.join("ops"))?;
388577×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
389577×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
390577×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
391577×
        if let Some(url) = storage {
3923×
            config.set("storage.url", url)?;
393574×
        }
394577×
        config.save(&oxy.join("config"))?;
395577×
        let workspace = WorkspaceId::random();
396577×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
397577×
        let store = open_objects(&oxy, &config)?;
398576×
        let repo = Repo {
399576×
            acceptor: None,
400576×
            keyless_key: Default::default(),
401576×
            last_change: Default::default(),
402576×
            at_op: None,
403576×
            head_seen: Default::default(),
404576×
            walked_dirs: Default::default(),
405576×
            listed_dirs: Default::default(),
406576×
            git_export_skipped: Default::default(),
407576×
            manifest_cache: Default::default(),
408576×
            listing_cache: Default::default(),
409576×
            untracked_nested: Default::default(),
410576×
            skipped_large: Default::default(),
411576×
            root,
412576×
            oxy,
413576×
            store,
414576×
            workspace,
415576×
            bare: false,
416576×
            keys_dir: default_keys_dir(),
417576×
            platform: crate::portable::Platform::current(),
418576×
            user_config: default_user_config(),
419576×
            config,
420576×
        };
421576×
        repo.register_workspace(&workspace, &repo.root)?;
422
423576×
        let wc = repo.new_working_copy(vec![], "");
424576×
        let wc_hash = repo.store.put_change(&wc)?;
425576×
        let mut view = View::default();
426576×
        view.bookmarks.insert(
427576×
            repo.config.bookmark.clone(),
428576×
            repo.store.put_state(&StateObject::new(vec![]))?,
429
        );
430576×
        view.workspaces.insert(workspace, wc_hash);
431576×
        repo.record_op(&[], "oxy init", view)?;
432574×
        Ok(repo)
433578×
    }
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
44446×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
44546×
        Self::init_bare_on(root, id, None)
44646×
    }
447
448
    /// [`Repo::init_on`] for a bare repository.
44946×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
45046×
        fs::create_dir_all(root)?;
45146×
        let root = crate::portable::canonical(root).unwrap_or_else(|_| root.to_path_buf());
45246×
        let oxy = root.join(OXY_DIR);
45346×
        if oxy.exists() {
4540×
            return fail(format!("{} is already an oxy repository", root.display()));
45546×
        }
45646×
        fs::create_dir_all(oxy.join("ops"))?;
45746×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
45846×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
45946×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
46046×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
46146×
        if let Some(url) = storage {
4620×
            config.set("storage.url", url)?;
46346×
        }
46446×
        config.save(&oxy.join("config"))?;
46546×
        let store = open_objects(&oxy, &config)?;
46646×
        let repo = Repo {
46746×
            acceptor: None,
46846×
            keyless_key: Default::default(),
46946×
            last_change: Default::default(),
47046×
            at_op: None,
47146×
            head_seen: Default::default(),
47246×
            walked_dirs: Default::default(),
47346×
            listed_dirs: Default::default(),
47446×
            git_export_skipped: Default::default(),
47546×
            manifest_cache: Default::default(),
47646×
            listing_cache: Default::default(),
47746×
            untracked_nested: Default::default(),
47846×
            skipped_large: Default::default(),
47946×
            root,
48046×
            oxy,
48146×
            store,
48246×
            workspace: WorkspaceId::ZERO,
48346×
            bare: true,
48446×
            keys_dir: default_keys_dir(),
48546×
            platform: crate::portable::Platform::current(),
48646×
            user_config: default_user_config(),
48746×
            config,
48846×
        };
48946×
        let mut view = View::default();
49046×
        view.bookmarks.insert(
49146×
            repo.config.bookmark.clone(),
49246×
            repo.store.put_state(&StateObject::new(vec![]))?,
493
        );
49446×
        repo.record_op(&[], "oxy init --bare", view)?;
49546×
        Ok(repo)
49646×
    }
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.
50120×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
50220×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
50320×
        fs::remove_file(repo.oxy.join("id"))?;
50420×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
50520×
        Ok(repo)
50620×
    }
507
5084281×
    pub fn is_unbound(&self) -> bool {
5094281×
        self.oxy.join(UNBOUND_MARKER).is_file()
5104281×
    }
511
512
    /// Give an unbound repository its id.
51319×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
51419×
        if !self.is_unbound() {
5150×
            return fail("this repository already has an id");
51619×
        }
51719×
        if id == [0; 16] {
5180×
            return fail("a repository id cannot be all zero");
51919×
        }
52019×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
52119×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
52219×
        Ok(())
52319×
    }
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).
5312247×
    pub fn open(start: &Path) -> Result<Repo> {
5322247×
        let start = crate::portable::canonical(start)?;
5332247×
        let mut dir: Option<&Path> = Some(&start);
5342255×
        while let Some(d) = dir {
5352253×
            let oxy = d.join(OXY_DIR);
5362253×
            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);
5732244×
            }
5742244×
            if oxy.is_dir() {
5752236×
                let format = fs::read_to_string(oxy.join("format"))?;
5762236×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5772236×
                let bare = oxy.join(BARE_MARKER).is_file();
5782236×
                let workspace = if bare {
579195×
                    WorkspaceId::ZERO
580
                } else {
5812041×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5822041×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
583
                };
5842236×
                let store = open_objects(&oxy, &config)?;
5852236×
                let mut repo = Repo {
5862236×
                    acceptor: None,
5872236×
                    keyless_key: Default::default(),
5882236×
                    last_change: Default::default(),
5892236×
                    at_op: None,
5902236×
                    head_seen: Default::default(),
5912236×
                    walked_dirs: Default::default(),
5922236×
                    listed_dirs: Default::default(),
5932236×
                    git_export_skipped: Default::default(),
5942236×
                    manifest_cache: Default::default(),
5952236×
                    listing_cache: Default::default(),
5962236×
                    untracked_nested: Default::default(),
5972236×
                    skipped_large: Default::default(),
5982236×
                    root: d.to_path_buf(),
5992236×
                    oxy,
6002236×
                    store,
6012236×
                    workspace,
6022236×
                    bare,
6032236×
                    keys_dir: default_keys_dir(),
6042236×
                    platform: crate::portable::Platform::current(),
6052236×
                    user_config: default_user_config(),
6062236×
                    config,
6072236×
                };
6082236×
                if !bare {
6092041×
                    repo.apply_workspace_bookmark();
6102041×
                }
6112236×
                if format == FORMAT1_LINE {
6121×
                    repo.migrate_format1()?;
6132235×
                } else if format != FORMAT_LINE {
6140×
                    return fail(format!("unsupported repository format: {}", format.trim()));
6152235×
                }
6162236×
                return Ok(repo);
6178×
            }
6188×
            dir = d.parent();
619
        }
6202×
        fail(format!(
621
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
6222×
            start.display()
623
        ))
6242247×
    }
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).
669776×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
670776×
        self.store
671776×
            .expire_retired(crate::store::RETIRED_FOR, &mut |_| {})?;
672776×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6730×
            self.store.pack_loose()?;
6740×
            self.store.merge_packs()?;
675776×
        }
676776×
        Ok(())
677776×
    }
678
679
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6803939×
    pub fn id(&self) -> Result<[u8; 16]> {
6813939×
        if self.is_unbound() {
68229×
            return Ok([0; 16]);
6833910×
        }
6843910×
        let path = self.oxy.join("id");
6853910×
        match fs::read_to_string(&path) {
6863910×
            Ok(h) => hex::decode(h.trim())
6873910×
                .ok()
6883910×
                .and_then(|v| v.try_into().ok())
6893910×
                .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
        }
6983939×
    }
699
70076×
    pub fn root(&self) -> &Path {
70176×
        &self.root
70276×
    }
703580×
    pub fn store(&self) -> &Store {
704580×
        &self.store
705580×
    }
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
730210×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
731210×
        let dir = dir.into();
732210×
        self.keys_dir = dir.join("keys");
733210×
        self.user_config = dir.join("config.toml");
734210×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
735210×
            self.config = c;
736210×
        }
737210×
        self.apply_workspace_bookmark();
738210×
        self
739210×
    }
740
741
    /// The workspace's current bookmark (spec §10.1) overrides the
742
    /// configured default when `oxy bookmark switch` has recorded one.
7432260×
    fn apply_workspace_bookmark(&mut self) {
7442260×
        if let Ok(b) = fs::read_to_string(
7452260×
            self.oxy
7462260×
                .join("workspaces")
7472260×
                .join(self.workspace.to_hex())
7482260×
                .join("bookmark"),
7492260×
        ) {
75041×
            let b = b.trim();
75141×
            if !b.is_empty() {
75241×
                self.config.bookmark = b.to_string();
75341×
            }
7542219×
        }
7552260×
    }
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
768422×
    pub fn save_config(&self) -> Result<()> {
769422×
        self.config.save(&self.oxy.join("config"))
770422×
    }
771
7725166×
    fn author(&self) -> KeyId {
7735166×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7745166×
    }
775
}
776
777
impl Repo {
7781957×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7791957×
        let mut c = Change {
7801957×
            version: crate::objects::CHANGE_VERSION,
7811957×
            change_id: ChangeId::random(),
7821957×
            deps,
7831957×
            author: self.author(),
7841957×
            hlc: Hlc::now(),
7851957×
            message: message.into(),
7861957×
            tree_ops: vec![],
7871957×
            edits: vec![],
7881957×
            kind: ChangeKind::WorkingCopy,
7891957×
        };
7901957×
        c.normalize();
7911957×
        c
7921957×
    }
793
794
    // ------------------------------------------------------------ operation log
795
79617128×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
79717128×
        if let Some(r) = self.at_op {
7985×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
79917123×
        }
80017123×
        let r = self.head_ref()?;
80117121×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
80217121×
        Ok((r, op))
80317128×
    }
804
80511536×
    pub fn view(&self) -> Result<View> {
80611536×
        Ok(self.head_op()?.1.view)
80711536×
    }
808
8094005×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
8104005×
        self.record_op_undoing(parents, command, view, None)
8114005×
    }
812
813
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
8144008×
    fn record_op_undoing(
8154008×
        &self,
8164008×
        parents: &[ObjectRef],
8174008×
        command: &str,
8184008×
        view: View,
8194008×
        undoes: Option<ObjectRef>,
8204008×
    ) -> Result<ObjectRef> {
8214008×
        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
            );
8254007×
        }
8264007×
        let op = Op {
8274007×
            parents: parents.to_vec(),
8284007×
            hlc: Hlc::now(),
8294007×
            command: command.into(),
8304007×
            view,
8314007×
            workspace: Some(self.workspace),
8324007×
            undoes,
8334007×
        };
8344007×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
835
        // The head is the commit point: everything it names must be on disk first.
8364005×
        let flushing = crate::timing::phase("op: flush the store");
8374005×
        self.store.flush()?;
8384003×
        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.
8444003×
        let _lock = if self.store.is_local() {
8453991×
            Some(self.lock_ops()?)
846
        } else {
84712×
            None
848
        };
8494003×
        let Some(parent) = parents.first() else {
850
            // The first operation (init): there is no head yet.
851622×
            if !self.swap_head(&r, None)? {
8522×
                return fail(format!(
853
                    "{} already holds a repository's operation log",
8542×
                    self.store.backend().describe()
855
                ));
856620×
            }
857620×
            return Ok(r);
858
        };
8593381×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8603381×
        for _ in 0..HEAD_TRIES {
8613381×
            let (current, version) = self.read_head()?;
8623381×
            let to = if current == *parent {
8633357×
                r
864
            } else {
86524×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
86623×
                let merged = Op {
86724×
                    parents: vec![current, r],
86824×
                    hlc: Hlc::now(),
86924×
                    command: format!("{command} (merged with a concurrent operation)"),
87024×
                    view: self.merge_views(&base, &op.view, &theirs)?,
87123×
                    workspace: Some(self.workspace),
87223×
                    undoes: None,
873
                };
87423×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
87523×
                self.store.flush()?;
87623×
                m
877
            };
8783380×
            if self.swap_head(&to, version.as_ref())? {
8793374×
                return Ok(to);
8800×
            }
881
        }
8820×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8834008×
    }
884
885
    /// The operation head's lock, held only while the head pointer moves.
8864001×
    fn lock_ops(&self) -> Result<FileLock> {
8874001×
        fs::create_dir_all(self.oxy.join("ops"))?;
8884001×
        FileLock::acquire(
8894001×
            self.oxy.join("ops").join("lock"),
8904001×
            "another oxy process holds the operation log",
891
        )
8924001×
    }
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`]).
89617125×
    fn head_ref(&self) -> Result<ObjectRef> {
89717125×
        if let Some(r) = self.head_seen.get() {
89813368×
            return Ok(r);
8993757×
        }
9003757×
        let r = self.read_head()?.0;
9013755×
        self.head_seen.set(Some(r));
9023755×
        Ok(r)
90317125×
    }
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.
912503×
    pub fn refresh(&self) -> Result<()> {
913503×
        self.forget_head();
914503×
        self.store.refresh()?;
915503×
        Ok(())
916503×
    }
917
918
    /// Read the operation head again on next use, as [`Repo::refresh`]
919
    /// does, leaving the packs as they are.
9202436×
    pub(crate) fn forget_head(&self) {
9212436×
        self.head_seen.set(None);
9222436×
    }
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).
9287229×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
9297229×
        if self.store.is_local() {
9307211×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
9317211×
            let r = ObjectRef::from_hex(hex.trim())
9327211×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
9337208×
            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
        }
9547229×
    }
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.
9614015×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
9624015×
        if self.store.is_local() {
9634001×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
9643995×
            self.head_seen.set(Some(*to));
9653995×
            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
        }
9794015×
    }
980
981
    /// Three-way merge of two views that both started from `base` (spec
982
    /// §12.1). A reference only one side changed takes that side's value.
983
    /// When both changed it differently: a bookmark keeps both sides'
984
    /// heads (it may then have several), a change beats a deletion, a
985
    /// workspace changed by both is an error (only one of them matches the
986
    /// files on disk), and otherwise this process's value wins for remote
987
    /// references and the policy, the first value for a tag (tags never
988
    /// move).
98924×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
99085×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
99185×
            b: &BTreeMap<K, V>,
99285×
            o: &BTreeMap<K, V>,
99385×
            t: &BTreeMap<K, V>,
99485×
            mut both: impl FnMut(&V, &V) -> Result<V>,
99585×
        ) -> Result<BTreeMap<K, V>> {
99685×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
99785×
            let mut out = BTreeMap::new();
99888×
            for k in keys {
99988×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
100088×
                let v = if ov == tv || tv == bv {
100145×
                    ov.cloned()
100243×
                } else if ov == bv {
100326×
                    tv.cloned()
1004
                } else {
100517×
                    match (ov, tv) {
100617×
                        (Some(x), Some(y)) => Some(both(x, y)?),
10070×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
10080×
                        (None, None) => None,
1009
                    }
1010
                };
101187×
                if let Some(v) = v {
101287×
                    out.insert(k.clone(), v);
101387×
                }
1014
            }
101584×
            Ok(out)
101685×
        }
101724×
        let bookmarks = pick(
101824×
            &base.bookmarks,
101924×
            &ours.bookmarks,
102024×
            &theirs.bookmarks,
102116×
            |x, y| {
102216×
                let mut heads = self.store.get_state(x)?.heads;
102316×
                heads.extend(self.store.get_state(y)?.heads);
102416×
                let heads = self.load_state(&heads)?.maximal(&heads);
102516×
                Ok(self.store.put_state(&StateObject::new(heads))?)
102616×
            },
10270×
        )?;
1028
        // Two operations that both replaced one workspace's working copy
1029
        // cannot both be right: the files on disk match only one of them.
1030
        // The working-copy lock keeps this from happening; should it happen
1031
        // anyway, this operation is not recorded.
103224×
        let workspaces = pick(
103324×
            &base.workspaces,
103424×
            &ours.workspaces,
103524×
            &theirs.workspaces,
10361×
            |_, _| {
10371×
                fail(
1038
                    "another oxy process changed this working copy at the same time; \
1039
                     this command was not recorded: check `oxy status` and run it again",
1040
                )
10411×
            },
10421×
        )?;
104323×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
104423×
        let empty = BTreeMap::new();
104523×
        let names: BTreeSet<&String> = base
104623×
            .remotes
104723×
            .keys()
104823×
            .chain(ours.remotes.keys())
104923×
            .chain(theirs.remotes.keys())
105023×
            .collect();
105123×
        let mut remotes = BTreeMap::new();
105223×
        for n in names {
105314×
            let m = pick(
105414×
                base.remotes.get(n).unwrap_or(&empty),
105514×
                ours.remotes.get(n).unwrap_or(&empty),
105614×
                theirs.remotes.get(n).unwrap_or(&empty),
10570×
                |x, _| Ok(*x),
10580×
            )?;
105914×
            if !m.is_empty() {
106014×
                remotes.insert(n.clone(), m);
106114×
            }
1062
        }
106323×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
106423×
            ours.policy
10650×
        } else if ours.policy == base.policy {
10660×
            theirs.policy
1067
        } else {
10680×
            ours.policy.or(theirs.policy)
1069
        };
107023×
        self.store.flush()?;
107123×
        Ok(View {
107223×
            bookmarks,
107323×
            workspaces,
107423×
            remotes,
107523×
            policy,
107623×
            tags,
107723×
        })
107824×
    }
1079
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.
1445224×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1446224×
        if let Some(st) = self.load_state_checkpointed(heads)? {
14474×
            return Ok(st);
1448219×
        }
1449219×
        self.load_state_full(heads)
1450224×
    }
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`].
14562144×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
14572144×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
145844×
            return Ok(st);
14592100×
        }
14602100×
        self.load_state_replayed(heads, State::new_history_only())
14612144×
    }
1462
1463
    /// Build these file graphs in a history-only state.
14642237×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
14652237×
        state
14662237×
            .load_graphs(
14672237×
                nodes,
146854×
                |refs| {
146954×
                    self.read_blobs(refs).map_err(|e| {
14703×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14713×
                    })
147254×
                },
14732436×
                |h| self.change_bytes(h),
1474
            )
14752237×
            .map_err(|e| self.index_damage(e))
14762237×
    }
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.
14812511×
    pub fn tree_view(&self, state: &mut State) -> Result<crate::tree::TreeView> {
14822511×
        let need = state.unify_candidates();
14832511×
        if !need.is_empty() {
1484105×
            self.load_graphs_of(state, &need)?;
14852406×
        }
14862511×
        Ok(state.view())
14872511×
    }
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.
1529433×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1530
        use crate::objects::TextRef;
1531433×
        let refs: Vec<ObjectRef> = texts
1532433×
            .iter()
15335569×
            .filter_map(|t| match t {
15341×
                TextRef::Blob(r, _, _) => Some(*r),
15355568×
                TextRef::Inline { .. } => None,
15365569×
            })
1537433×
            .collect();
1538433×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1539433×
        let mut out = Vec::with_capacity(texts.len());
15405569×
        for t in texts {
15415569×
            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
                }
15485568×
                TextRef::Inline { change, start, end } => {
15495568×
                    let bytes = self.change_bytes(change)?;
15505568×
                    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×
                    })?;
15535568×
                    crate::objects::inline_lines(range)?
1554
                }
1555
            };
15565569×
            out.push(lines.bytes().to_vec());
1557
        }
1558433×
        Ok(out)
1559433×
    }
1560
1561
    /// Build every graph a history-only state still lacks, making it full.
15622528×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
15632528×
        state
15642528×
            .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×
                },
15705352×
                |h| self.change_bytes(h),
1571
            )
15722528×
            .map_err(|e| self.index_damage(e))
15732528×
    }
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.
157813439×
    fn change_bytes(
157913439×
        &self,
158013439×
        h: &ChangeHash,
158113439×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
158213439×
        let mut cache = self.last_change.borrow_mut();
158322827×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
158410516×
            let hit = cache.remove(i);
158510516×
            let b = hit.1.clone();
158610516×
            cache.push(hit);
158710516×
            return Ok(b);
15882923×
        }
15892923×
        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×
        })?);
15922923×
        cache.push((*h, b.clone()));
1593
        // The last few, within a memory budget; the newest always stays.
15944722×
        while cache.len() > CHANGE_CACHE_COUNT
15952923×
            || (cache.len() > 1
15968812×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15971799×
        {
15981799×
            cache.remove(0);
15991799×
        }
16002923×
        Ok(b)
160113439×
    }
1602
1603
    /// Load the dependency closure of `heads` change by change.
1604273×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1605273×
        self.load_state_replayed(heads, State::new())
1606273×
    }
1607
16084098×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
16094098×
        let history = state.is_history_only();
16104098×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
16114098×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1612
        {
16134098×
            let _t = crate::timing::phase("load: read and add changes");
16144098×
            let (mut read, mut add, mut fetch) = (
16154098×
                std::time::Duration::ZERO,
16164098×
                std::time::Duration::ZERO,
16174098×
                std::time::Duration::ZERO,
16184098×
            );
161916614×
            while let Some(h) = stack.pop() {
1620
                // A change the state holds brings its history with it.
162112521×
                if !seen.insert(h) || state.contains(&h) {
16222971×
                    continue;
16239550×
                }
16249550×
                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.
16279550×
                let (c, texts) = if history {
16288020×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
16298017×
                    fetch += t0.elapsed();
16308017×
                    Change::decode_skeleton(&bytes, h)
16318017×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1632
                } else {
16331530×
                    (self.store.get_change(&h)?, Vec::new())
1634
                };
16359545×
                read += t0.elapsed();
16369545×
                stack.extend(c.deps.iter().copied());
16379545×
                let t1 = std::time::Instant::now();
16389545×
                state.add_known(h, c, texts);
16399545×
                add += t1.elapsed();
1640
            }
16414093×
            crate::timing::record("load:   of which reading", read);
16424093×
            crate::timing::record("load:     of which fetching", fetch);
16434093×
            crate::timing::record("load:   of which applying", add);
1644
        }
16454093×
        let _t = crate::timing::phase("load: validate");
16464093×
        state.validate()?;
16474093×
        Ok(state)
16484098×
    }
1649
16502837×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
16512837×
        if self.bare {
16522×
            return fail("this is a bare repository: it has no working copy");
16532835×
        }
16542835×
        let view = self.view()?;
16552835×
        let h = *view
16562835×
            .workspaces
16572835×
            .get(&self.workspace)
16582835×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
16592834×
        Ok((h, self.store.get_change(&h)?))
16602837×
    }
1661
1662
    /// Heads of a bookmark's state (spec §10.1).
16632054×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
16642054×
        match view.bookmarks.get(bookmark) {
16652054×
            Some(st) => Ok(self.store.get_state(st)?.heads),
16660×
            None => Ok(vec![]),
1667
        }
16682054×
    }
1669
1670575×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1671575×
        self.heads_of(&self.view()?, &self.config.bookmark)
1672575×
    }
1673
1674
    // ------------------------------------------------------------ blobs
1675
1676472×
    fn blob_for(content: &[u8]) -> Blob {
1677472×
        Blob::of(content)
1678472×
    }
1679
1680267×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1681267×
        Self::blob_for(content).hash()
1682267×
    }
1683
1684203×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1685286×
        for c in crate::chunk::chunks(content) {
1686286×
            self.store.put_chunk(c)?;
1687
        }
1688203×
        Ok(self
1689203×
            .store
1690203×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1691203×
    }
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.
1696507×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1697507×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1698507×
        let t = crate::timing::phase("blobs: get_many blobs");
1699507×
        let got_all = self.store.get_many(refs);
1700507×
        drop(t);
1701507×
        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
        }
1709507×
        let chunk_refs: Vec<ObjectRef> = blobs
1710507×
            .iter()
1711507×
            .flatten()
1712507×
            .flat_map(|b| b.chunks.iter().copied())
1713507×
            .collect();
1714507×
        let t = crate::timing::phase("blobs: get_many chunks");
1715507×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1716507×
        drop(t);
1717507×
        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
            );
1724507×
        }
1725507×
        let mut out = Vec::with_capacity(refs.len());
1726507×
        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
        }
1743502×
        Ok(out)
1744507×
    }
1745
1746
    /// Read a blob's content, fetching it from the remote that withheld it
1747
    /// when it is lazily absent (spec §13.5).
1748188×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1749188×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
17505×
            self.fetch_lazy_blob(r)?;
1751183×
        }
1752188×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1753183×
        let mut out = Vec::with_capacity(blob.length as usize);
1754249×
        for c in &blob.chunks {
1755249×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1756
        }
1757183×
        Ok(out)
1758188×
    }
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).
177830×
    pub fn untracked_nested(&self) -> Vec<String> {
177930×
        self.untracked_nested.borrow().clone()
178030×
    }
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).
178434×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
178534×
        self.skipped_large.borrow().clone()
178634×
    }
1787
1788
    /// Attributes from a materialized state's `.oxyattributes` files.
17896×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
179013×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
179113×
            match &f.content {
179213×
                FileContent::Text { bytes, .. }
179313×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1794
                {
17952×
                    Some((p.as_str(), bytes.as_slice()))
1796
                }
179711×
                _ => None,
1798
            }
179913×
        }))
18006×
    }
1801
1802
    /// Store a blob, raw when the path is `nocompress`.
1803183×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1804183×
        if !nocompress {
1805181×
            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())?)
1813183×
    }
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.
18202969×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
18212969×
        let mut heads = heads.to_vec();
18222969×
        heads.sort();
18232969×
        let mut h = blake3::Hasher::new();
18243101×
        for c in &heads {
18253101×
            h.update(&c.0);
18263101×
        }
18272969×
        self.oxy.join("index").join(format!(
18282969×
            "{}{}",
18292969×
            self.state_index_prefix(),
18302969×
            &h.finalize().to_hex()[..16]
18312969×
        ))
18322969×
    }
1833
18345833×
    fn state_index_prefix(&self) -> String {
18355833×
        format!("state-{}-", self.workspace.to_hex())
18365833×
    }
1837
1838
    /// This workspace's state indexes, newest first.
18392864×
    fn state_indexes(&self) -> Vec<PathBuf> {
18402864×
        let prefix = self.state_index_prefix();
18412864×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
18422864×
            .into_iter()
18432864×
            .flatten()
18442864×
            .flatten()
18452864×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
18462864×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
18472864×
            .collect();
18482864×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
18492864×
        found.into_iter().map(|(_, p)| p).collect()
18502864×
    }
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.
18562488×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
18572488×
        if let Some((st, heads)) = self.read_state_index(deps) {
18582017×
            let mut have = st.maximal(deps);
18592017×
            have.sort();
18602017×
            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)]
1864170×
                if let Some(mine) = st.write_index() {
1865164×
                    assert_eq!(
1866164×
                        Some(mine),
1867164×
                        self.load_state_history(deps)?.write_index(),
1868
                        "a state index holds the state history gives"
1869
                    );
18706×
                }
1871292×
                return Ok(st);
18721725×
            }
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.
18771725×
            let (indexed, started) = (st.len(), std::time::Instant::now());
18781725×
            if let Ok(st) = self.load_state_replayed(deps, st) {
18791722×
                let mut all = deps.to_vec();
18801722×
                all.extend(heads.iter().copied());
18811722×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
18821722×
                within.sort();
18831722×
                want.sort();
18841722×
                if within == want {
1885
                    #[cfg(test)]
1886978×
                    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).
18901721×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
18911721×
                        || started.elapsed() > INDEX_REPLAY_TIME
18925×
                    {
18935×
                        self.write_state_index(deps, &st);
18941716×
                    }
18951721×
                    return Ok(st);
18961×
                }
18973×
            }
1898471×
        }
1899475×
        let st = self.load_state_history(deps)?;
1900475×
        self.write_state_index(deps, &st);
1901475×
        Ok(st)
19022488×
    }
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)]
1908978×
    fn assert_same_state(&self, a: &State, b: &State) {
19091956×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1910978×
        assert_eq!(ids(a), ids(b), "the same changes");
19111956×
        let files = |s: &State| {
19121956×
            let mut s = s.clone();
19131956×
            self.load_all_graphs(&mut s).unwrap();
19141956×
            s.materialize().files
19151956×
        };
1916978×
        assert_eq!(files(a), files(b), "the same files");
1917978×
    }
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.
19252488×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1926
        use std::io::Read;
19272488×
        let _t = crate::timing::phase("load: state index");
19282488×
        let exact = self.state_index_path(deps);
19292488×
        let reading = crate::timing::phase("load:   of which reading the file");
19302488×
        let mut f = match fs::File::open(&exact) {
1931292×
            Ok(f) => {
1932
                // Used now: the newest, so the last to be dropped.
1933292×
                let _ = fs::File::options()
1934292×
                    .write(true)
1935292×
                    .open(&exact)
1936292×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1937292×
                f
1938
            }
19392196×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1940
        };
19412017×
        let total = f.metadata().ok()?.len();
19422017×
        let mut word = [0u8; 4];
19432017×
        f.read_exact(&mut word).ok()?;
19442017×
        let n = u32::from_le_bytes(word) as usize;
19452017×
        let mut head = vec![0u8; 32 * n + 64 + 8];
19462017×
        f.read_exact(&mut head).ok()?;
19472017×
        let heads: Vec<ChangeHash> = head[..32 * n]
19482017×
            .chunks_exact(32)
19492017×
            .map(|c| ObjectRef(c.try_into().unwrap()))
19502017×
            .collect();
19512017×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
19522017×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
19532017×
        let at = (4 + head.len()) as u64;
19542017×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
19550×
            return None;
19562017×
        }
1957
        // The front only: the files' histories after it are read, each
1958
        // checked by its own hash, when a command builds that file.
19592017×
        let mut front = vec![0u8; front_len as usize];
19602017×
        f.read_exact(&mut front).ok()?;
19612017×
        drop(reading);
19622017×
        let checking = crate::timing::phase("load:   of which checking the file");
19632017×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
19642017×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
19654034×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
19662017×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
19670×
            return None;
19682017×
        }
19692017×
        drop(checking);
19702017×
        let histories = crate::state::Histories::File(
19712017×
            std::sync::Arc::new(f),
19722017×
            at + front_len,
19732017×
            total - at - front_len,
19742017×
        );
19752017×
        Some((State::read_index_front(&front, histories).ok()?, heads))
19762488×
    }
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)]
1981185×
    pub(crate) fn read_state_index_changes(
1982185×
        &self,
1983185×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1984
        use std::io::Read;
1985185×
        let _t = crate::timing::phase("load: state index changes");
1986185×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1987168×
        let mut word = [0u8; 4];
1988168×
        f.read_exact(&mut word).ok()?;
1989168×
        let n = u32::from_le_bytes(word) as usize;
1990
        // Heads, the two sums, the front's length, then the changes block.
1991168×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1992168×
        f.read_exact(&mut head).ok()?;
1993168×
        let heads: Vec<ChangeHash> = head[..32 * n]
1994168×
            .chunks_exact(32)
1995168×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1996168×
            .collect();
1997168×
        let sum = &head[32 * n..32 * n + 32];
1998168×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1999168×
        let mut changes = vec![0u8; 4 + len];
2000168×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
2001168×
        f.read_exact(&mut changes[4..]).ok()?;
2002168×
        let checking = crate::timing::phase("load:   of which checking");
2003168×
        let mut h = blake3::Hasher::new();
2004168×
        h.update_rayon(&changes);
2005168×
        if h.finalize().as_bytes() != sum {
20060×
            return None;
2007168×
        }
2008168×
        drop(checking);
2009168×
        let _decoding = crate::timing::phase("load:   of which decoding");
2010168×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
2011185×
    }
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).
2015481×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
2016481×
        let _t = crate::timing::phase("write: state index");
2017481×
        let encoding = crate::timing::phase("write:   of which encoding");
2018481×
        let Some(body) = st.write_index() else {
20190×
            return;
2020
        };
2021481×
        drop(encoding);
2022
        #[cfg(test)]
2023283×
        assert_eq!(
2024283×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
2025283×
            Some(body.clone()),
2026
            "a state index reads back as written"
2027
        );
2028481×
        let mut heads = st.maximal(deps);
2029481×
        heads.sort();
2030481×
        let mut w = crate::flat::Writer::default();
2031481×
        w.count(heads.len());
2032481×
        for h in &heads {
203312×
            w.object(h);
203412×
        }
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.
2038481×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
2039481×
        let front = &body[8..8 + front_len];
2040481×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
2041962×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
2042481×
        w.fixed(&sum(&front[..split]));
2043481×
        w.fixed(&sum(&front[split..]));
2044481×
        w.fixed(&body);
2045481×
        let path = self.state_index_path(&heads);
2046481×
        let _ = fs::create_dir_all(self.oxy.join("index"));
2047481×
        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.
2050481×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
20511×
            let _ = fs::remove_file(old);
20521×
        }
2053481×
        let _ = fs::remove_file(
2054481×
            self.oxy
2055481×
                .join("index")
2056481×
                .join(format!("state-{}", self.workspace.to_hex())),
2057481×
        );
2058481×
    }
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).
209425350×
    pub fn in_scope(&self, path: &str) -> bool {
209525350×
        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}/")))
210125350×
    }
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.
21221609×
    fn walk_working_copy_with(
21231609×
        &self,
21241609×
        cache: Option<&prompt::Manifest>,
21251609×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
21261609×
        keys: Option<&KeyOf>,
21271609×
    ) -> Result<BTreeMap<String, FsEntry>> {
2128
        let mut out: BTreeMap<String, FsEntry>;
21291609×
        let sparse = &self.config.sparse_paths;
21309698×
        let in_scope = |p: &str| {
21319698×
            sparse.is_empty()
21327×
                || sparse
21337×
                    .iter()
21347×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
21359698×
        };
21361609×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2137
        let walk::Listing {
21381609×
            files,
21391609×
            symlinks,
21401609×
            nested,
21411609×
            dirs,
21421609×
        } = match self.listing_cache.take() {
2143207×
            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).
21479710×
            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.
21531609×
        let limit = self.config.max_new_file;
21541609×
        let mut skipped = Vec::new();
21551609×
        let files: Vec<_> = files
21561609×
            .into_iter()
215712740×
            .filter(|(rel, _, meta)| {
215812740×
                let new = !tracked.contains_key(rel)
21593225×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
216012740×
                if limit > 0 && new && meta.size > limit {
21613×
                    skipped.push((rel.clone(), meta.size));
21623×
                    return false;
216312737×
                }
216412737×
                true
216512740×
            })
21661609×
            .collect();
21671609×
        *self.skipped_large.borrow_mut() = skipped;
21681609×
        let keys = keys.filter(|k| {
216912724×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
21701605×
            let attrs_unchanged =
21711605×
                files
21721605×
                    .iter()
217312687×
                    .filter(|(r, _, _)| is_attributes(r))
21741605×
                    .all(|(rel, _, meta)| {
217518×
                        stat_cached(rel, meta, cache)
217618×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
217718×
                    });
21781605×
            let none_removed = tracked
21791605×
                .keys()
21809618×
                .filter(|r| is_attributes(r))
21811605×
                .all(|r| on_disk.contains(r.as_str()));
21821605×
            attrs_unchanged && none_removed
21831605×
        });
21841609×
        *self.walked_dirs.borrow_mut() =
21851609×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
21861609×
        drop(walk_phase);
21871609×
        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::*;
21911609×
            let mut read: Vec<(String, FsEntry)> = files
21921609×
                .par_iter()
219312737×
                .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.
219612737×
                    let key = keys
219712737×
                        .filter(|_| !is_attributes(rel))
219812737×
                        .filter(|_| {
219912669×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
220012669×
                        })
220112737×
                        .and_then(|k| k(rel));
220212737×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
220312737×
                })
22041609×
                .collect::<Result<Vec<_>>>()?;
220512735×
            for (rel, e) in read.iter_mut() {
2206
                // A cached blob the store lost (gc, a partial clone): read the file after all.
220712735×
                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;
221012735×
                }
2211
            }
2212
            // The listing is in path order, so the map is built without
2213
            // searching.
22141608×
            out = read.into_iter().collect();
22151608×
            for (rel, target) in symlinks {
22162×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
22172×
            }
2218
        }
22191608×
        drop(_read_phase);
22201608×
        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.
22241608×
        let modules = self.modules_on_disk();
2225
        // A subrepo at the state its recorded pin names is unmodified,
2226
        // whatever bookmark it sits on (#147): the recorded pin stands.
22271608×
        let subrepo_entry = |rel: &str, pin: crate::subrepo::Pin| -> FsEntry {
222853×
            if let Some((NodeKind::Subrepo, Some(b))) = tracked.get(rel) {
222936×
                let recorded = self
223036×
                    .read_blob(b)
223136×
                    .ok()
223236×
                    .and_then(|x| crate::subrepo::Pin::decode(&x).ok());
223336×
                if recorded.is_some_and(|r| r.same_state(&pin)) {
223423×
                    return FsEntry {
223523×
                        blob: Some(*b),
223623×
                        ..FsEntry::new(NodeKind::Subrepo, false, vec![])
223723×
                    };
223813×
                }
223917×
            }
224030×
            FsEntry::new(NodeKind::Subrepo, false, pin.encode())
224153×
        };
2242
        // A removal's marker is spent once the removal is recorded (no
2243
        // subrepo node is tracked there) or the path is registered again:
2244
        // dropped before it is read, or the change registering it again
2245
        // would leave it out (oxygen#152).
22461608×
        let mut removed = self.removed_subrepos();
22471608×
        removed.retain(|rel| {
22485×
            let spent = tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
22493×
                || modules.entries.contains_key(rel);
22505×
            if spent {
22512×
                self.clear_removed_subrepo(rel);
22523×
            }
22535×
            !spent
22545×
        });
22551608×
        let mut untracked_nested = Vec::new();
22561608×
        for dir in nested {
225758×
            let rel = self.rel_path(&dir);
225858×
            if !self.in_scope(&rel) || removed.contains(&rel) {
22593×
                continue;
226055×
            }
226155×
            let registered = modules.entries.get(&rel);
226255×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2263
            {
22642×
                untracked_nested.push(rel);
22652×
                continue;
226653×
            }
226753×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
226853×
            let entry = subrepo_entry(&rel, pin);
226953×
            out.insert(rel, entry);
2270
        }
22711608×
        untracked_nested.sort();
22721608×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2273
        // Tracked paths the ignore rules hid.
22741608×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
227575×
            if !self.in_scope(rel) {
227610×
                continue;
227765×
            }
227865×
            let path = self.root.join(rel);
227965×
            if *kind == NodeKind::Subrepo {
22804×
                if removed.contains(rel) {
22813×
                    continue;
22821×
                }
22831×
                let present =
22841×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
22851×
                if present {
22860×
                    let pin = subrepos::read_pin(
22870×
                        &path,
22880×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
22890×
                    )?;
22900×
                    out.insert(rel.clone(), subrepo_entry(rel, pin));
22911×
                } else if let Some(b) = blob {
22921×
                    // Not cloned (or emptied): the pin stays as recorded, as a
22931×
                    // Git gitlink does when its directory is absent.
22941×
                    out.insert(
22951×
                        rel.clone(),
22961×
                        FsEntry {
22971×
                            blob: Some(*b),
22981×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
22991×
                        },
23001×
                    );
23011×
                }
23021×
                continue;
230361×
            }
230461×
            let Ok(meta) = fs::symlink_metadata(&path) else {
230561×
                continue;
2306
            };
23070×
            let ft = meta.file_type();
23080×
            if ft.is_symlink() {
23090×
                let target = fs::read_link(&path)?;
23100×
                out.insert(
23110×
                    rel.clone(),
23120×
                    FsEntry::new(
23130×
                        NodeKind::Symlink,
2314
                        false,
23150×
                        target.to_string_lossy().as_bytes().to_vec(),
2316
                    ),
2317
                );
23180×
            } else if ft.is_file() {
23190×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
23200×
                out.insert(rel.clone(), e);
23210×
            }
2322
        }
23231608×
        Ok(out)
23241609×
    }
2325
2326
    /// The entry for one regular file, read or served from the stat cache.
23270×
    fn file_entry(
23280×
        &self,
23290×
        rel: &str,
23300×
        path: &Path,
23310×
        meta: &walk::Stat,
23320×
        cache: Option<&prompt::Manifest>,
23330×
    ) -> Result<FsEntry> {
23340×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
23350×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
23360×
            e.content = std::sync::Arc::new(fs::read(path)?);
23370×
            e.blob = None;
23380×
        }
23390×
        Ok(e)
23400×
    }
2341
2342
    /// The non-directory paths of a snapshot with their kinds, for the
2343
    /// walker's `tracked` set.
23443×
    pub(crate) fn tracked_kinds(
23453×
        snapshot: &Snapshot,
23463×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
23473×
        snapshot
23483×
            .files
23493×
            .iter()
235012×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
23518×
            .map(|(p, f)| {
23528×
                let blob = match &f.content {
23534×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
23544×
                    _ => None,
2355
                };
23568×
                (p.clone(), (f.kind, blob))
23578×
            })
23583×
            .collect()
23593×
    }
2360
2361
    /// A path under the root as a `/`-separated relative string.
2362124×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
2363124×
        path.strip_prefix(&self.root)
2364124×
            .unwrap_or(path)
2365124×
            .components()
2366226×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
2367124×
            .collect::<Vec<_>>()
2368124×
            .join("/")
2369124×
    }
2370
}
2371
2372
impl Repo {
2373
    /// Changes reachable from the bookmark and the working copy, newest first.
2374104×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
2375104×
        let heads = self.bookmark_heads()?;
2376104×
        if self.bare {
23771×
            return self.log_state(&heads);
2378103×
        }
2379103×
        let (wc_hash, wc) = self.working_copy()?;
2380103×
        let mut all = heads.clone();
2381103×
        all.push(wc_hash);
2382103×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
2383103×
        let mut entries: Vec<LogEntry> = Vec::new();
2384
        // A shallow clone knows changes beyond its boundary from a
2385
        // checkpoint's metadata only: its log comes from the state.
2386103×
        let metas = if self.is_shallow() {
23872×
            self.load_state_history(&all)?
23882×
                .changes()
238912×
                .map(|(h, m)| (*h, m.clone()))
23902×
                .collect()
2391
        } else {
2392
            // The working copy's change is in hand, and is never in the
2393
            // state index: its metadata is not looked up again.
2394101×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
2395101×
            below.extend(wc.deps.iter().copied());
2396101×
            let _t = crate::timing::phase("log: metadata");
2397101×
            let mut metas = self.metas_of(&below)?;
2398350×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
2399101×
                // First, where the log puts it, so the order may hold.
2400101×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
2401101×
            }
2402101×
            metas
2403
        };
2404103×
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2405463×
            hash: h,
2406463×
            change: meta,
2407463×
            is_working_copy: h == wc_hash,
2408463×
            is_head: head_set.contains(&h),
2409463×
        }));
2410103×
        let _sorting = crate::timing::phase("log: sort");
2411
        // The hash makes the order total, so an unstable sort gives the same.
2412
        // From the state index the order already holds (oxygen#94).
2413849×
        let order = |a: &LogEntry, b: &LogEntry| {
2414849×
            b.is_working_copy
2415849×
                .cmp(&a.is_working_copy)
2416849×
                .then(crate::state::log_order(
2417849×
                    (&a.hash, &a.change.hlc),
2418849×
                    (&b.hash, &b.change.hlc),
2419
                ))
2420849×
        };
2421249×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
242257×
            entries.sort_unstable_by(order);
242357×
        }
2424103×
        Ok(entries)
2425104×
    }
2426
2427
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2428
    /// count, for paginated views.
24290×
    pub fn log_window(
24300×
        &self,
24310×
        heads: &[ChangeHash],
24320×
        offset: usize,
24330×
        limit: usize,
24340×
    ) -> Result<(Vec<LogEntry>, usize)> {
24350×
        let all = self.log_state(heads)?;
24360×
        let total = all.len();
24370×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
24380×
    }
2439
2440
    /// The log of the state with these heads, newest first, with no working
2441
    /// copy involved (for hosted repositories and any explicit state).
244210×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2443
        // The log needs change metadata only: neither graphs nor the tree.
244410×
        if self.is_shallow() {
24450×
            return Ok(self.log_of(&self.load_state_history(heads)?));
244610×
        }
244710×
        let metas = self.metas_of(heads)?;
244810×
        let depended: BTreeSet<ChangeHash> = metas
244910×
            .iter()
245030×
            .flat_map(|(_, m)| m.deps.iter().copied())
245110×
            .collect();
245210×
        let mut entries: Vec<LogEntry> = metas
245310×
            .into_iter()
245410×
            .map(|(h, meta)| LogEntry {
245530×
                hash: h,
245630×
                is_head: !depended.contains(&h),
245730×
                change: meta,
2458
                is_working_copy: false,
245930×
            })
246010×
            .collect();
246138×
        let order = |a: &LogEntry, b: &LogEntry| {
246238×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
246338×
        };
246411×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
24653×
            entries.sort_unstable_by(order);
24667×
        }
246710×
        Ok(entries)
246810×
    }
2469
2470
    /// Every change of the state with these heads and its metadata, read
2471
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2472
    /// a shallow clone's boundary is left out.
2473185×
    pub fn metas_of(
2474185×
        &self,
2475185×
        heads: &[ChangeHash],
2476185×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2477185×
        let boundary = self.boundary();
2478
        // The state index holds the metadata of its heads' closure: a
2479
        // change found there is not read from the store (a change object
2480
        // can be as large as the tree it adds).
2481185×
        let read = self.read_state_index_changes();
2482
        // Every one of `heads` in the index, and every head of the index
2483
        // among them: their closure is the index's changes, all of them
2484
        // (it is closed), and no walk is needed to find it.
2485185×
        if let Some((index_heads, all)) = &read {
2486168×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2487168×
            let in_index = || {
2488168×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2489168×
                    index_heads.iter().collect();
2490
                // Usually the heads asked are the index's: no set of all.
2491168×
                heads.iter().all(|h| index_heads.contains(h)) || {
2492168×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2493168×
                        all.iter().map(|(h, _)| h).collect();
2494168×
                    heads.iter().all(|h| all.contains(h))
2495
                }
2496168×
            };
2497168×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
24980×
                let (_, all) = read.expect("matched above");
2499
                #[cfg(test)]
2500
                {
2501
                    // The walk the shortcut saves finds the same changes.
25020×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
25030×
                    let mut stack = heads.to_vec();
25040×
                    while let Some(h) = stack.pop() {
25050×
                        if seen.insert(h) {
25060×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
25070×
                        }
2508
                    }
25090×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2510
                }
25110×
                return Ok(all);
2512168×
            }
251317×
        }
2514185×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2515185×
            read.map(|(_, all)| all.into_iter().collect());
2516185×
        let _walk = crate::timing::phase("metadata: walk");
2517185×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2518185×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2519185×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2520185×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
25211333×
        while let Some(h) = stack.pop() {
25221148×
            if !seen.insert(h) {
2523484×
                continue;
2524664×
            }
2525
            // Taken out of the index's map, each once: not copied.
2526664×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2527
                #[cfg(test)]
25280×
                assert_eq!(
2529
                    meta,
25300×
                    self.store.get_change_meta(&h)?,
2531
                    "the state index holds a change's metadata"
2532
                );
25330×
                stack.extend(meta.deps.iter().copied());
25340×
                out.push((h, meta));
25350×
                continue;
2536664×
            }
2537664×
            let started = std::time::Instant::now();
2538664×
            let meta = match self.store.get_change_meta(&h) {
2539664×
                Ok(m) => m,
25400×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
25410×
                Err(e) => return Err(e.into()),
2542
            };
2543664×
            stored += 1;
2544664×
            from_store += started.elapsed();
2545664×
            stack.extend(meta.deps.iter().copied());
2546664×
            out.push((h, meta));
2547
        }
2548185×
        if stored > 0 && crate::timing::enabled() {
25490×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2550185×
        }
2551185×
        Ok(out)
2552185×
    }
2553
2554
    /// The log of a state already loaded, newest first.
2555
    /// The history of lines `first..=last` (1-based) of `path` in the
2556
    /// state `heads` make (spec §27): every change that inserted or
2557
    /// deleted one of their atoms, or an atom deleted from between them,
2558
    /// newest first. Exact, as atoms keep their identity across edits.
25596×
    pub fn line_history(
25606×
        &self,
25616×
        heads: &[ChangeHash],
25626×
        path: &str,
25636×
        first: usize,
25646×
        last: usize,
25656×
    ) -> Result<Vec<LogEntry>> {
25666×
        if first == 0 || last < first {
25671×
            return fail(format!(
2568
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2569
            ));
25705×
        }
25715×
        let mut state = self.load_state_history(heads)?;
25725×
        let Some(node) = self
25735×
            .tree_view(&mut state)?
2574
            .entries
25755×
            .get(path)
25765×
            .map(|e| e.node)
2577
        else {
25781×
            return fail(format!("{path} is not in that state"));
2579
        };
25804×
        self.load_graphs_of(&mut state, &[node])?;
25814×
        let live = state.live_lines(&node);
25824×
        if last > live.len() {
25831×
            return fail(format!(
2584
                "{path} has {} lines; asked for {first},{last}",
25851×
                live.len()
2586
            ));
25873×
        }
25883×
        let Some(g) = state.file(&node) else {
25890×
            return fail(format!("{path} is not a text file"));
2590
        };
25913×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
25923×
        let touched = g.touching(&atoms);
25933×
        Ok(self
25943×
            .log_of(&state)
25953×
            .into_iter()
259613×
            .filter(|e| touched.contains(&e.hash))
25973×
            .collect())
25986×
    }
2599
26008×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
26018×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
26028×
        let mut entries: Vec<LogEntry> = state
26038×
            .changes()
26048×
            .map(|(h, meta)| LogEntry {
260531×
                hash: *h,
260631×
                change: meta.clone(),
2607
                is_working_copy: false,
260831×
                is_head: head_set.contains(h),
260931×
            })
26108×
            .collect();
261139×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
26128×
        entries
26138×
    }
2614
2615
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2616
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2617
    /// (`resolve_change`).
261867×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
261967×
        let view = self.view()?;
262067×
        if let Some(st) = view.bookmarks.get(spec) {
262139×
            return Ok(self.store.get_state(st)?.heads);
262228×
        }
262328×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
26242×
            return Ok(self.store.get_state(&st)?.heads);
262526×
        }
262626×
        if let Some(heads) = self.tag_heads(spec)? {
26272×
            return Ok(heads);
262824×
        }
262924×
        Ok(vec![self.resolve_change(spec)?])
263067×
    }
2631
2632
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2633
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
263437×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
263537×
        if spec == "@" {
26360×
            return Ok(self.working_copy()?.0);
263737×
        }
263837×
        let view = self.view()?;
263937×
        let named = match view.bookmarks.get(spec) {
26401×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
264136×
            None => match remote_bookmark(&view, spec) {
26421×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
264335×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2644
            },
2645
        };
264637×
        if let Some((kind, heads)) = named {
26473×
            return match heads.len() {
26483×
                1 => Ok(heads[0]),
26490×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2650
            };
265134×
        }
265234×
        if spec.is_empty() || spec == "#" {
26530×
            return fail("empty change specifier");
265434×
        }
265534×
        let entries = self.log()?;
2656
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2657
        // cannot be a ChangeId, which has 32 (oxygen#103).
265834×
        let full_hash =
2659128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
266034×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
266128×
            entries
266228×
                .iter()
2663112×
                .filter(|e| e.hash.starts_with_hex(hp))
266428×
                .collect()
2665
        } else {
26666×
            entries
26676×
                .iter()
266821×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
26696×
                .collect()
2670
        };
267134×
        match matches.len() {
267229×
            1 => Ok(matches[0].hash),
26735×
            0 => match self.resolve_in_remotes(spec)? {
26741×
                Some(h) => Ok(h),
26754×
                None => fail(format!("no change matches {spec:?}")),
2676
            },
2677
            _ => {
26780×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
26790×
                if ids.len() == 1 {
26800×
                    fail(format!(
2681
                        "change {spec} is divergent: {} variants",
26820×
                        matches.len()
2683
                    ))
2684
                } else {
26850×
                    fail(format!("{spec:?} is ambiguous"))
2686
                }
2687
            }
2688
        }
268937×
    }
2690
2691
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2692
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2693
    /// `None` when none matches, or more than one.
26945×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
26955×
        let view = self.view()?;
26965×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
26975×
        for bookmarks in view.remotes.values() {
26983×
            for st in bookmarks.values() {
26993×
                let heads = self.store.get_state(st)?.heads;
27007×
                for e in self.log_state(&heads)? {
27017×
                    let hit = match spec.strip_prefix('#') {
27022×
                        Some(hp) => e.hash.starts_with_hex(hp),
27035×
                        None => e.change.change_id.starts_with_hex(spec),
2704
                    };
27057×
                    if hit {
27061×
                        found.insert(e.hash);
27076×
                    }
2708
                }
2709
            }
2710
        }
27115×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
27125×
    }
2713
2714
    /// Where a change is when no local bookmark or the working copy holds
2715
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2716
    /// it is held locally, or nowhere.
27174×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
27188×
        if self.log()?.iter().any(|e| e.hash == *hash) {
27193×
            return Ok(None);
27201×
        }
27211×
        let view = self.view()?;
27221×
        for (remote, bookmarks) in &view.remotes {
27231×
            for (name, st) in bookmarks {
27241×
                let heads = self.store.get_state(st)?.heads;
27251×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
27261×
                    return Ok(Some(format!("{remote}/{name}")));
27270×
                }
2728
            }
2729
        }
27300×
        Ok(None)
27314×
    }
2732
2733
    /// Human-readable description of what a change does, with line content.
27344×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
27354×
        let change = self.store.get_change(hash)?;
27364×
        let (base, base_snapshot) = self.change_base(&change)?;
27374×
        Ok(render_change(&change, &base, &base_snapshot))
27384×
    }
2739
2740
    /// The base state of `change` (its dependencies) and its rendering, as
2741
    /// much as showing the change needs: the whole tree, and the graphs and
2742
    /// contents of the files the change edits. Other text files are left
2743
    /// unrendered ([`Snapshot::unrendered`]).
27448×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
27458×
        let base = self.load_state_history(&change.deps)?;
27468×
        self.render_base_for(change, base)
27478×
    }
2748
2749
    /// The base for showing `change` alone: the graphs of the files it
2750
    /// edits built, and the base's tree with no file rendered, which is
2751
    /// all [`render_change`](snapshot::render_change) and
2752
    /// [`diff_files_of`](snapshot::diff_files_of) read.
27533×
    pub(crate) fn tree_base_for(
27543×
        &self,
27553×
        change: &Change,
27563×
        mut base: State,
27573×
    ) -> Result<(State, Snapshot)> {
27583×
        let _t = crate::timing::phase("diff: the base's tree");
27593×
        let edited: std::collections::HashSet<NodeId> =
27608×
            change.edits.iter().map(|e| e.node()).collect();
27613×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
27623×
        self.load_graphs_of(&mut base, &nodes)?;
27633×
        let snapshot = Snapshot {
27643×
            tree: self.tree_view(&mut base)?,
27653×
            files: BTreeMap::new(),
27663×
            unrendered: BTreeSet::new(),
2767
        };
27683×
        Ok((base, snapshot))
27693×
    }
2770
2771
    /// [`Repo::change_base`] with the base already loaded (the working
2772
    /// copy's comes from the state index).
2773236×
    pub(crate) fn render_base_for(
2774236×
        &self,
2775236×
        change: &Change,
2776236×
        mut base: State,
2777236×
    ) -> Result<(State, Snapshot)> {
2778236×
        let _t = crate::timing::phase("diff: render the base");
2779236×
        let edited: std::collections::HashSet<NodeId> =
2780444×
            change.edits.iter().map(|e| e.node()).collect();
2781236×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2782236×
        self.load_graphs_of(&mut base, &nodes)?;
2783236×
        self.tree_view(&mut base)?;
2784236×
        let snapshot = {
2785236×
            let _t = crate::timing::phase("diff:   of which materialize");
2786236×
            base.materialize_nodes(&edited)
2787
        };
2788236×
        Ok((base, snapshot))
2789236×
    }
2790
}
2791
27920×
fn remove_any(path: &Path) -> std::io::Result<()> {
27930×
    let m = fs::symlink_metadata(path)?;
27940×
    if m.is_dir() {
27950×
        fs::remove_dir_all(path)
2796
    } else {
27970×
        fs::remove_file(path)
2798
    }
27990×
}
2800
28015×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
28025×
    let mut perms = fs::metadata(path)?.permissions();
28035×
    perms.set_readonly(readonly);
28045×
    fs::set_permissions(path, perms)
28055×
}
2806
2807
#[cfg(unix)]
28085956×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2809
    use std::os::unix::fs::PermissionsExt;
28105956×
    let mut perms = fs::metadata(path)?.permissions();
28115956×
    let mode = perms.mode();
28125956×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
28135956×
    if want != mode {
28146×
        perms.set_mode(want);
28156×
        fs::set_permissions(path, perms)?;
28165950×
    }
28175956×
    Ok(())
28185956×
}
2819
#[cfg(not(unix))]
2820
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2821
    Ok(())
2822
}
2823
2824
#[cfg(unix)]
282517170×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2826
    use std::os::unix::fs::PermissionsExt;
282717170×
    m.permissions().mode() & 0o111 != 0
282817170×
}
2829
#[cfg(not(unix))]
2830
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2831
    false
2832
}
2833
283413557×
fn op_ref(k: OpKey) -> OpRef {
283513557×
    OpRef {
283613557×
        change: k.0,
283713557×
        index: k.1,
283813557×
    }
283913557×
}
2840
28416250×
fn split_path(path: &str) -> (&str, &str) {
28426250×
    match path.rfind('/') {
28435066×
        Some(i) => (&path[..i], &path[i + 1..]),
28441184×
        None => ("", path),
2845
    }
28466250×
}
2847
2848
/// Whether `rel` is an attributes file (spec §7.6).
284970147×
fn is_attributes(rel: &str) -> bool {
285070147×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
285170147×
}
2852
2853
/// The manifest entry for `rel` when its size and mtime match it outside
2854
/// the racy window.
285525424×
fn stat_cached<'m>(
285625424×
    rel: &str,
285725424×
    meta: &walk::Stat,
285825424×
    cache: Option<&'m prompt::Manifest>,
285925424×
) -> Option<&'m prompt::ManifestEntry> {
286025424×
    let m = cache?;
286120383×
    let e = m.entries.get(rel)?;
286218940×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
286318940×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
286425424×
}
2865
2866
/// Read one working-copy file, or serve it from the stat cache (spec
2867
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2868
/// an opaque file is not read at all (its stored blob stands in), and a
2869
/// text file the manifest recorded equal to a base graph whose key is
2870
/// `key`, the key the base has now, is not read either: equal keys mean
2871
/// equal renderings, so it still equals the base. Touches no repository
2872
/// state, so the walk runs it in parallel; the caller checks that a cached
2873
/// blob is still in the store.
287412737×
fn read_file_entry(
287512737×
    rel: &str,
287612737×
    path: &Path,
287712737×
    meta: &walk::Stat,
287812737×
    cache: Option<&prompt::Manifest>,
287912737×
    key: Option<[u8; 32]>,
288012737×
) -> Result<FsEntry> {
288112737×
    let exec = meta.exec;
288212737×
    let stat = Some((meta.size, meta.mtime_ns));
288312737×
    let mut e = match stat_cached(rel, meta, cache) {
28844247×
        Some(e) if e.blob.is_some() => FsEntry {
28851×
            blob: e.blob,
28861×
            content_hash: Some(e.hash),
28871×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28881×
        },
28894246×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
28904241×
            content_hash: Some(e.hash),
28914241×
            unchanged: true,
28924241×
            graph_key: e.graph,
28934241×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28944241×
        },
28955×
        Some(e) => FsEntry {
28965×
            content_hash: Some(e.hash),
28975×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2898
        },
28998490×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2900
    };
2901
    // The stat the manifest records: taken before the read, so a file that
2902
    // changes meanwhile is read again next time.
290312736×
    e.stat = stat;
290412736×
    Ok(e)
290512737×
}
2906
2907
/// Two maps side by side in key order: each key of either, with its value
2908
/// in each. Linear, with no lookups, for maps of a whole tree.
29093093×
pub(crate) fn join<'a, A, B>(
29103093×
    a: &'a BTreeMap<String, A>,
29113093×
    b: &'a BTreeMap<String, B>,
29123093×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
29133093×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
291436876×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
29153093×
        (None, None) => None,
29163012×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
29175990×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
291824781×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2919356×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2920328×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2921
            std::cmp::Ordering::Equal => {
292224097×
                let (k, va) = a.next()?;
292324097×
                let (_, vb) = b.next()?;
292424097×
                Some((k, Some(va), Some(vb)))
2925
            }
2926
        },
292736876×
    })
29283093×
}
2929
2930
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2931
/// lookups.
29321609×
pub(crate) fn missing_from<'a, A, B>(
29331609×
    a: &'a BTreeMap<String, A>,
29341609×
    b: &BTreeMap<String, B>,
29351609×
) -> Vec<(&'a String, &'a A)> {
29361609×
    let mut keys = b.keys().peekable();
29371609×
    a.iter()
29389628×
        .filter(|(k, _)| {
293918370×
            while keys.next_if(|kb| *kb < *k).is_some() {}
29409628×
            keys.peek() != Some(k)
29419628×
        })
29421609×
        .collect()
29431609×
}