OXYGENHUB

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

1902 of 2135 lines run, 446 of 723 functions · run #406 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.
752876×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762876×
    let Some(url) = &config.storage_url else {
772871×
        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×
    )?)
1002876×
}
101
102180×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103180×
    Err(RepoError::Msg(s.into()))
104180×
}
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.
1685541×
pub(crate) fn name_file(name: &str) -> String {
1695541×
    name.replace('%', "%25").replace('/', "%2F")
1705541×
}
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
1778632×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1788632×
    Ok(crate::durable::write_atomic(path, data)?)
1798632×
}
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
1953369×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1963369×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1973369×
    fs::write(&tmp, data)?;
1983369×
    fs::rename(&tmp, path)?;
1993369×
    Ok(())
2003369×
}
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 {
24023416×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
24123416×
        FsEntry {
24223416×
            kind,
24323416×
            exec,
24423416×
            content: std::sync::Arc::new(content),
24523416×
            blob: None,
24623416×
            content_hash: None,
24723416×
            unchanged: false,
24823416×
            graph_key: None,
24923416×
            stat: None,
25023416×
        }
25123416×
    }
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/`.
3178913×
pub fn default_home() -> PathBuf {
3188913×
    if let Ok(h) = std::env::var("OXY_HOME") {
3198883×
        return PathBuf::from(h);
32030×
    }
32130×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3220×
        return PathBuf::from(x).join("oxy");
32330×
    }
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
    }
33030×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
33130×
    PathBuf::from(home).join(".config").join("oxy")
3328913×
}
333
3342879×
pub fn default_keys_dir() -> PathBuf {
3352879×
    default_home().join("keys")
3362879×
}
337
3385754×
pub fn default_user_config() -> PathBuf {
3395754×
    default_home().join("config.toml")
3405754×
}
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
354273×
    pub fn init(root: &Path) -> Result<Repo> {
355273×
        let mut id = [0u8; 16];
356273×
        rand::rngs::OsRng.fill_bytes(&mut id);
357273×
        Self::init_with_id(root, id)
358273×
    }
359
360
    /// Initialize a repository with a given repository ID (clones share the
361
    /// ID of their origin, spec §14.4).
362563×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
363563×
        Self::init_on(root, id, None)
364563×
    }
365
366
    /// A new repository with a fresh id, bare or not, on `storage` or in
367
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
36814×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
36914×
        let mut id = [0u8; 16];
37014×
        rand::rngs::OsRng.fill_bytes(&mut id);
37114×
        if bare {
3720×
            Self::init_bare_on(root, id, storage)
373
        } else {
37414×
            Self::init_on(root, id, storage)
375
        }
37614×
    }
377
378
    /// Initialize a repository whose objects and operation head are kept
379
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
380580×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
381580×
        fs::create_dir_all(root)?;
382580×
        let root = crate::portable::canonical(root).unwrap_or_else(|_| root.to_path_buf());
383580×
        let oxy = root.join(OXY_DIR);
384580×
        if oxy.exists() {
3851×
            return fail(format!("{} is already an oxy repository", root.display()));
386579×
        }
387579×
        fs::create_dir_all(oxy.join("ops"))?;
388579×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
389579×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
390579×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
391579×
        if let Some(url) = storage {
3923×
            config.set("storage.url", url)?;
393576×
        }
394579×
        config.save(&oxy.join("config"))?;
395579×
        let workspace = WorkspaceId::random();
396579×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
397579×
        let store = open_objects(&oxy, &config)?;
398578×
        let repo = Repo {
399578×
            acceptor: None,
400578×
            keyless_key: Default::default(),
401578×
            last_change: Default::default(),
402578×
            at_op: None,
403578×
            head_seen: Default::default(),
404578×
            walked_dirs: Default::default(),
405578×
            listed_dirs: Default::default(),
406578×
            git_export_skipped: Default::default(),
407578×
            manifest_cache: Default::default(),
408578×
            listing_cache: Default::default(),
409578×
            untracked_nested: Default::default(),
410578×
            skipped_large: Default::default(),
411578×
            root,
412578×
            oxy,
413578×
            store,
414578×
            workspace,
415578×
            bare: false,
416578×
            keys_dir: default_keys_dir(),
417578×
            platform: crate::portable::Platform::current(),
418578×
            user_config: default_user_config(),
419578×
            config,
420578×
        };
421578×
        repo.register_workspace(&workspace, &repo.root)?;
422
423578×
        let wc = repo.new_working_copy(vec![], "");
424578×
        let wc_hash = repo.store.put_change(&wc)?;
425578×
        let mut view = View::default();
426578×
        view.bookmarks.insert(
427578×
            repo.config.bookmark.clone(),
428578×
            repo.store.put_state(&StateObject::new(vec![]))?,
429
        );
430578×
        view.workspaces.insert(workspace, wc_hash);
431578×
        repo.record_op(&[], "oxy init", view)?;
432576×
        Ok(repo)
433580×
    }
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
5084276×
    pub fn is_unbound(&self) -> bool {
5094276×
        self.oxy.join(UNBOUND_MARKER).is_file()
5104276×
    }
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).
5312253×
    pub fn open(start: &Path) -> Result<Repo> {
5322253×
        let start = crate::portable::canonical(start)?;
5332253×
        let mut dir: Option<&Path> = Some(&start);
5342261×
        while let Some(d) = dir {
5352259×
            let oxy = d.join(OXY_DIR);
5362259×
            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);
5732250×
            }
5742250×
            if oxy.is_dir() {
5752242×
                let format = fs::read_to_string(oxy.join("format"))?;
5762242×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5772242×
                let bare = oxy.join(BARE_MARKER).is_file();
5782242×
                let workspace = if bare {
579195×
                    WorkspaceId::ZERO
580
                } else {
5812047×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5822047×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
583
                };
5842242×
                let store = open_objects(&oxy, &config)?;
5852242×
                let mut repo = Repo {
5862242×
                    acceptor: None,
5872242×
                    keyless_key: Default::default(),
5882242×
                    last_change: Default::default(),
5892242×
                    at_op: None,
5902242×
                    head_seen: Default::default(),
5912242×
                    walked_dirs: Default::default(),
5922242×
                    listed_dirs: Default::default(),
5932242×
                    git_export_skipped: Default::default(),
5942242×
                    manifest_cache: Default::default(),
5952242×
                    listing_cache: Default::default(),
5962242×
                    untracked_nested: Default::default(),
5972242×
                    skipped_large: Default::default(),
5982242×
                    root: d.to_path_buf(),
5992242×
                    oxy,
6002242×
                    store,
6012242×
                    workspace,
6022242×
                    bare,
6032242×
                    keys_dir: default_keys_dir(),
6042242×
                    platform: crate::portable::Platform::current(),
6052242×
                    user_config: default_user_config(),
6062242×
                    config,
6072242×
                };
6082242×
                if !bare {
6092047×
                    repo.apply_workspace_bookmark();
6102047×
                }
6112242×
                if format == FORMAT1_LINE {
6121×
                    repo.migrate_format1()?;
6132241×
                } else if format != FORMAT_LINE {
6140×
                    return fail(format!("unsupported repository format: {}", format.trim()));
6152241×
                }
6162242×
                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
        ))
6242253×
    }
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).
669775×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
670775×
        self.store
671775×
            .expire_retired(crate::store::RETIRED_FOR, &mut |_| {})?;
672775×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6730×
            self.store.pack_loose()?;
6740×
            self.store.merge_packs()?;
675775×
        }
676775×
        Ok(())
677775×
    }
678
679
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6803933×
    pub fn id(&self) -> Result<[u8; 16]> {
6813933×
        if self.is_unbound() {
68229×
            return Ok([0; 16]);
6833904×
        }
6843904×
        let path = self.oxy.join("id");
6853904×
        match fs::read_to_string(&path) {
6863904×
            Ok(h) => hex::decode(h.trim())
6873904×
                .ok()
6883904×
                .and_then(|v| v.try_into().ok())
6893904×
                .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
        }
6983933×
    }
699
70078×
    pub fn root(&self) -> &Path {
70178×
        &self.root
70278×
    }
703
    /// The repository's `.oxy` directory (shared by its workspaces), for
704
    /// what other crates keep beside the store (Cylinder's artifacts).
70524×
    pub fn oxy_dir(&self) -> &Path {
70624×
        &self.oxy
70724×
    }
708580×
    pub fn store(&self) -> &Store {
709580×
        &self.store
710580×
    }
71111×
    pub fn workspace(&self) -> WorkspaceId {
71211×
        self.workspace
71311×
    }
714
715
    /// Use a different user directory for keys and the user config file
716
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
717
    /// Act as if the working copy were on another platform's file system
718
    /// (tests of Windows and macOS behaviour on any host).
719
    /// Accept certified updates as `identity` (a host's key), recording when
720
    /// (spec §14.7).
72148×
    pub fn with_acceptor(mut self, identity: Identity, sk: crate::identity::SecretKey) -> Repo {
72248×
        self.acceptor = Some(std::sync::Arc::new((identity, sk)));
72348×
        self
72448×
    }
725
7262×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
7272×
        self.platform = platform;
7282×
        self
7292×
    }
730
7310×
    pub fn platform(&self) -> crate::portable::Platform {
7320×
        self.platform
7330×
    }
734
735210×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
736210×
        let dir = dir.into();
737210×
        self.keys_dir = dir.join("keys");
738210×
        self.user_config = dir.join("config.toml");
739210×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
740210×
            self.config = c;
741210×
        }
742210×
        self.apply_workspace_bookmark();
743210×
        self
744210×
    }
745
746
    /// The workspace's current bookmark (spec §10.1) overrides the
747
    /// configured default when `oxy bookmark switch` has recorded one.
7482266×
    fn apply_workspace_bookmark(&mut self) {
7492266×
        if let Ok(b) = fs::read_to_string(
7502266×
            self.oxy
7512266×
                .join("workspaces")
7522266×
                .join(self.workspace.to_hex())
7532266×
                .join("bookmark"),
7542266×
        ) {
75541×
            let b = b.trim();
75641×
            if !b.is_empty() {
75741×
                self.config.bookmark = b.to_string();
75841×
            }
7592225×
        }
7602266×
    }
761
7622×
    pub fn user_config_path(&self) -> &Path {
7632×
        &self.user_config
7642×
    }
765
766
    /// Set a key in the user file and refresh the effective configuration.
76728×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
76828×
        Config::set_user(&self.user_config, key, value)?;
76927×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
77027×
        Ok(())
77128×
    }
772
773422×
    pub fn save_config(&self) -> Result<()> {
774422×
        self.config.save(&self.oxy.join("config"))
775422×
    }
776
7775165×
    fn author(&self) -> KeyId {
7785165×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7795165×
    }
780
}
781
782
impl Repo {
7831956×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7841956×
        let mut c = Change {
7851956×
            version: crate::objects::CHANGE_VERSION,
7861956×
            change_id: ChangeId::random(),
7871956×
            deps,
7881956×
            author: self.author(),
7891956×
            hlc: Hlc::now(),
7901956×
            message: message.into(),
7911956×
            tree_ops: vec![],
7921956×
            edits: vec![],
7931956×
            kind: ChangeKind::WorkingCopy,
7941956×
        };
7951956×
        c.normalize();
7961956×
        c
7971956×
    }
798
799
    // ------------------------------------------------------------ operation log
800
80117116×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
80217116×
        if let Some(r) = self.at_op {
8035×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
80417111×
        }
80517111×
        let r = self.head_ref()?;
80617109×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
80717109×
        Ok((r, op))
80817116×
    }
809
81011526×
    pub fn view(&self) -> Result<View> {
81111526×
        Ok(self.head_op()?.1.view)
81211526×
    }
813
8143999×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
8153999×
        self.record_op_undoing(parents, command, view, None)
8163999×
    }
817
818
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
8194002×
    fn record_op_undoing(
8204002×
        &self,
8214002×
        parents: &[ObjectRef],
8224002×
        command: &str,
8234002×
        view: View,
8244002×
        undoes: Option<ObjectRef>,
8254002×
    ) -> Result<ObjectRef> {
8264002×
        if self.at_op.is_some() {
8271×
            return fail(
828
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
829
            );
8304001×
        }
8314001×
        let op = Op {
8324001×
            parents: parents.to_vec(),
8334001×
            hlc: Hlc::now(),
8344001×
            command: command.into(),
8354001×
            view,
8364001×
            workspace: Some(self.workspace),
8374001×
            undoes,
8384001×
        };
8394001×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
840
        // The head is the commit point: everything it names must be on disk first.
8413999×
        let flushing = crate::timing::phase("op: flush the store");
8423999×
        self.store.flush()?;
8433997×
        drop(flushing);
844
        // Compare and swap (spec §12.1): when another process recorded an
845
        // operation since this one read the head, the two are merged
846
        // instead of one overwriting the other. On this disk the head moves
847
        // under a short lock; on any other store by its record's version,
848
        // and a record that moved meanwhile is read again and merged again.
8493997×
        let _lock = if self.store.is_local() {
8503985×
            Some(self.lock_ops()?)
851
        } else {
85212×
            None
853
        };
8543997×
        let Some(parent) = parents.first() else {
855
            // The first operation (init): there is no head yet.
856624×
            if !self.swap_head(&r, None)? {
8572×
                return fail(format!(
858
                    "{} already holds a repository's operation log",
8592×
                    self.store.backend().describe()
860
                ));
861622×
            }
862622×
            return Ok(r);
863
        };
8643373×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8653373×
        for _ in 0..HEAD_TRIES {
8663373×
            let (current, version) = self.read_head()?;
8673373×
            let to = if current == *parent {
8683349×
                r
869
            } else {
87024×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
87123×
                let merged = Op {
87224×
                    parents: vec![current, r],
87324×
                    hlc: Hlc::now(),
87424×
                    command: format!("{command} (merged with a concurrent operation)"),
87524×
                    view: self.merge_views(&base, &op.view, &theirs)?,
87623×
                    workspace: Some(self.workspace),
87723×
                    undoes: None,
878
                };
87923×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
88023×
                self.store.flush()?;
88123×
                m
882
            };
8833372×
            if self.swap_head(&to, version.as_ref())? {
8843366×
                return Ok(to);
8850×
            }
886
        }
8870×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8884002×
    }
889
890
    /// The operation head's lock, held only while the head pointer moves.
8913995×
    fn lock_ops(&self) -> Result<FileLock> {
8923995×
        fs::create_dir_all(self.oxy.join("ops"))?;
8933995×
        FileLock::acquire(
8943995×
            self.oxy.join("ops").join("lock"),
8953995×
            "another oxy process holds the operation log",
896
        )
8973995×
    }
898
899
    /// The operation head this handle reads: the one it first read, or
900
    /// the last one it moved the head to (see [`Repo::refresh`]).
90117113×
    fn head_ref(&self) -> Result<ObjectRef> {
90217113×
        if let Some(r) = self.head_seen.get() {
90313358×
            return Ok(r);
9043755×
        }
9053755×
        let r = self.read_head()?.0;
9063753×
        self.head_seen.set(Some(r));
9073753×
        Ok(r)
90817113×
    }
909
910
    /// Read the operation head again: what another process or handle
911
    /// recorded since this handle first read it becomes visible. A handle
912
    /// keeps the head it first read for the rest of its life otherwise,
913
    /// so whatever it reads comes from one view (oxygenhub#249); a loop
914
    /// that waits for others' operations, or a step that must see what
915
    /// another handle just recorded, refreshes. Packs written since are
916
    /// picked up too.
917504×
    pub fn refresh(&self) -> Result<()> {
918504×
        self.forget_head();
919504×
        self.store.refresh()?;
920504×
        Ok(())
921504×
    }
922
923
    /// Read the operation head again on next use, as [`Repo::refresh`]
924
    /// does, leaving the packs as they are.
9252435×
    pub(crate) fn forget_head(&self) {
9262435×
        self.head_seen.set(None);
9272435×
    }
928
929
    /// The operation head, and on a store its record's version for
930
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
931
    /// any other store (a bucket, or memory in tests) it is the store's
932
    /// [`HEAD_RECORD`] reference record (oxygen#68).
9337219×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
9347219×
        if self.store.is_local() {
9357201×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
9367201×
            let r = ObjectRef::from_hex(hex.trim())
9377201×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
9387198×
            return Ok((r, None));
93918×
        }
94018×
        let backend = self.store.backend();
94118×
        match backend.read_ref(HEAD_RECORD) {
94218×
            Ok(Some((bytes, version))) => {
94318×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
9440×
                    || {
9450×
                        RepoError::Msg(format!(
9460×
                            "the operation head in {} is corrupt",
9470×
                            backend.describe()
9480×
                        ))
9490×
                    },
9500×
                )?;
95118×
                Ok((r, Some(version)))
952
            }
9530×
            Ok(None) => fail(format!(
954
                "{} holds no operation log (no {HEAD_RECORD} record)",
9550×
                backend.describe()
956
            )),
9570×
            Err(e) => fail(format!("read the operation head: {e}")),
958
        }
9597219×
    }
960
961
    /// Move the operation head to `to` from the `expected` version
962
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
963
    /// disk the caller holds the operations lock and the head always
964
    /// moves; on a store it moves only if the record is unchanged, and
965
    /// `false` says another process moved it first.
9664009×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
9674009×
        if self.store.is_local() {
9683995×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
9693989×
            self.head_seen.set(Some(*to));
9703989×
            return Ok(true);
97114×
        }
97214×
        match self
97314×
            .store
97414×
            .backend()
97514×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
976
        {
977
            Ok(_) => {
97811×
                self.head_seen.set(Some(*to));
97911×
                Ok(true)
980
            }
9813×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
9820×
            Err(e) => fail(format!("move the operation head: {e}")),
983
        }
9844009×
    }
985
986
    /// Three-way merge of two views that both started from `base` (spec
987
    /// §12.1). A reference only one side changed takes that side's value.
988
    /// When both changed it differently: a bookmark keeps both sides'
989
    /// heads (it may then have several), a change beats a deletion, a
990
    /// workspace changed by both is an error (only one of them matches the
991
    /// files on disk), and otherwise this process's value wins for remote
992
    /// references and the policy, the first value for a tag (tags never
993
    /// move).
99424×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
99589×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
99689×
            b: &BTreeMap<K, V>,
99789×
            o: &BTreeMap<K, V>,
99889×
            t: &BTreeMap<K, V>,
99989×
            mut both: impl FnMut(&V, &V) -> Result<V>,
100089×
        ) -> Result<BTreeMap<K, V>> {
100189×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
100289×
            let mut out = BTreeMap::new();
100392×
            for k in keys {
100492×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
100592×
                let v = if ov == tv || tv == bv {
100647×
                    ov.cloned()
100745×
                } else if ov == bv {
100827×
                    tv.cloned()
1009
                } else {
101018×
                    match (ov, tv) {
101118×
                        (Some(x), Some(y)) => Some(both(x, y)?),
10120×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
10130×
                        (None, None) => None,
1014
                    }
1015
                };
101691×
                if let Some(v) = v {
101791×
                    out.insert(k.clone(), v);
101891×
                }
1019
            }
102088×
            Ok(out)
102189×
        }
102224×
        let bookmarks = pick(
102324×
            &base.bookmarks,
102424×
            &ours.bookmarks,
102524×
            &theirs.bookmarks,
102617×
            |x, y| {
102717×
                let mut heads = self.store.get_state(x)?.heads;
102817×
                heads.extend(self.store.get_state(y)?.heads);
102917×
                let heads = self.load_state(&heads)?.maximal(&heads);
103017×
                Ok(self.store.put_state(&StateObject::new(heads))?)
103117×
            },
10320×
        )?;
1033
        // Two operations that both replaced one workspace's working copy
1034
        // cannot both be right: the files on disk match only one of them.
1035
        // The working-copy lock keeps this from happening; should it happen
1036
        // anyway, this operation is not recorded.
103724×
        let workspaces = pick(
103824×
            &base.workspaces,
103924×
            &ours.workspaces,
104024×
            &theirs.workspaces,
10411×
            |_, _| {
10421×
                fail(
1043
                    "another oxy process changed this working copy at the same time; \
1044
                     this command was not recorded: check `oxy status` and run it again",
1045
                )
10461×
            },
10471×
        )?;
104823×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
104923×
        let empty = BTreeMap::new();
105023×
        let names: BTreeSet<&String> = base
105123×
            .remotes
105223×
            .keys()
105323×
            .chain(ours.remotes.keys())
105423×
            .chain(theirs.remotes.keys())
105523×
            .collect();
105623×
        let mut remotes = BTreeMap::new();
105723×
        for n in names {
105818×
            let m = pick(
105918×
                base.remotes.get(n).unwrap_or(&empty),
106018×
                ours.remotes.get(n).unwrap_or(&empty),
106118×
                theirs.remotes.get(n).unwrap_or(&empty),
10620×
                |x, _| Ok(*x),
10630×
            )?;
106418×
            if !m.is_empty() {
106518×
                remotes.insert(n.clone(), m);
106618×
            }
1067
        }
106823×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
106923×
            ours.policy
10700×
        } else if ours.policy == base.policy {
10710×
            theirs.policy
1072
        } else {
10730×
            ours.policy.or(theirs.policy)
1074
        };
107523×
        self.store.flush()?;
107623×
        Ok(View {
107723×
            bookmarks,
107823×
            workspaces,
107923×
            remotes,
108023×
            policy,
108123×
            tags,
108223×
        })
108324×
    }
1084
108558×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
108658×
        let mut out = Vec::new();
108758×
        let (mut r, mut op) = self.head_op()?;
1088
        loop {
1089299×
            let next = op.parents.first().copied();
1090299×
            out.push((r, op));
1091299×
            match next {
1092241×
                Some(p) => {
1093241×
                    r = p;
1094241×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1095
                }
109658×
                None => break,
1097
            }
1098
        }
109958×
        Ok(out)
110058×
    }
1101
1102
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1103
    ///
1104
    /// The command undone is the newest one this workspace ran: operations
1105
    /// that only recorded a working-copy snapshot are skipped (the files are
1106
    /// still on disk and the next snapshot recreates them), as are pushes
1107
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1108
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1109
    /// operations are never undone, and a command an earlier undo already
1110
    /// reverted is passed over, so undoing again goes further back.
1111
    ///
1112
    /// When nothing newer came from another workspace, the operation head
1113
    /// moves back to before the command. Otherwise the command is reverted
1114
    /// in place: every reference it changed goes back to its value before
1115
    /// it, recorded as a new operation that names it, and anything another
1116
    /// workspace changed since is kept. A reference both the command and a
1117
    /// later operation of another workspace changed is not guessed at: the
1118
    /// undo is refused, naming it.
1119
    ///
1120
    /// When the working copy is clean and was clean after the command's
1121
    /// predecessor, its files follow too, since nothing on disk can be
1122
    /// lost; otherwise they stay as they are (an undone commit's edits come
1123
    /// back as uncommitted work).
112416×
    pub fn undo(&self) -> Result<Undone> {
112516×
        let _wc = self.lock_working_copy()?;
112616×
        let clean_now =
112716×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
112816×
        let (head_ref, head) = self.head_op()?;
112916×
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
113039×
        let load = |r: &ObjectRef| -> Result<Op> {
113139×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
113239×
        };
113316×
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
113416×
        let mut pending_checkout: Option<Op> = None;
113516×
        let mut others = 0usize;
113616×
        let (mut r, mut op) = (head_ref, head.clone());
113715×
        let (target_ref, target, parent) = loop {
113840×
            let parent = match op.parents.first() {
113939×
                Some(p) => Some((*p, load(p)?)),
11401×
                None => None,
1141
            };
114240×
            if skip.contains(&r) {
11431×
                pending_checkout = None;
114439×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
11459×
                // A push cannot be taken back: undoing it would only make
11469×
                // this repository forget what the remote holds.
114730×
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
114810×
                others += 1;
114920×
            } else if let Some(u) = op.undoes {
11501×
                skip.insert(u);
11511×
                pending_checkout = None;
115219×
            } else if op.command.ends_with(" (checkout)") {
11533×
                pending_checkout = Some(op.clone());
11543×
            } else {
115516×
                match parent {
115615×
                    Some((_, p)) => break (r, op, p),
11571×
                    None => return fail("nothing to undo in this workspace"),
1158
                }
1159
            }
116024×
            match parent {
116124×
                Some((pr, p)) => (r, op) = (pr, p),
11620×
                None => return fail("nothing to undo in this workspace"),
1163
            }
1164
        };
116515×
        let before = parent.view;
116615×
        let after = pending_checkout
116715×
            .map(|o| o.view)
116815×
            .unwrap_or_else(|| target.view.clone());
116915×
        let changes = self.view_changes(&before, &after)?;
117015×
        let pushed = self.pushed_by(&before, &after, &head.view)?;
117115×
        let restored_wc = before.workspaces.get(&self.workspace).copied();
117215×
        if others == 0 {
1173
            // Only this workspace's operations since: move the head back.
117410×
            let _lock = if self.store.is_local() {
117510×
                Some(self.lock_ops()?)
1176
            } else {
11770×
                None
1178
            };
117910×
            let parent_ref = *target.parents.first().expect("the target has a parent");
118010×
            let (now, version) = self.read_head()?;
118110×
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
11820×
                return fail("another oxy command ran while undoing; run undo again");
118310×
            }
1184
        } else {
11855×
            let view = self.revert_view(&head.view, &before, &after)?;
11863×
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1187
        }
118813×
        self.drop_manifest();
118913×
        if let Some(then) = restored_wc {
119013×
            if clean_now && Some(then) != wc_now {
1191
                // Past `core.snapshot-retention` the working copy may be
1192
                // gone: the files then stay as they are.
119310×
                let Ok(wc) = self.store.get_change(&then) else {
11940×
                    return Ok(Undone {
11950×
                        command: target.command,
11960×
                        changes,
11970×
                        others_kept: others,
11980×
                        pushed,
11990×
                    });
1200
                };
120110×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
12028×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1203
                    // The files differ from the restored working copy by
1204
                    // exactly what the undone command did: nothing else is
1205
                    // on disk, as the working copy was clean.
12068×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
12072×
                }
12083×
            }
12090×
        }
121013×
        Ok(Undone {
121113×
            command: target.command,
121213×
            changes,
121313×
            others_kept: others,
121413×
            pushed,
121513×
        })
121616×
    }
1217
1218
    /// Whether operation `op` was a push: it changed only what this
1219
    /// repository knows of remotes.
122031×
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
122131×
        let Some(p) = parent else {
12221×
            return false;
1223
        };
122430×
        op.command.starts_with("oxy push")
12251×
            && op.view.bookmarks == p.view.bookmarks
12261×
            && op.view.tags == p.view.tags
12271×
            && op.view.workspaces == p.view.workspaces
12281×
            && op.view.policy == p.view.policy
122931×
    }
1230
1231
    /// Whether operation `op` (whose predecessor is `parent`) was this
1232
    /// workspace's. Operations record their workspace (oxygen#99); for older
1233
    /// ones it is read from the view: one that changed only other
1234
    /// workspaces' working copies was theirs, anything else counts as ours.
123530×
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
123630×
        if let Some(w) = op.workspace {
123730×
            return w == self.workspace;
12380×
        }
12390×
        let Some(p) = parent else {
12400×
            return true;
1241
        };
12420×
        let ids: BTreeSet<&WorkspaceId> = op
12430×
            .view
12440×
            .workspaces
12450×
            .keys()
12460×
            .chain(p.view.workspaces.keys())
12470×
            .collect();
12480×
        let moved: Vec<&WorkspaceId> = ids
12490×
            .into_iter()
12500×
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
12510×
            .collect();
12520×
        moved.is_empty() || moved.contains(&&self.workspace)
125330×
    }
1254
1255
    /// `current` with what changed from `before` to `after` put back, this
1256
    /// workspace's working copy included; refused when a later operation
1257
    /// changed one of the same references again.
12585×
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
125910×
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
126010×
            cur: &mut BTreeMap<K, V>,
126110×
            before: &BTreeMap<K, V>,
126210×
            after: &BTreeMap<K, V>,
126310×
            name: impl Fn(&K) -> String,
126410×
            clashes: &mut Vec<String>,
126510×
        ) {
126610×
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
126710×
            for k in keys {
12685×
                let (b, a) = (before.get(k), after.get(k));
12695×
                if a == b {
12704×
                    continue;
12711×
                }
12721×
                if cur.get(k) != a {
12731×
                    clashes.push(name(k));
12741×
                    continue;
12750×
                }
12760×
                match b {
12770×
                    Some(v) => cur.insert(k.clone(), v.clone()),
12780×
                    None => cur.remove(k),
1279
                };
1280
            }
128110×
        }
12825×
        let mut out = current.clone();
12835×
        let mut clashes = Vec::new();
1284
        // A bookmark another workspace moved since is put back head by
1285
        // head: the heads the command added go, the heads it replaced
1286
        // return, and the other workspace's heads stay. Only when a later
1287
        // change was built on one the command added is that not possible.
12885×
        let names: BTreeSet<&String> = before
12895×
            .bookmarks
12905×
            .keys()
12915×
            .chain(after.bookmarks.keys())
12925×
            .collect();
12938×
        for name in names {
12948×
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
12958×
            let cur = current.bookmarks.get(name);
12968×
            if a == b {
12974×
                continue;
12984×
            }
12994×
            if cur == a {
13002×
                match b {
13012×
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
13020×
                    None => out.bookmarks.remove(name),
1303
                };
13042×
                continue;
13052×
            }
13062×
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
13070×
                clashes.push(format!("bookmark {name}"));
13080×
                continue;
1309
            };
13102×
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
13112×
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
13122×
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
13132×
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
13142×
            if !added.iter().all(|h| now.contains(h)) {
13151×
                clashes.push(format!(
1316
                    "bookmark {name} (a later change builds on this one)"
1317
                ));
13181×
                continue;
13191×
            }
13201×
            let mut heads: Vec<ChangeHash> = now
13211×
                .iter()
13223×
                .filter(|h| !added.contains(h))
13231×
                .chain(was.difference(&became))
13241×
                .copied()
13251×
                .collect();
13261×
            heads.sort();
13271×
            heads.dedup();
13281×
            let heads = self.load_state(&heads)?.maximal(&heads);
13291×
            out.bookmarks.insert(
13301×
                name.clone(),
13311×
                self.store.put_state(&StateObject::new(heads))?,
1332
            );
1333
        }
1334
13355×
        back(
13365×
            &mut out.tags,
13375×
            &before.tags,
13385×
            &after.tags,
13390×
            |k| format!("tag {k}"),
13405×
            &mut clashes,
1341
        );
13425×
        let mine = self.workspace;
134315×
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
134415×
            v.workspaces
134515×
                .iter()
134629×
                .filter(|(k, _)| **k != mine)
134715×
                .map(|(k, v)| (*k, *v))
134815×
                .collect()
134915×
        };
13505×
        let mut theirs = others(&out);
13515×
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
13521×
            Some(p) => format!("the workspace at {}", p.display()),
13530×
            None => format!("workspace {}", id.to_hex()),
13541×
        };
13555×
        back(
13565×
            &mut theirs,
13575×
            &others(before),
13585×
            &others(after),
13595×
            workspace_name,
13605×
            &mut clashes,
1361
        );
13625×
        let empty = BTreeMap::new();
13635×
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
13645×
        for n in names {
13650×
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
13660×
            back(
13670×
                &mut cur,
13680×
                before.remotes.get(n).unwrap_or(&empty),
13690×
                after.remotes.get(n).unwrap_or(&empty),
13700×
                |k| format!("{n}/{k}"),
13710×
                &mut clashes,
1372
            );
13730×
            if cur.is_empty() {
13740×
                out.remotes.remove(n);
13750×
            } else {
13760×
                out.remotes.insert(n.clone(), cur);
13770×
            }
1378
        }
13795×
        if before.policy != after.policy {
13800×
            if out.policy == after.policy {
13810×
                out.policy = before.policy;
13820×
            } else {
13830×
                clashes.push("the policy".into());
13840×
            }
13855×
        }
13865×
        if !clashes.is_empty() {
13872×
            return fail(format!(
1388
                "undo would also take back what another workspace has done since to {}; \
1389
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
13902×
                clashes.join(", ")
1391
            ));
13923×
        }
13933×
        out.workspaces = theirs;
13943×
        match before.workspaces.get(&mine) {
13953×
            Some(wc) => out.workspaces.insert(mine, *wc),
13960×
            None => out.workspaces.remove(&mine),
1397
        };
13983×
        Ok(out)
13995×
    }
1400
1401
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1402
    /// in `now` already holds: undoing them locally leaves them there.
140315×
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
140415×
        let mut out = Vec::new();
140518×
        for (name, st) in &after.bookmarks {
140618×
            if before.bookmarks.get(name) == Some(st) {
14074×
                continue;
140814×
            }
140914×
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
141014×
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
14110×
                None => BTreeSet::new(),
1412
            };
141314×
            let added: Vec<ChangeHash> = self
141414×
                .store
141514×
                .get_state(st)?
1416
                .heads
141714×
                .into_iter()
141820×
                .filter(|h| !had.contains(h))
141914×
                .collect();
142014×
            if added.is_empty() {
14211×
                continue;
142213×
            }
142313×
            for (remote, bookmarks) in &now.remotes {
14241×
                if let Some(rs) = bookmarks.get(name) {
14251×
                    let theirs = self.store.get_state(rs)?.heads;
14261×
                    if added.iter().any(|h| theirs.contains(h)) {
14271×
                        out.push((name.clone(), remote.clone()));
14281×
                    }
14290×
                }
1430
            }
1431
        }
143215×
        Ok(out)
143315×
    }
1434
1435
    /// The last operation that was not a snapshot.
14362×
    pub fn last_command(&self) -> Result<Op> {
14372×
        let (_, mut op) = self.head_op()?;
14384×
        while op.is_snapshot() {
14392×
            let Some(parent) = op.parents.first() else {
14400×
                break;
1441
            };
14422×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1443
        }
14442×
        Ok(op)
14452×
    }
1446
1447
    // ------------------------------------------------------------ states
1448
1449
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1450222×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1451222×
        if let Some(st) = self.load_state_checkpointed(heads)? {
14524×
            return Ok(st);
1453217×
        }
1454217×
        self.load_state_full(heads)
1455222×
    }
1456
1457
    /// The state of `heads` for its history (changes, tree, metadata) with
1458
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1459
    /// and friends. Build the graphs a command needs with
1460
    /// [`Repo::load_graphs_of`].
14612140×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
14622140×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
146344×
            return Ok(st);
14642096×
        }
14652096×
        self.load_state_replayed(heads, State::new_history_only())
14662140×
    }
1467
1468
    /// Build these file graphs in a history-only state.
14692239×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
14702239×
        state
14712239×
            .load_graphs(
14722239×
                nodes,
147354×
                |refs| {
147454×
                    self.read_blobs(refs).map_err(|e| {
14753×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14763×
                    })
147754×
                },
14782454×
                |h| self.change_bytes(h),
1479
            )
14802239×
            .map_err(|e| self.index_damage(e))
14812239×
    }
1482
1483
    /// The tree of `state` as every reader sees it ([`State::view`]), with
1484
    /// the graphs built that it compares: same-path additions with
1485
    /// identical content are one entry, not a name conflict.
14862510×
    pub fn tree_view(&self, state: &mut State) -> Result<crate::tree::TreeView> {
14872510×
        let need = state.unify_candidates();
14882510×
        if !need.is_empty() {
1489110×
            self.load_graphs_of(state, &need)?;
14902400×
        }
14912510×
        Ok(state.view())
14922510×
    }
1493
1494
    /// An error building graphs, and when it is a state index found
1495
    /// damaged (a file's history that does not match its hash), the
1496
    /// workspace's state indexes removed: they are rebuilt from history by
1497
    /// the next command.
14984×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
14994×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
15003×
            return e.into();
1501
        };
15022×
        for path in self.state_indexes() {
15032×
            let _ = fs::remove_file(path);
15042×
        }
15051×
        RepoError::Msg(format!(
15061×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
15071×
        ))
15084×
    }
1509
1510
    /// The graphs of `nodes` of a history-only state, built beside it (see
1511
    /// [`State::build_graphs_detached`]).
151277×
    pub fn build_graphs_detached(
151377×
        &self,
151477×
        state: &State,
151577×
        nodes: &[crate::ids::NodeId],
151677×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
151777×
        Ok(state
151877×
            .build_graphs_detached(
151977×
                nodes,
15200×
                |refs| {
15210×
                    self.read_blobs(refs).map_err(|e| {
15220×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15230×
                    })
15240×
                },
152583×
                |h| self.change_bytes(h),
1526
            )
152777×
            .map_err(|e| self.index_damage(e))?
152877×
            .into_iter()
152977×
            .collect())
153077×
    }
1531
1532
    /// The contents of texts [`State::single_text`] gave: blobs read in
1533
    /// one go, inline ones from their changes.
1534432×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1535
        use crate::objects::TextRef;
1536432×
        let refs: Vec<ObjectRef> = texts
1537432×
            .iter()
15385571×
            .filter_map(|t| match t {
15391×
                TextRef::Blob(r, _, _) => Some(*r),
15405570×
                TextRef::Inline { .. } => None,
15415571×
            })
1542432×
            .collect();
1543432×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1544432×
        let mut out = Vec::with_capacity(texts.len());
15455571×
        for t in texts {
15465571×
            let lines = match t {
15471×
                TextRef::Blob(_, count, form) => {
15481×
                    let content = blobs
15491×
                        .next()
15501×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
15511×
                    crate::objects::text_lines(&content, *count, *form)?
1552
                }
15535570×
                TextRef::Inline { change, start, end } => {
15545570×
                    let bytes = self.change_bytes(change)?;
15555570×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
15560×
                        RepoError::Msg("an inline insert lies outside its change".into())
15570×
                    })?;
15585570×
                    crate::objects::inline_lines(range)?
1559
                }
1560
            };
15615571×
            out.push(lines.bytes().to_vec());
1562
        }
1563432×
        Ok(out)
1564432×
    }
1565
1566
    /// Build every graph a history-only state still lacks, making it full.
15672526×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
15682526×
        state
15692526×
            .load_all_graphs(
157016×
                |refs| {
157116×
                    self.read_blobs(refs).map_err(|e| {
15720×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15730×
                    })
157416×
                },
15755361×
                |h| self.change_bytes(h),
1576
            )
15772526×
            .map_err(|e| self.index_damage(e))
15782526×
    }
1579
1580
    /// A change's encoding, for building graphs of its inline inserts. The
1581
    /// last few read are kept: a checkout building graphs a batch at a
1582
    /// time reads the same large changes for every batch, often in turn.
158313468×
    fn change_bytes(
158413468×
        &self,
158513468×
        h: &ChangeHash,
158613468×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
158713468×
        let mut cache = self.last_change.borrow_mut();
158823078×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
158910482×
            let hit = cache.remove(i);
159010482×
            let b = hit.1.clone();
159110482×
            cache.push(hit);
159210482×
            return Ok(b);
15932986×
        }
15942986×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
15950×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
15960×
        })?);
15972986×
        cache.push((*h, b.clone()));
1598
        // The last few, within a memory budget; the newest always stays.
15994859×
        while cache.len() > CHANGE_CACHE_COUNT
16002986×
            || (cache.len() > 1
16019088×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
16021873×
        {
16031873×
            cache.remove(0);
16041873×
        }
16052986×
        Ok(b)
160613468×
    }
1607
1608
    /// Load the dependency closure of `heads` change by change.
1609271×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1610271×
        self.load_state_replayed(heads, State::new())
1611271×
    }
1612
16134091×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
16144091×
        let history = state.is_history_only();
16154091×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
16164091×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1617
        {
16184091×
            let _t = crate::timing::phase("load: read and add changes");
16194091×
            let (mut read, mut add, mut fetch) = (
16204091×
                std::time::Duration::ZERO,
16214091×
                std::time::Duration::ZERO,
16224091×
                std::time::Duration::ZERO,
16234091×
            );
162416691×
            while let Some(h) = stack.pop() {
1625
                // A change the state holds brings its history with it.
162612605×
                if !seen.insert(h) || state.contains(&h) {
16273034×
                    continue;
16289571×
                }
16299571×
                let t0 = std::time::Instant::now();
1630
                // A history-only state reads text only for the graphs it
1631
                // builds; either way the hash is the one asked for.
16329571×
                let (c, texts) = if history {
16338023×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
16348020×
                    fetch += t0.elapsed();
16358020×
                    Change::decode_skeleton(&bytes, h)
16368020×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1637
                } else {
16381548×
                    (self.store.get_change(&h)?, Vec::new())
1639
                };
16409566×
                read += t0.elapsed();
16419566×
                stack.extend(c.deps.iter().copied());
16429566×
                let t1 = std::time::Instant::now();
16439566×
                state.add_known(h, c, texts);
16449566×
                add += t1.elapsed();
1645
            }
16464086×
            crate::timing::record("load:   of which reading", read);
16474086×
            crate::timing::record("load:     of which fetching", fetch);
16484086×
            crate::timing::record("load:   of which applying", add);
1649
        }
16504086×
        let _t = crate::timing::phase("load: validate");
16514086×
        state.validate()?;
16524086×
        Ok(state)
16534091×
    }
1654
16552836×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
16562836×
        if self.bare {
16572×
            return fail("this is a bare repository: it has no working copy");
16582834×
        }
16592834×
        let view = self.view()?;
16602834×
        let h = *view
16612834×
            .workspaces
16622834×
            .get(&self.workspace)
16632834×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
16642833×
        Ok((h, self.store.get_change(&h)?))
16652836×
    }
1666
1667
    /// Heads of a bookmark's state (spec §10.1).
16682049×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
16692049×
        match view.bookmarks.get(bookmark) {
16702049×
            Some(st) => Ok(self.store.get_state(st)?.heads),
16710×
            None => Ok(vec![]),
1672
        }
16732049×
    }
1674
1675574×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1676574×
        self.heads_of(&self.view()?, &self.config.bookmark)
1677574×
    }
1678
1679
    // ------------------------------------------------------------ blobs
1680
1681486×
    fn blob_for(content: &[u8]) -> Blob {
1682486×
        Blob::of(content)
1683486×
    }
1684
1685267×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1686267×
        Self::blob_for(content).hash()
1687267×
    }
1688
1689217×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1690303×
        for c in crate::chunk::chunks(content) {
1691303×
            self.store.put_chunk(c)?;
1692
        }
1693217×
        Ok(self
1694217×
            .store
1695217×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1696217×
    }
1697
1698
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1699
    /// all their chunks, are read in parallel; a blob the store lacks goes
1700
    /// through [`Repo::read_blob`], which may fetch it lazily.
1701506×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1702506×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1703506×
        let t = crate::timing::phase("blobs: get_many blobs");
1704506×
        let got_all = self.store.get_many(refs);
1705506×
        drop(t);
1706506×
        for (r, got) in refs.iter().zip(got_all) {
170780×
            blobs.push(match got {
170875×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
17090×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
17105×
                Err(crate::store::StoreError::NotFound(_)) => None,
17110×
                Err(e) => return Err(e.into()),
1712
            });
1713
        }
1714506×
        let chunk_refs: Vec<ObjectRef> = blobs
1715506×
            .iter()
1716506×
            .flatten()
1717506×
            .flat_map(|b| b.chunks.iter().copied())
1718506×
            .collect();
1719506×
        let t = crate::timing::phase("blobs: get_many chunks");
1720506×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1721506×
        drop(t);
1722506×
        if crate::timing::enabled() {
17230×
            eprintln!(
1724
                "timing blobs: {} blobs, {} chunks, {} one by one",
17250×
                refs.len(),
17260×
                chunk_refs.len(),
17270×
                blobs.iter().filter(|b| b.is_none()).count()
1728
            );
1729506×
        }
1730506×
        let mut out = Vec::with_capacity(refs.len());
1731506×
        for (r, blob) in refs.iter().zip(blobs) {
173280×
            match blob {
17335×
                None => out.push(self.read_blob(r)?),
173475×
                Some(b) => {
173575×
                    let mut content = Vec::with_capacity(b.length as usize);
1736114×
                    for c in &b.chunks {
1737114×
                        match chunks.next() {
1738114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
17390×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
17400×
                            Some(Err(e)) => return Err(e.into()),
17410×
                            None => return fail("chunk list ended early"),
1742
                        }
1743
                    }
174475×
                    out.push(content);
1745
                }
1746
            }
1747
        }
1748501×
        Ok(out)
1749506×
    }
1750
1751
    /// Read a blob's content, fetching it from the remote that withheld it
1752
    /// when it is lazily absent (spec §13.5).
1753218×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1754218×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
17555×
            self.fetch_lazy_blob(r)?;
1756213×
        }
1757218×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1758213×
        let mut out = Vec::with_capacity(blob.length as usize);
1759282×
        for c in &blob.chunks {
1760282×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1761
        }
1762213×
        Ok(out)
1763218×
    }
1764
1765
    // ------------------------------------------------------------ working copy
1766
1767
    /// Attributes from the `.oxyattributes` files in the working directory.
17682×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1769
        // Nested repositories and ignored paths are left out, as in a walk.
17708×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
17712×
        let files: Vec<(String, Vec<u8>)> = listing
17722×
            .files
17732×
            .into_iter()
17742×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
17752×
            .collect();
17762×
        crate::attributes::Attributes::from_files(
17772×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1778
        )
17792×
    }
1780
1781
    /// Folders holding a repository of their own that the last look at the
1782
    /// working copy left out, not being subrepos (oxygen#43).
178330×
    pub fn untracked_nested(&self) -> Vec<String> {
178430×
        self.untracked_nested.borrow().clone()
178530×
    }
1786
1787
    /// New untracked files the last snapshot left out for being larger than
1788
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
178934×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
179034×
        self.skipped_large.borrow().clone()
179134×
    }
1792
1793
    /// Attributes from a materialized state's `.oxyattributes` files.
17946×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
179513×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
179613×
            match &f.content {
179713×
                FileContent::Text { bytes, .. }
179813×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1799
                {
18002×
                    Some((p.as_str(), bytes.as_slice()))
1801
                }
180211×
                _ => None,
1803
            }
180413×
        }))
18056×
    }
1806
1807
    /// Store a blob, raw when the path is `nocompress`.
1808183×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1809183×
        if !nocompress {
1810181×
            return self.store_blob(content);
18112×
        }
18122×
        for c in crate::chunk::chunks(content) {
18132×
            self.store.put_chunk_nocompress(c)?;
1814
        }
18152×
        Ok(self
18162×
            .store
18172×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1818183×
    }
1819
1820
    /// This workspace's state index (oxygen#41): its working copy's base,
1821
    /// saved so a snapshot reads it rather than replaying history.
1822
    /// The state index of the state with these heads: this workspace keeps
1823
    /// the last few it used, named by their heads, so moving between two
1824
    /// states finds both.
18252966×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
18262966×
        let mut heads = heads.to_vec();
18272966×
        heads.sort();
18282966×
        let mut h = blake3::Hasher::new();
18293103×
        for c in &heads {
18303103×
            h.update(&c.0);
18313103×
        }
18322966×
        self.oxy.join("index").join(format!(
18332966×
            "{}{}",
18342966×
            self.state_index_prefix(),
18352966×
            &h.finalize().to_hex()[..16]
18362966×
        ))
18372966×
    }
1838
18395827×
    fn state_index_prefix(&self) -> String {
18405827×
        format!("state-{}-", self.workspace.to_hex())
18415827×
    }
1842
1843
    /// This workspace's state indexes, newest first.
18442861×
    fn state_indexes(&self) -> Vec<PathBuf> {
18452861×
        let prefix = self.state_index_prefix();
18462861×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
18472861×
            .into_iter()
18482861×
            .flatten()
18492861×
            .flatten()
18502861×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
18512861×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
18522861×
            .collect();
18532861×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
18542861×
        found.into_iter().map(|(_, p)| p).collect()
18552861×
    }
1856
1857
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1858
    /// from this workspace's state index when it holds that history: every
1859
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1860
    /// is loaded from history and indexed for next time.
18612487×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
18622487×
        if let Some((st, heads)) = self.read_state_index(deps) {
18632016×
            let mut have = st.maximal(deps);
18642016×
            have.sort();
18652016×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1866
                // Re-encoding reads every history: one found damaged is
1867
                // left to the build that reads it, which reports it.
1868
                #[cfg(test)]
1869170×
                if let Some(mine) = st.write_index() {
1870165×
                    assert_eq!(
1871165×
                        Some(mine),
1872165×
                        self.load_state_history(deps)?.write_index(),
1873
                        "a state index holds the state history gives"
1874
                    );
18755×
                }
1876292×
                return Ok(st);
18771724×
            }
1878
            // An index a few changes behind (a commit, a pull since): add
1879
            // what it lacks, as long as all it holds is history of `deps`.
1880
            // Anything amiss (a change beyond a shallow boundary) takes the
1881
            // long way instead.
18821724×
            let (indexed, started) = (st.len(), std::time::Instant::now());
18831724×
            if let Ok(st) = self.load_state_replayed(deps, st) {
18841721×
                let mut all = deps.to_vec();
18851721×
                all.extend(heads.iter().copied());
18861721×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
18871721×
                within.sort();
18881721×
                want.sort();
18891721×
                if within == want {
1890
                    #[cfg(test)]
1891976×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1892
                    // Writing the index costs far more than replaying a
1893
                    // few small changes: it is rewritten once it falls
1894
                    // behind, or when replaying took long (large changes).
18951720×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
18961720×
                        || started.elapsed() > INDEX_REPLAY_TIME
18973×
                    {
18983×
                        self.write_state_index(deps, &st);
18991717×
                    }
19001720×
                    return Ok(st);
19011×
                }
19023×
            }
1903471×
        }
1904475×
        let st = self.load_state_history(deps)?;
1905475×
        self.write_state_index(deps, &st);
1906475×
        Ok(st)
19072487×
    }
1908
1909
    /// Two history-only states hold the same changes and render the same
1910
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1911
    /// the checkpoint's graphs as the bases of its files' histories.
1912
    #[cfg(test)]
1913976×
    fn assert_same_state(&self, a: &State, b: &State) {
19141952×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1915976×
        assert_eq!(ids(a), ids(b), "the same changes");
19161952×
        let files = |s: &State| {
19171952×
            let mut s = s.clone();
19181952×
            self.load_all_graphs(&mut s).unwrap();
19191952×
            s.materialize().files
19201952×
        };
1921976×
        assert_eq!(files(a), files(b), "the same files");
1922976×
    }
1923
1924
    /// The state index file: its heads, a hash of its changes block and one
1925
    /// of the rest, then the body [`State::write_index`] gives, whose first
1926
    /// block is the changes. Hashed in two parts so the log can read and
1927
    /// check the changes alone.
1928
    /// The index of `deps` if there is one, else the newest, which the
1929
    /// caller may bring up to date.
19302487×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1931
        use std::io::Read;
19322487×
        let _t = crate::timing::phase("load: state index");
19332487×
        let exact = self.state_index_path(deps);
19342487×
        let reading = crate::timing::phase("load:   of which reading the file");
19352487×
        let mut f = match fs::File::open(&exact) {
1936292×
            Ok(f) => {
1937
                // Used now: the newest, so the last to be dropped.
1938292×
                let _ = fs::File::options()
1939292×
                    .write(true)
1940292×
                    .open(&exact)
1941292×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1942292×
                f
1943
            }
19442195×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1945
        };
19462016×
        let total = f.metadata().ok()?.len();
19472016×
        let mut word = [0u8; 4];
19482016×
        f.read_exact(&mut word).ok()?;
19492016×
        let n = u32::from_le_bytes(word) as usize;
19502016×
        let mut head = vec![0u8; 32 * n + 64 + 8];
19512016×
        f.read_exact(&mut head).ok()?;
19522016×
        let heads: Vec<ChangeHash> = head[..32 * n]
19532016×
            .chunks_exact(32)
19542016×
            .map(|c| ObjectRef(c.try_into().unwrap()))
19552016×
            .collect();
19562016×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
19572016×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
19582016×
        let at = (4 + head.len()) as u64;
19592016×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
19600×
            return None;
19612016×
        }
1962
        // The front only: the files' histories after it are read, each
1963
        // checked by its own hash, when a command builds that file.
19642016×
        let mut front = vec![0u8; front_len as usize];
19652016×
        f.read_exact(&mut front).ok()?;
19662016×
        drop(reading);
19672016×
        let checking = crate::timing::phase("load:   of which checking the file");
19682016×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
19692016×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
19704032×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
19712016×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
19720×
            return None;
19732016×
        }
19742016×
        drop(checking);
19752016×
        let histories = crate::state::Histories::File(
19762016×
            std::sync::Arc::new(f),
19772016×
            at + front_len,
19782016×
            total - at - front_len,
19792016×
        );
19802016×
        Some((State::read_index_front(&front, histories).ok()?, heads))
19812487×
    }
1982
1983
    /// The changes of this workspace's state index (the closure of its
1984
    /// heads), read without the rest of the index.
1985
    #[allow(clippy::type_complexity)]
1986185×
    pub(crate) fn read_state_index_changes(
1987185×
        &self,
1988185×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1989
        use std::io::Read;
1990185×
        let _t = crate::timing::phase("load: state index changes");
1991185×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1992168×
        let mut word = [0u8; 4];
1993168×
        f.read_exact(&mut word).ok()?;
1994168×
        let n = u32::from_le_bytes(word) as usize;
1995
        // Heads, the two sums, the front's length, then the changes block.
1996168×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1997168×
        f.read_exact(&mut head).ok()?;
1998168×
        let heads: Vec<ChangeHash> = head[..32 * n]
1999168×
            .chunks_exact(32)
2000168×
            .map(|c| ObjectRef(c.try_into().unwrap()))
2001168×
            .collect();
2002168×
        let sum = &head[32 * n..32 * n + 32];
2003168×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
2004168×
        let mut changes = vec![0u8; 4 + len];
2005168×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
2006168×
        f.read_exact(&mut changes[4..]).ok()?;
2007168×
        let checking = crate::timing::phase("load:   of which checking");
2008168×
        let mut h = blake3::Hasher::new();
2009168×
        h.update_rayon(&changes);
2010168×
        if h.finalize().as_bytes() != sum {
20110×
            return None;
2012168×
        }
2013168×
        drop(checking);
2014168×
        let _decoding = crate::timing::phase("load:   of which decoding");
2015168×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
2016185×
    }
2017
2018
    /// Save `st`, the history-only state of `deps`, as this workspace's
2019
    /// state index; quietly nothing when it cannot be (it is only a cache).
2020479×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
2021479×
        let _t = crate::timing::phase("write: state index");
2022479×
        let encoding = crate::timing::phase("write:   of which encoding");
2023479×
        let Some(body) = st.write_index() else {
20240×
            return;
2025
        };
2026479×
        drop(encoding);
2027
        #[cfg(test)]
2028281×
        assert_eq!(
2029281×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
2030281×
            Some(body.clone()),
2031
            "a state index reads back as written"
2032
        );
2033479×
        let mut heads = st.maximal(deps);
2034479×
        heads.sort();
2035479×
        let mut w = crate::flat::Writer::default();
2036479×
        w.count(heads.len());
2037479×
        for h in &heads {
203810×
            w.object(h);
203910×
        }
2040
        // The body is the front's length, the front, then the files'
2041
        // histories, which carry their own hashes: the sums cover the
2042
        // front's changes block and the rest of the front.
2043479×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
2044479×
        let front = &body[8..8 + front_len];
2045479×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
2046958×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
2047479×
        w.fixed(&sum(&front[..split]));
2048479×
        w.fixed(&sum(&front[split..]));
2049479×
        w.fixed(&body);
2050479×
        let path = self.state_index_path(&heads);
2051479×
        let _ = fs::create_dir_all(self.oxy.join("index"));
2052479×
        let _ = write_cache(&path, &w.0);
2053
        // The last two used: the index of a state moved away from stays for
2054
        // a move back. Older ones (and the unnamed one of before) go.
2055479×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
20561×
            let _ = fs::remove_file(old);
20571×
        }
2058479×
        let _ = fs::remove_file(
2059479×
            self.oxy
2060479×
                .join("index")
2061479×
                .join(format!("state-{}", self.workspace.to_hex())),
2062479×
        );
2063479×
    }
2064
20656×
    fn locks_dir(&self) -> PathBuf {
20666×
        self.oxy.join("locks")
20676×
    }
2068
2069
    /// Whether `path` is locked locally for editing (spec §18, advisory).
20703×
    pub fn is_locked(&self, path: &str) -> bool {
20713×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
20723×
    }
2073
2074
    /// Take the advisory local lock on a `lockable` file and make it writable.
20752×
    pub fn lock_path(&self, path: &str) -> Result<()> {
20762×
        let attrs = self.disk_attributes();
20772×
        if !attrs.lookup(path).lockable {
20781×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
20791×
        }
20801×
        fs::create_dir_all(self.locks_dir())?;
20811×
        write_atomic(
20821×
            &self.locks_dir().join(path.replace('/', "%2F")),
20831×
            std::process::id().to_string().as_bytes(),
20840×
        )?;
20851×
        set_readonly(&self.root.join(path), false)?;
20861×
        Ok(())
20872×
    }
2088
2089
    /// Release the local lock and make the file read-only again.
20901×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
20911×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
20921×
        if self.root.join(path).exists() {
20931×
            set_readonly(&self.root.join(path), true)?;
20940×
        }
20951×
        Ok(())
20961×
    }
2097
2098
    /// Whether a repository path is inside the sparse filter (spec §17).
209925352×
    pub fn in_scope(&self, path: &str) -> bool {
210025352×
        self.config.sparse_paths.is_empty()
210182×
            || self
210282×
                .config
210382×
                .sparse_paths
210482×
                .iter()
210599×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
210625352×
    }
2107
21081×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
21091×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
21101×
    }
2111
2112
    /// Walk the working copy; with a manifest, a file whose size and mtime
2113
    /// match it is not read: an opaque file yields its known blob, and a
2114
    /// text file whose recorded graph key equals its base graph's key in
2115
    /// `keys` (path → key) is marked unchanged; other text files are read
2116
    /// but keep their known hash. Files modified within two seconds of the
2117
    /// manifest are never trusted (a racy stat).
2118
    ///
2119
    /// `.oxyattributes` files are always read, since their content is
2120
    /// needed; and when any of them is not known unchanged (added, removed,
2121
    /// edited, or changed in the base), no text file is taken as unchanged,
2122
    /// because attributes decide how a file compares with the base.
2123
    ///
2124
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2125
    /// (the base state's files) that exists on disk is included even when
2126
    /// an ignore rule matches it, as in Git.
21271611×
    fn walk_working_copy_with(
21281611×
        &self,
21291611×
        cache: Option<&prompt::Manifest>,
21301611×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
21311611×
        keys: Option<&KeyOf>,
21321611×
    ) -> Result<BTreeMap<String, FsEntry>> {
2133
        let mut out: BTreeMap<String, FsEntry>;
21341611×
        let sparse = &self.config.sparse_paths;
21359703×
        let in_scope = |p: &str| {
21369703×
            sparse.is_empty()
21377×
                || sparse
21387×
                    .iter()
21397×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
21409703×
        };
21411611×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2142
        let walk::Listing {
21431611×
            files,
21441611×
            symlinks,
21451611×
            nested,
21461611×
            dirs,
21471611×
        } = match self.listing_cache.take() {
2148206×
            Some(l) => l,
2149
            // Ignore rules apply to untracked paths only, so the base's
2150
            // files are not matched against them (an added file is: a rule
2151
            // written after it was snapshotted leaves it out again).
21529715×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2153
        };
2154
        // A new file larger than the limit is left out and named, not taken
2155
        // in unseen (oxygen#98): a build's output or a downloaded image
2156
        // would otherwise be stored by the next status, kept by the
2157
        // operation log. Files tracked, or already in the working copy, stay.
21581611×
        let limit = self.config.max_new_file;
21591611×
        let mut skipped = Vec::new();
21601611×
        let files: Vec<_> = files
21611611×
            .into_iter()
216212744×
            .filter(|(rel, _, meta)| {
216312744×
                let new = !tracked.contains_key(rel)
21643227×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
216512744×
                if limit > 0 && new && meta.size > limit {
21663×
                    skipped.push((rel.clone(), meta.size));
21673×
                    return false;
216812741×
                }
216912741×
                true
217012744×
            })
21711611×
            .collect();
21721611×
        *self.skipped_large.borrow_mut() = skipped;
21731611×
        let keys = keys.filter(|k| {
217412728×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
21751607×
            let attrs_unchanged =
21761607×
                files
21771607×
                    .iter()
217812691×
                    .filter(|(r, _, _)| is_attributes(r))
21791607×
                    .all(|(rel, _, meta)| {
218018×
                        stat_cached(rel, meta, cache)
218118×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
218218×
                    });
21831607×
            let none_removed = tracked
21841607×
                .keys()
21859626×
                .filter(|r| is_attributes(r))
21861607×
                .all(|r| on_disk.contains(r.as_str()));
21871607×
            attrs_unchanged && none_removed
21881607×
        });
21891611×
        *self.walked_dirs.borrow_mut() =
21901611×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
21911611×
        drop(walk_phase);
21921611×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2193
        // Reading files is most of a walk's cost; do it in parallel.
2194
        {
2195
            use rayon::prelude::*;
21961611×
            let mut read: Vec<(String, FsEntry)> = files
21971611×
                .par_iter()
219812741×
                .map(|(rel, path, meta)| {
2199
                    // A key is worked out only for a file the manifest
2200
                    // knows with the same stat and a key of its own.
220112741×
                    let key = keys
220212741×
                        .filter(|_| !is_attributes(rel))
220312741×
                        .filter(|_| {
220412673×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
220512673×
                        })
220612741×
                        .and_then(|k| k(rel));
220712741×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
220812741×
                })
22091611×
                .collect::<Result<Vec<_>>>()?;
221012739×
            for (rel, e) in read.iter_mut() {
2211
                // A cached blob the store lost (gc, a partial clone): read the file after all.
221212739×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
22130×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
22140×
                    e.blob = None;
221512739×
                }
2216
            }
2217
            // The listing is in path order, so the map is built without
2218
            // searching.
22191610×
            out = read.into_iter().collect();
22201610×
            for (rel, target) in symlinks {
22212×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
22222×
            }
2223
        }
22241610×
        drop(_read_phase);
22251610×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2226
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2227
        // already tracked as subrepo nodes, they contribute their pin;
2228
        // unregistered ones are left alone.
22291610×
        let modules = self.modules_on_disk();
2230
        // A subrepo at the state its recorded pin names is unmodified,
2231
        // whatever bookmark it sits on (#147): the recorded pin stands.
22321610×
        let subrepo_entry = |rel: &str, pin: crate::subrepo::Pin| -> FsEntry {
223353×
            if let Some((NodeKind::Subrepo, Some(b))) = tracked.get(rel) {
223436×
                let recorded = self
223536×
                    .read_blob(b)
223636×
                    .ok()
223736×
                    .and_then(|x| crate::subrepo::Pin::decode(&x).ok());
223836×
                if recorded.is_some_and(|r| r.same_state(&pin)) {
223923×
                    return FsEntry {
224023×
                        blob: Some(*b),
224123×
                        ..FsEntry::new(NodeKind::Subrepo, false, vec![])
224223×
                    };
224313×
                }
224417×
            }
224530×
            FsEntry::new(NodeKind::Subrepo, false, pin.encode())
224653×
        };
2247
        // A removal's marker is spent once the removal is recorded (no
2248
        // subrepo node is tracked there) or the path is registered again:
2249
        // dropped before it is read, or the change registering it again
2250
        // would leave it out (oxygen#152).
22511610×
        let mut removed = self.removed_subrepos();
22521610×
        removed.retain(|rel| {
22535×
            let spent = tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
22543×
                || modules.entries.contains_key(rel);
22555×
            if spent {
22562×
                self.clear_removed_subrepo(rel);
22573×
            }
22585×
            !spent
22595×
        });
22601610×
        let mut untracked_nested = Vec::new();
22611610×
        for dir in nested {
226258×
            let rel = self.rel_path(&dir);
226358×
            if !self.in_scope(&rel) || removed.contains(&rel) {
22643×
                continue;
226555×
            }
226655×
            let registered = modules.entries.get(&rel);
226755×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2268
            {
22692×
                untracked_nested.push(rel);
22702×
                continue;
227153×
            }
227253×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
227353×
            let entry = subrepo_entry(&rel, pin);
227453×
            out.insert(rel, entry);
2275
        }
22761610×
        untracked_nested.sort();
22771610×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2278
        // Tracked paths the ignore rules hid.
22791610×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
228081×
            if !self.in_scope(rel) {
228110×
                continue;
228271×
            }
228371×
            let path = self.root.join(rel);
228471×
            if *kind == NodeKind::Subrepo {
22854×
                if removed.contains(rel) {
22863×
                    continue;
22871×
                }
22881×
                let present =
22891×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
22901×
                if present {
22910×
                    let pin = subrepos::read_pin(
22920×
                        &path,
22930×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
22940×
                    )?;
22950×
                    out.insert(rel.clone(), subrepo_entry(rel, pin));
22961×
                } else if let Some(b) = blob {
22971×
                    // Not cloned (or emptied): the pin stays as recorded, as a
22981×
                    // Git gitlink does when its directory is absent.
22991×
                    out.insert(
23001×
                        rel.clone(),
23011×
                        FsEntry {
23021×
                            blob: Some(*b),
23031×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
23041×
                        },
23051×
                    );
23061×
                }
23071×
                continue;
230867×
            }
230967×
            let Ok(meta) = fs::symlink_metadata(&path) else {
231067×
                continue;
2311
            };
23120×
            let ft = meta.file_type();
23130×
            if ft.is_symlink() {
23140×
                let target = fs::read_link(&path)?;
23150×
                out.insert(
23160×
                    rel.clone(),
23170×
                    FsEntry::new(
23180×
                        NodeKind::Symlink,
2319
                        false,
23200×
                        target.to_string_lossy().as_bytes().to_vec(),
2321
                    ),
2322
                );
23230×
            } else if ft.is_file() {
23240×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
23250×
                out.insert(rel.clone(), e);
23260×
            }
2327
        }
23281610×
        Ok(out)
23291611×
    }
2330
2331
    /// The entry for one regular file, read or served from the stat cache.
23320×
    fn file_entry(
23330×
        &self,
23340×
        rel: &str,
23350×
        path: &Path,
23360×
        meta: &walk::Stat,
23370×
        cache: Option<&prompt::Manifest>,
23380×
    ) -> Result<FsEntry> {
23390×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
23400×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
23410×
            e.content = std::sync::Arc::new(fs::read(path)?);
23420×
            e.blob = None;
23430×
        }
23440×
        Ok(e)
23450×
    }
2346
2347
    /// The non-directory paths of a snapshot with their kinds, for the
2348
    /// walker's `tracked` set.
23493×
    pub(crate) fn tracked_kinds(
23503×
        snapshot: &Snapshot,
23513×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
23523×
        snapshot
23533×
            .files
23543×
            .iter()
235512×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
23568×
            .map(|(p, f)| {
23578×
                let blob = match &f.content {
23584×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
23594×
                    _ => None,
2360
                };
23618×
                (p.clone(), (f.kind, blob))
23628×
            })
23633×
            .collect()
23643×
    }
2365
2366
    /// A path under the root as a `/`-separated relative string.
2367124×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
2368124×
        path.strip_prefix(&self.root)
2369124×
            .unwrap_or(path)
2370124×
            .components()
2371226×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
2372124×
            .collect::<Vec<_>>()
2373124×
            .join("/")
2374124×
    }
2375
}
2376
2377
impl Repo {
2378
    /// Changes reachable from the bookmark and the working copy, newest first.
2379104×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
2380104×
        let heads = self.bookmark_heads()?;
2381104×
        if self.bare {
23821×
            return self.log_state(&heads);
2383103×
        }
2384103×
        let (wc_hash, wc) = self.working_copy()?;
2385103×
        let mut all = heads.clone();
2386103×
        all.push(wc_hash);
2387103×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
2388103×
        let mut entries: Vec<LogEntry> = Vec::new();
2389
        // A shallow clone knows changes beyond its boundary from a
2390
        // checkpoint's metadata only: its log comes from the state.
2391103×
        let metas = if self.is_shallow() {
23922×
            self.load_state_history(&all)?
23932×
                .changes()
239412×
                .map(|(h, m)| (*h, m.clone()))
23952×
                .collect()
2396
        } else {
2397
            // The working copy's change is in hand, and is never in the
2398
            // state index: its metadata is not looked up again.
2399101×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
2400101×
            below.extend(wc.deps.iter().copied());
2401101×
            let _t = crate::timing::phase("log: metadata");
2402101×
            let mut metas = self.metas_of(&below)?;
2403350×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
2404101×
                // First, where the log puts it, so the order may hold.
2405101×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
2406101×
            }
2407101×
            metas
2408
        };
2409103×
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2410463×
            hash: h,
2411463×
            change: meta,
2412463×
            is_working_copy: h == wc_hash,
2413463×
            is_head: head_set.contains(&h),
2414463×
        }));
2415103×
        let _sorting = crate::timing::phase("log: sort");
2416
        // The hash makes the order total, so an unstable sort gives the same.
2417
        // From the state index the order already holds (oxygen#94).
2418804×
        let order = |a: &LogEntry, b: &LogEntry| {
2419804×
            b.is_working_copy
2420804×
                .cmp(&a.is_working_copy)
2421804×
                .then(crate::state::log_order(
2422804×
                    (&a.hash, &a.change.hlc),
2423804×
                    (&b.hash, &b.change.hlc),
2424
                ))
2425804×
        };
2426218×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
242753×
            entries.sort_unstable_by(order);
242853×
        }
2429103×
        Ok(entries)
2430104×
    }
2431
2432
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2433
    /// count, for paginated views.
24340×
    pub fn log_window(
24350×
        &self,
24360×
        heads: &[ChangeHash],
24370×
        offset: usize,
24380×
        limit: usize,
24390×
    ) -> Result<(Vec<LogEntry>, usize)> {
24400×
        let all = self.log_state(heads)?;
24410×
        let total = all.len();
24420×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
24430×
    }
2444
2445
    /// The log of the state with these heads, newest first, with no working
2446
    /// copy involved (for hosted repositories and any explicit state).
244710×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2448
        // The log needs change metadata only: neither graphs nor the tree.
244910×
        if self.is_shallow() {
24500×
            return Ok(self.log_of(&self.load_state_history(heads)?));
245110×
        }
245210×
        let metas = self.metas_of(heads)?;
245310×
        let depended: BTreeSet<ChangeHash> = metas
245410×
            .iter()
245530×
            .flat_map(|(_, m)| m.deps.iter().copied())
245610×
            .collect();
245710×
        let mut entries: Vec<LogEntry> = metas
245810×
            .into_iter()
245910×
            .map(|(h, meta)| LogEntry {
246030×
                hash: h,
246130×
                is_head: !depended.contains(&h),
246230×
                change: meta,
2463
                is_working_copy: false,
246430×
            })
246510×
            .collect();
246633×
        let order = |a: &LogEntry, b: &LogEntry| {
246733×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
246833×
        };
246911×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
24704×
            entries.sort_unstable_by(order);
24716×
        }
247210×
        Ok(entries)
247310×
    }
2474
2475
    /// Every change of the state with these heads and its metadata, read
2476
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2477
    /// a shallow clone's boundary is left out.
2478185×
    pub fn metas_of(
2479185×
        &self,
2480185×
        heads: &[ChangeHash],
2481185×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2482185×
        let boundary = self.boundary();
2483
        // The state index holds the metadata of its heads' closure: a
2484
        // change found there is not read from the store (a change object
2485
        // can be as large as the tree it adds).
2486185×
        let read = self.read_state_index_changes();
2487
        // Every one of `heads` in the index, and every head of the index
2488
        // among them: their closure is the index's changes, all of them
2489
        // (it is closed), and no walk is needed to find it.
2490185×
        if let Some((index_heads, all)) = &read {
2491168×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2492168×
            let in_index = || {
2493168×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2494168×
                    index_heads.iter().collect();
2495
                // Usually the heads asked are the index's: no set of all.
2496168×
                heads.iter().all(|h| index_heads.contains(h)) || {
2497168×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2498168×
                        all.iter().map(|(h, _)| h).collect();
2499168×
                    heads.iter().all(|h| all.contains(h))
2500
                }
2501168×
            };
2502168×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
25030×
                let (_, all) = read.expect("matched above");
2504
                #[cfg(test)]
2505
                {
2506
                    // The walk the shortcut saves finds the same changes.
25070×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
25080×
                    let mut stack = heads.to_vec();
25090×
                    while let Some(h) = stack.pop() {
25100×
                        if seen.insert(h) {
25110×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
25120×
                        }
2513
                    }
25140×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2515
                }
25160×
                return Ok(all);
2517168×
            }
251817×
        }
2519185×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2520185×
            read.map(|(_, all)| all.into_iter().collect());
2521185×
        let _walk = crate::timing::phase("metadata: walk");
2522185×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2523185×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2524185×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2525185×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
25261333×
        while let Some(h) = stack.pop() {
25271148×
            if !seen.insert(h) {
2528484×
                continue;
2529664×
            }
2530
            // Taken out of the index's map, each once: not copied.
2531664×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2532
                #[cfg(test)]
25330×
                assert_eq!(
2534
                    meta,
25350×
                    self.store.get_change_meta(&h)?,
2536
                    "the state index holds a change's metadata"
2537
                );
25380×
                stack.extend(meta.deps.iter().copied());
25390×
                out.push((h, meta));
25400×
                continue;
2541664×
            }
2542664×
            let started = std::time::Instant::now();
2543664×
            let meta = match self.store.get_change_meta(&h) {
2544664×
                Ok(m) => m,
25450×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
25460×
                Err(e) => return Err(e.into()),
2547
            };
2548664×
            stored += 1;
2549664×
            from_store += started.elapsed();
2550664×
            stack.extend(meta.deps.iter().copied());
2551664×
            out.push((h, meta));
2552
        }
2553185×
        if stored > 0 && crate::timing::enabled() {
25540×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2555185×
        }
2556185×
        Ok(out)
2557185×
    }
2558
2559
    /// The log of a state already loaded, newest first.
2560
    /// The history of lines `first..=last` (1-based) of `path` in the
2561
    /// state `heads` make (spec §27): every change that inserted or
2562
    /// deleted one of their atoms, or an atom deleted from between them,
2563
    /// newest first. Exact, as atoms keep their identity across edits.
25646×
    pub fn line_history(
25656×
        &self,
25666×
        heads: &[ChangeHash],
25676×
        path: &str,
25686×
        first: usize,
25696×
        last: usize,
25706×
    ) -> Result<Vec<LogEntry>> {
25716×
        if first == 0 || last < first {
25721×
            return fail(format!(
2573
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2574
            ));
25755×
        }
25765×
        let mut state = self.load_state_history(heads)?;
25775×
        let Some(node) = self
25785×
            .tree_view(&mut state)?
2579
            .entries
25805×
            .get(path)
25815×
            .map(|e| e.node)
2582
        else {
25831×
            return fail(format!("{path} is not in that state"));
2584
        };
25854×
        self.load_graphs_of(&mut state, &[node])?;
25864×
        let live = state.live_lines(&node);
25874×
        if last > live.len() {
25881×
            return fail(format!(
2589
                "{path} has {} lines; asked for {first},{last}",
25901×
                live.len()
2591
            ));
25923×
        }
25933×
        let Some(g) = state.file(&node) else {
25940×
            return fail(format!("{path} is not a text file"));
2595
        };
25963×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
25973×
        let touched = g.touching(&atoms);
25983×
        Ok(self
25993×
            .log_of(&state)
26003×
            .into_iter()
260113×
            .filter(|e| touched.contains(&e.hash))
26023×
            .collect())
26036×
    }
2604
26058×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
26068×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
26078×
        let mut entries: Vec<LogEntry> = state
26088×
            .changes()
26098×
            .map(|(h, meta)| LogEntry {
261031×
                hash: *h,
261131×
                change: meta.clone(),
2612
                is_working_copy: false,
261331×
                is_head: head_set.contains(h),
261431×
            })
26158×
            .collect();
261638×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
26178×
        entries
26188×
    }
2619
2620
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2621
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2622
    /// (`resolve_change`).
262367×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
262467×
        let view = self.view()?;
262567×
        if let Some(st) = view.bookmarks.get(spec) {
262639×
            return Ok(self.store.get_state(st)?.heads);
262728×
        }
262828×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
26292×
            return Ok(self.store.get_state(&st)?.heads);
263026×
        }
263126×
        if let Some(heads) = self.tag_heads(spec)? {
26322×
            return Ok(heads);
263324×
        }
263424×
        Ok(vec![self.resolve_change(spec)?])
263567×
    }
2636
2637
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2638
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
263937×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
264037×
        if spec == "@" {
26410×
            return Ok(self.working_copy()?.0);
264237×
        }
264337×
        let view = self.view()?;
264437×
        let named = match view.bookmarks.get(spec) {
26451×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
264636×
            None => match remote_bookmark(&view, spec) {
26471×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
264835×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2649
            },
2650
        };
265137×
        if let Some((kind, heads)) = named {
26523×
            return match heads.len() {
26533×
                1 => Ok(heads[0]),
26540×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2655
            };
265634×
        }
265734×
        if spec.is_empty() || spec == "#" {
26580×
            return fail("empty change specifier");
265934×
        }
266034×
        let entries = self.log()?;
2661
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2662
        // cannot be a ChangeId, which has 32 (oxygen#103).
266334×
        let full_hash =
2664128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
266534×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
266628×
            entries
266728×
                .iter()
2668112×
                .filter(|e| e.hash.starts_with_hex(hp))
266928×
                .collect()
2670
        } else {
26716×
            entries
26726×
                .iter()
267321×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
26746×
                .collect()
2675
        };
267634×
        match matches.len() {
267729×
            1 => Ok(matches[0].hash),
26785×
            0 => match self.resolve_in_remotes(spec)? {
26791×
                Some(h) => Ok(h),
26804×
                None => fail(format!("no change matches {spec:?}")),
2681
            },
2682
            _ => {
26830×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
26840×
                if ids.len() == 1 {
26850×
                    fail(format!(
2686
                        "change {spec} is divergent: {} variants",
26870×
                        matches.len()
2688
                    ))
2689
                } else {
26900×
                    fail(format!("{spec:?} is ambiguous"))
2691
                }
2692
            }
2693
        }
269437×
    }
2695
2696
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2697
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2698
    /// `None` when none matches, or more than one.
26995×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
27005×
        let view = self.view()?;
27015×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
27025×
        for bookmarks in view.remotes.values() {
27033×
            for st in bookmarks.values() {
27043×
                let heads = self.store.get_state(st)?.heads;
27057×
                for e in self.log_state(&heads)? {
27067×
                    let hit = match spec.strip_prefix('#') {
27072×
                        Some(hp) => e.hash.starts_with_hex(hp),
27085×
                        None => e.change.change_id.starts_with_hex(spec),
2709
                    };
27107×
                    if hit {
27111×
                        found.insert(e.hash);
27126×
                    }
2713
                }
2714
            }
2715
        }
27165×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
27175×
    }
2718
2719
    /// Where a change is when no local bookmark or the working copy holds
2720
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2721
    /// it is held locally, or nowhere.
27224×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
27238×
        if self.log()?.iter().any(|e| e.hash == *hash) {
27243×
            return Ok(None);
27251×
        }
27261×
        let view = self.view()?;
27271×
        for (remote, bookmarks) in &view.remotes {
27281×
            for (name, st) in bookmarks {
27291×
                let heads = self.store.get_state(st)?.heads;
27301×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
27311×
                    return Ok(Some(format!("{remote}/{name}")));
27320×
                }
2733
            }
2734
        }
27350×
        Ok(None)
27364×
    }
2737
2738
    /// Human-readable description of what a change does, with line content.
27394×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
27404×
        let change = self.store.get_change(hash)?;
27414×
        let (base, base_snapshot) = self.change_base(&change)?;
27424×
        Ok(render_change(&change, &base, &base_snapshot))
27434×
    }
2744
2745
    /// The base state of `change` (its dependencies) and its rendering, as
2746
    /// much as showing the change needs: the whole tree, and the graphs and
2747
    /// contents of the files the change edits. Other text files are left
2748
    /// unrendered ([`Snapshot::unrendered`]).
27498×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
27508×
        let base = self.load_state_history(&change.deps)?;
27518×
        self.render_base_for(change, base)
27528×
    }
2753
2754
    /// The base for showing `change` alone: the graphs of the files it
2755
    /// edits built, and the base's tree with no file rendered, which is
2756
    /// all [`render_change`](snapshot::render_change) and
2757
    /// [`diff_files_of`](snapshot::diff_files_of) read.
27583×
    pub(crate) fn tree_base_for(
27593×
        &self,
27603×
        change: &Change,
27613×
        mut base: State,
27623×
    ) -> Result<(State, Snapshot)> {
27633×
        let _t = crate::timing::phase("diff: the base's tree");
27643×
        let edited: std::collections::HashSet<NodeId> =
27658×
            change.edits.iter().map(|e| e.node()).collect();
27663×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
27673×
        self.load_graphs_of(&mut base, &nodes)?;
27683×
        let snapshot = Snapshot {
27693×
            tree: self.tree_view(&mut base)?,
27703×
            files: BTreeMap::new(),
27713×
            unrendered: BTreeSet::new(),
2772
        };
27733×
        Ok((base, snapshot))
27743×
    }
2775
2776
    /// [`Repo::change_base`] with the base already loaded (the working
2777
    /// copy's comes from the state index).
2778235×
    pub(crate) fn render_base_for(
2779235×
        &self,
2780235×
        change: &Change,
2781235×
        mut base: State,
2782235×
    ) -> Result<(State, Snapshot)> {
2783235×
        let _t = crate::timing::phase("diff: render the base");
2784235×
        let edited: std::collections::HashSet<NodeId> =
2785424×
            change.edits.iter().map(|e| e.node()).collect();
2786235×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2787235×
        self.load_graphs_of(&mut base, &nodes)?;
2788235×
        self.tree_view(&mut base)?;
2789235×
        let snapshot = {
2790235×
            let _t = crate::timing::phase("diff:   of which materialize");
2791235×
            base.materialize_nodes(&edited)
2792
        };
2793235×
        Ok((base, snapshot))
2794235×
    }
2795
}
2796
27970×
fn remove_any(path: &Path) -> std::io::Result<()> {
27980×
    let m = fs::symlink_metadata(path)?;
27990×
    if m.is_dir() {
28000×
        fs::remove_dir_all(path)
2801
    } else {
28020×
        fs::remove_file(path)
2803
    }
28040×
}
2805
28065×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
28075×
    let mut perms = fs::metadata(path)?.permissions();
28085×
    perms.set_readonly(readonly);
28095×
    fs::set_permissions(path, perms)
28105×
}
2811
2812
#[cfg(unix)]
28135942×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2814
    use std::os::unix::fs::PermissionsExt;
28155942×
    let mut perms = fs::metadata(path)?.permissions();
28165942×
    let mode = perms.mode();
28175942×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
28185942×
    if want != mode {
28196×
        perms.set_mode(want);
28206×
        fs::set_permissions(path, perms)?;
28215936×
    }
28225942×
    Ok(())
28235942×
}
2824
#[cfg(not(unix))]
2825
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2826
    Ok(())
2827
}
2828
2829
#[cfg(unix)]
283017166×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2831
    use std::os::unix::fs::PermissionsExt;
283217166×
    m.permissions().mode() & 0o111 != 0
283317166×
}
2834
#[cfg(not(unix))]
2835
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2836
    false
2837
}
2838
283913568×
fn op_ref(k: OpKey) -> OpRef {
284013568×
    OpRef {
284113568×
        change: k.0,
284213568×
        index: k.1,
284313568×
    }
284413568×
}
2845
28466252×
fn split_path(path: &str) -> (&str, &str) {
28476252×
    match path.rfind('/') {
28485067×
        Some(i) => (&path[..i], &path[i + 1..]),
28491185×
        None => ("", path),
2850
    }
28516252×
}
2852
2853
/// Whether `rel` is an attributes file (spec §7.6).
285470113×
fn is_attributes(rel: &str) -> bool {
285570113×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
285670113×
}
2857
2858
/// The manifest entry for `rel` when its size and mtime match it outside
2859
/// the racy window.
286025432×
fn stat_cached<'m>(
286125432×
    rel: &str,
286225432×
    meta: &walk::Stat,
286325432×
    cache: Option<&'m prompt::Manifest>,
286425432×
) -> Option<&'m prompt::ManifestEntry> {
286525432×
    let m = cache?;
286620391×
    let e = m.entries.get(rel)?;
286718944×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
286818944×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
286925432×
}
2870
2871
/// Read one working-copy file, or serve it from the stat cache (spec
2872
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2873
/// an opaque file is not read at all (its stored blob stands in), and a
2874
/// text file the manifest recorded equal to a base graph whose key is
2875
/// `key`, the key the base has now, is not read either: equal keys mean
2876
/// equal renderings, so it still equals the base. Touches no repository
2877
/// state, so the walk runs it in parallel; the caller checks that a cached
2878
/// blob is still in the store.
287912741×
fn read_file_entry(
288012741×
    rel: &str,
288112741×
    path: &Path,
288212741×
    meta: &walk::Stat,
288312741×
    cache: Option<&prompt::Manifest>,
288412741×
    key: Option<[u8; 32]>,
288512741×
) -> Result<FsEntry> {
288612741×
    let exec = meta.exec;
288712741×
    let stat = Some((meta.size, meta.mtime_ns));
288812741×
    let mut e = match stat_cached(rel, meta, cache) {
28894247×
        Some(e) if e.blob.is_some() => FsEntry {
28901×
            blob: e.blob,
28911×
            content_hash: Some(e.hash),
28921×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28931×
        },
28944246×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
28954241×
            content_hash: Some(e.hash),
28964241×
            unchanged: true,
28974241×
            graph_key: e.graph,
28984241×
            ..FsEntry::new(NodeKind::File, exec, vec![])
28994241×
        },
29005×
        Some(e) => FsEntry {
29015×
            content_hash: Some(e.hash),
29025×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2903
        },
29048494×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2905
    };
2906
    // The stat the manifest records: taken before the read, so a file that
2907
    // changes meanwhile is read again next time.
290812740×
    e.stat = stat;
290912740×
    Ok(e)
291012741×
}
2911
2912
/// Two maps side by side in key order: each key of either, with its value
2913
/// in each. Linear, with no lookups, for maps of a whole tree.
29143093×
pub(crate) fn join<'a, A, B>(
29153093×
    a: &'a BTreeMap<String, A>,
29163093×
    b: &'a BTreeMap<String, B>,
29173093×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
29183093×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
291936876×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
29203093×
        (None, None) => None,
29213012×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
29225990×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
292324781×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2924356×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2925328×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2926
            std::cmp::Ordering::Equal => {
292724097×
                let (k, va) = a.next()?;
292824097×
                let (_, vb) = b.next()?;
292924097×
                Some((k, Some(va), Some(vb)))
2930
            }
2931
        },
293236876×
    })
29333093×
}
2934
2935
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2936
/// lookups.
29371611×
pub(crate) fn missing_from<'a, A, B>(
29381611×
    a: &'a BTreeMap<String, A>,
29391611×
    b: &BTreeMap<String, B>,
29401611×
) -> Vec<(&'a String, &'a A)> {
29411611×
    let mut keys = b.keys().peekable();
29421611×
    a.iter()
29439636×
        .filter(|(k, _)| {
294418380×
            while keys.next_if(|kb| *kb < *k).is_some() {}
29459636×
            keys.peek() != Some(k)
29469636×
        })
29471611×
        .collect()
29481611×
}