OXYGENHUB

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

1830 of 2062 lines run, 429 of 690 functions · run #313 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.
752432×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762432×
    let Some(url) = &config.storage_url else {
772427×
        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×
    )?)
1002432×
}
101
102163×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103163×
    Err(RepoError::Msg(s.into()))
104163×
}
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 ops;
120
mod policy;
121
mod prompt;
122
mod receipts;
123
mod revset;
124
mod snapshot;
125
pub mod strata;
126
mod subrepos;
127
mod sync;
128
mod tags;
129
#[cfg(test)]
130
mod tests;
131
mod touched;
132
mod walk;
133
mod workspace;
134
135
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
136
pub use checkout::CheckoutReport;
137
pub use config::{parse_size, read_config_file, Config};
138
pub use doctor::{Check, DoctorReport, Health};
139
pub use fsck::{FsckReport, Problem, Severity};
140
pub use gc::GcReport;
141
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
142
pub use hooks::{json_array, json_str, HookOutcome};
143
pub use hosted::FileEdit;
144
pub use identity::{Rotation, SignatureStatus};
145
pub use inspect::{BisectStep, BlameLine, Description};
146
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
147
pub use policy::PolicyUpdate;
148
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
149
pub use receipts::ReceiptInfo;
150
pub use revset::{Revset, REVSET_BUDGET};
151
pub use snapshot::{
152
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
153
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
154
    Selection, SnapshotResult,
155
};
156
pub use subrepos::{SubrepoInfo, SubrepoSync};
157
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT};
158
pub use tags::TagInfo;
159
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
160
161
/// The file name under which per-bookmark or per-tag data is kept: `/`
162
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
163
/// than a directory that would clash with it.
1644025×
pub(crate) fn name_file(name: &str) -> String {
1654025×
    name.replace('%', "%25").replace('/', "%2F")
1664025×
}
167
168
/// The name a [`name_file`] file name stands for.
16943×
pub(crate) fn file_name_to_name(file: &str) -> String {
17043×
    file.replace("%2F", "/").replace("%25", "%")
17143×
}
172
1737007×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1747007×
    Ok(crate::durable::write_atomic(path, data)?)
1757007×
}
176
177
/// Replace a cache file: whole or not at all, but without waiting for the
178
/// disk. A cache checks its own bytes when read, so one a crash leaves
179
/// short or stale is rebuilt rather than trusted.
180
/// How many changes a state index may fall behind its working copy before
181
/// it is written again; until then each load replays them.
182
const INDEX_REPLAY_LIMIT: usize = 16;
183
/// The changes whose encodings are kept for building graphs: a batch of
184
/// files often takes inline text from a few changes in turn.
185
const CHANGE_CACHE_COUNT: usize = 4;
186
const CHANGE_CACHE_BYTES: usize = 512 << 20;
187
/// How many state indexes a workspace keeps.
188
const STATE_INDEXES_KEPT: usize = 2;
189
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
190
1912770×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1922770×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1932770×
    fs::write(&tmp, data)?;
1942770×
    fs::rename(&tmp, path)?;
1952770×
    Ok(())
1962770×
}
197
198
pub struct LogEntry {
199
    pub hash: ChangeHash,
200
    /// Metadata from the state; the full change may be absent in a shallow repository.
201
    pub change: crate::state::ChangeMeta,
202
    pub is_working_copy: bool,
203
    pub is_head: bool,
204
}
205
206
/// A text file's base graph key, by path, as a walk asks for it.
207
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
208
209
/// A file as found on disk or in an imported tree.
210
#[derive(Clone)]
211
pub(crate) struct FsEntry {
212
    pub kind: NodeKind,
213
    pub exec: bool,
214
    /// File content, or a symlink's target. Empty when `blob` is set.
215
    /// Shared, so a new file's insert holds it without a copy.
216
    pub content: std::sync::Arc<Vec<u8>>,
217
    /// The stored blob of an opaque file whose size and mtime are unchanged
218
    /// since the last manifest (spec §12.3 stat cache); the content was not
219
    /// read.
220
    pub blob: Option<ObjectRef>,
221
    /// BLAKE3 of the content, carried over from the manifest when the stat
222
    /// is unchanged, so the manifest can be rewritten without rehashing.
223
    pub content_hash: Option<[u8; 32]>,
224
    /// A text file known equal to the base's rendering without reading it:
225
    /// its stat matches the manifest and the manifest recorded it equal to
226
    /// a base file graph with the same key (spec §12.3). `content` is empty.
227
    pub unchanged: bool,
228
    /// The base graph key this file equals, for the next manifest.
229
    pub graph_key: Option<[u8; 32]>,
230
    /// Size and mtime already known to be current (a checkout leaving the
231
    /// file as it was), so the manifest need not stat it again.
232
    pub stat: Option<(u64, u128)>,
233
}
234
235
impl FsEntry {
23622567×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
23722567×
        FsEntry {
23822567×
            kind,
23922567×
            exec,
24022567×
            content: std::sync::Arc::new(content),
24122567×
            blob: None,
24222567×
            content_hash: None,
24322567×
            unchanged: false,
24422567×
            graph_key: None,
24522567×
            stat: None,
24622567×
        }
24722567×
    }
248
}
249
250
pub struct Repo {
251
    /// The key a host accepts certified updates with (spec §14.7): when
252
    /// set, accepting a reference update signed by a short-lived key also
253
    /// records the host's acceptance and its time.
254
    pub(crate) acceptor: Option<std::sync::Arc<(Identity, crate::identity::SecretKey)>>,
255
    /// Oxygen-pinned subrepos skipped by the running Git export.
256
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
257
    /// The manifest as last read, with the file identity it was read from,
258
    /// so one command parses it once (see `read_manifest`).
259
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
260
    /// A listing of the working copy left by a failed clean check, for the
261
    /// snapshot that follows it to reuse; taken by the next walk and
262
    /// dropped whenever the manifest is written.
263
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
264
    /// The nested repositories the last walk left out, being neither
265
    /// registered nor tracked subrepos (oxygen#43).
266
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
267
    /// New untracked files the last walk left out for their size, with
268
    /// their sizes (oxygen#98).
269
    pub(crate) skipped_large: std::cell::RefCell<Vec<(String, u64)>>,
270
    root: PathBuf,
271
    oxy: PathBuf,
272
    store: Store,
273
    workspace: WorkspaceId,
274
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
275
    bare: bool,
276
    keys_dir: PathBuf,
277
    user_config: PathBuf,
278
    pub config: Config,
279
    /// What the working copy's file system can represent (spec §7.7).
280
    platform: crate::portable::Platform,
281
    /// The encodings of the changes last read for their inline inserts,
282
    /// oldest first.
283
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
284
    /// `--at-op`: read the repository as it was after this operation;
285
    /// recording an operation is refused.
286
    at_op: Option<ObjectRef>,
287
    /// The directories (with their times) and nested repositories of the
288
    /// last walk, for the manifest written from it.
289
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
290
    /// The directories a manifest check listed, for its restamp only.
291
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
292
}
293
294
/// A walk's directories with their times, and its nested repositories.
295
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
296
297
/// Marker file of a bare repository, inside `.oxy/`.
298
const BARE_MARKER: &str = "bare";
299
/// Marker of a hosted repository that has no id yet: the first push binds
300
/// it to the pusher's id (spec §16.1).
301
const UNBOUND_MARKER: &str = "unbound";
302
303
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
304
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
3057534×
pub fn default_home() -> PathBuf {
3067534×
    if let Ok(h) = std::env::var("OXY_HOME") {
3077528×
        return PathBuf::from(h);
3086×
    }
3096×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3100×
        return PathBuf::from(x).join("oxy");
3116×
    }
312
    // Windows has no HOME as a rule: the roaming profile's application
313
    // data, as Windows programs keep theirs.
314
    #[cfg(windows)]
315
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
316
        return PathBuf::from(d).join("oxy");
317
    }
3186×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3196×
    PathBuf::from(home).join(".config").join("oxy")
3207534×
}
321
3222433×
pub fn default_keys_dir() -> PathBuf {
3232433×
    default_home().join("keys")
3242433×
}
325
3264864×
pub fn default_user_config() -> PathBuf {
3274864×
    default_home().join("config.toml")
3284864×
}
329
330
/// Where `create_identity` records the author.
331
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
332
pub enum IdentityScope {
333
    /// The user file: every repository of this user signs with it.
334
    User,
335
    /// This repository only.
336
    Repo,
337
}
338
339
impl Repo {
340
    // ------------------------------------------------------------ lifecycle
341
342225×
    pub fn init(root: &Path) -> Result<Repo> {
343225×
        let mut id = [0u8; 16];
344225×
        rand::rngs::OsRng.fill_bytes(&mut id);
345225×
        Self::init_with_id(root, id)
346225×
    }
347
348
    /// Initialize a repository with a given repository ID (clones share the
349
    /// ID of their origin, spec §14.4).
350469×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
351469×
        Self::init_on(root, id, None)
352469×
    }
353
354
    /// A new repository with a fresh id, bare or not, on `storage` or in
355
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
35612×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
35712×
        let mut id = [0u8; 16];
35812×
        rand::rngs::OsRng.fill_bytes(&mut id);
35912×
        if bare {
3600×
            Self::init_bare_on(root, id, storage)
361
        } else {
36212×
            Self::init_on(root, id, storage)
363
        }
36412×
    }
365
366
    /// Initialize a repository whose objects and operation head are kept
367
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
368484×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
369484×
        fs::create_dir_all(root)?;
370484×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
371484×
        let oxy = root.join(OXY_DIR);
372484×
        if oxy.exists() {
3731×
            return fail(format!("{} is already an oxy repository", root.display()));
374483×
        }
375483×
        fs::create_dir_all(oxy.join("ops"))?;
376483×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
377483×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
378483×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
379483×
        if let Some(url) = storage {
3803×
            config.set("storage.url", url)?;
381480×
        }
382483×
        config.save(&oxy.join("config"))?;
383483×
        let workspace = WorkspaceId::random();
384483×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
385483×
        let store = open_objects(&oxy, &config)?;
386482×
        let repo = Repo {
387482×
            acceptor: None,
388482×
            last_change: Default::default(),
389482×
            at_op: None,
390482×
            walked_dirs: Default::default(),
391482×
            listed_dirs: Default::default(),
392482×
            git_export_skipped: Default::default(),
393482×
            manifest_cache: Default::default(),
394482×
            listing_cache: Default::default(),
395482×
            untracked_nested: Default::default(),
396482×
            skipped_large: Default::default(),
397482×
            root,
398482×
            oxy,
399482×
            store,
400482×
            workspace,
401482×
            bare: false,
402482×
            keys_dir: default_keys_dir(),
403482×
            platform: crate::portable::Platform::current(),
404482×
            user_config: default_user_config(),
405482×
            config,
406482×
        };
407482×
        repo.register_workspace(&workspace, &repo.root)?;
408
409482×
        let wc = repo.new_working_copy(vec![], "");
410482×
        let wc_hash = repo.store.put_change(&wc)?;
411482×
        let mut view = View::default();
412482×
        view.bookmarks.insert(
413482×
            repo.config.bookmark.clone(),
414482×
            repo.store.put_state(&StateObject::new(vec![]))?,
415
        );
416482×
        view.workspaces.insert(workspace, wc_hash);
417482×
        repo.record_op(&[], "oxy init", view)?;
418480×
        Ok(repo)
419484×
    }
420
421
    /// Create a bare repository: an object store, operation log and
422
    /// references with no workspace and no working copy, for hosting
423
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4245×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4255×
        let mut id = [0u8; 16];
4265×
        rand::rngs::OsRng.fill_bytes(&mut id);
4275×
        Self::init_bare_with_id(root, id)
4285×
    }
429
43040×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
43140×
        Self::init_bare_on(root, id, None)
43240×
    }
433
434
    /// [`Repo::init_on`] for a bare repository.
43540×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
43640×
        fs::create_dir_all(root)?;
43740×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
43840×
        let oxy = root.join(OXY_DIR);
43940×
        if oxy.exists() {
4400×
            return fail(format!("{} is already an oxy repository", root.display()));
44140×
        }
44240×
        fs::create_dir_all(oxy.join("ops"))?;
44340×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
44440×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
44540×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
44640×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
44740×
        if let Some(url) = storage {
4480×
            config.set("storage.url", url)?;
44940×
        }
45040×
        config.save(&oxy.join("config"))?;
45140×
        let store = open_objects(&oxy, &config)?;
45240×
        let repo = Repo {
45340×
            acceptor: None,
45440×
            last_change: Default::default(),
45540×
            at_op: None,
45640×
            walked_dirs: Default::default(),
45740×
            listed_dirs: Default::default(),
45840×
            git_export_skipped: Default::default(),
45940×
            manifest_cache: Default::default(),
46040×
            listing_cache: Default::default(),
46140×
            untracked_nested: Default::default(),
46240×
            skipped_large: Default::default(),
46340×
            root,
46440×
            oxy,
46540×
            store,
46640×
            workspace: WorkspaceId::ZERO,
46740×
            bare: true,
46840×
            keys_dir: default_keys_dir(),
46940×
            platform: crate::portable::Platform::current(),
47040×
            user_config: default_user_config(),
47140×
            config,
47240×
        };
47340×
        let mut view = View::default();
47440×
        view.bookmarks.insert(
47540×
            repo.config.bookmark.clone(),
47640×
            repo.store.put_state(&StateObject::new(vec![]))?,
477
        );
47840×
        repo.record_op(&[], "oxy init --bare", view)?;
47940×
        Ok(repo)
48040×
    }
481
482
    /// A bare repository with no id yet. Its `id()` is all zero until the
483
    /// first push binds it (`bind_id`), so an existing repository can be
484
    /// pushed to a freshly created hosted one and keep its identity.
48514×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
48614×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
48714×
        fs::remove_file(repo.oxy.join("id"))?;
48814×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
48914×
        Ok(repo)
49014×
    }
491
4923482×
    pub fn is_unbound(&self) -> bool {
4933482×
        self.oxy.join(UNBOUND_MARKER).is_file()
4943482×
    }
495
496
    /// Give an unbound repository its id.
49713×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
49813×
        if !self.is_unbound() {
4990×
            return fail("this repository already has an id");
50013×
        }
50113×
        if id == [0; 16] {
5020×
            return fail("a repository id cannot be all zero");
50313×
        }
50413×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
50513×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
50613×
        Ok(())
50713×
    }
508
509
    /// Whether this repository has no working copy (`init_bare`).
51076×
    pub fn is_bare(&self) -> bool {
51176×
        self.bare
51276×
    }
513
514
    /// Open the repository containing `start` (searching upwards).
5151909×
    pub fn open(start: &Path) -> Result<Repo> {
5161909×
        let start = start.canonicalize()?;
5171909×
        let mut dir: Option<&Path> = Some(&start);
5181909×
        while let Some(d) = dir {
5191909×
            let oxy = d.join(OXY_DIR);
5201909×
            if oxy.is_file() {
521
                // A secondary workspace (spec §12.2): the file points at the repository.
5229×
                let text = fs::read_to_string(&oxy)?;
5239×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5240×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
525
                };
5269×
                let format = fs::read_to_string(shared.join("format"))?;
5279×
                if format != FORMAT_LINE {
5280×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5299×
                }
5309×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5319×
                let store = open_objects(&shared, &config)?;
5329×
                let mut repo = Repo {
5339×
                    acceptor: None,
5349×
                    last_change: Default::default(),
5359×
                    at_op: None,
5369×
                    walked_dirs: Default::default(),
5379×
                    listed_dirs: Default::default(),
5389×
                    git_export_skipped: Default::default(),
5399×
                    manifest_cache: Default::default(),
5409×
                    listing_cache: Default::default(),
5419×
                    untracked_nested: Default::default(),
5429×
                    skipped_large: Default::default(),
5439×
                    root: d.to_path_buf(),
5449×
                    oxy: shared,
5459×
                    store,
5469×
                    workspace,
5479×
                    bare: false,
5489×
                    keys_dir: default_keys_dir(),
5499×
                    platform: crate::portable::Platform::current(),
5509×
                    user_config: default_user_config(),
5519×
                    config,
5529×
                };
5539×
                repo.apply_workspace_bookmark();
5549×
                return Ok(repo);
5551900×
            }
5561900×
            if oxy.is_dir() {
5571900×
                let format = fs::read_to_string(oxy.join("format"))?;
5581900×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5591900×
                let bare = oxy.join(BARE_MARKER).is_file();
5601900×
                let workspace = if bare {
561148×
                    WorkspaceId::ZERO
562
                } else {
5631752×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5641752×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
565
                };
5661900×
                let store = open_objects(&oxy, &config)?;
5671900×
                let mut repo = Repo {
5681900×
                    acceptor: None,
5691900×
                    last_change: Default::default(),
5701900×
                    at_op: None,
5711900×
                    walked_dirs: Default::default(),
5721900×
                    listed_dirs: Default::default(),
5731900×
                    git_export_skipped: Default::default(),
5741900×
                    manifest_cache: Default::default(),
5751900×
                    listing_cache: Default::default(),
5761900×
                    untracked_nested: Default::default(),
5771900×
                    skipped_large: Default::default(),
5781900×
                    root: d.to_path_buf(),
5791900×
                    oxy,
5801900×
                    store,
5811900×
                    workspace,
5821900×
                    bare,
5831900×
                    keys_dir: default_keys_dir(),
5841900×
                    platform: crate::portable::Platform::current(),
5851900×
                    user_config: default_user_config(),
5861900×
                    config,
5871900×
                };
5881900×
                if !bare {
5891752×
                    repo.apply_workspace_bookmark();
5901752×
                }
5911900×
                if format == FORMAT1_LINE {
5921×
                    repo.migrate_format1()?;
5931899×
                } else if format != FORMAT_LINE {
5940×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5951899×
                }
5961900×
                return Ok(repo);
5970×
            }
5980×
            dir = d.parent();
599
        }
6000×
        fail(format!(
601
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
6020×
            start.display()
603
        ))
6041909×
    }
605
606
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
607
    /// into format 2, where each bookmark names a `state` object.
6081×
    fn migrate_format1(&self) -> Result<()> {
6091×
        let (head, version) = self.read_head()?;
610
        // Collect the chain root-first.
6111×
        let mut chain: Vec<Format1Op> = Vec::new();
6121×
        let mut cur = Some(head);
6133×
        while let Some(r) = cur {
6142×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
6152×
            cur = op.parents.first().copied();
6162×
            chain.push(op);
617
        }
6181×
        chain.reverse();
6191×
        let mut new_parent: Option<ObjectRef> = None;
6202×
        for old in chain {
6212×
            let mut view = View::default();
6222×
            for (name, heads) in &old.view.bookmarks {
6232×
                view.bookmarks.insert(
6242×
                    name.clone(),
6252×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
626
                );
627
            }
6282×
            view.workspaces = old.view.workspaces.clone();
6292×
            let op = Op {
6302×
                parents: new_parent.into_iter().collect(),
6312×
                hlc: old.hlc,
6322×
                command: old.command,
6332×
                view,
6342×
                workspace: None,
6352×
                undoes: None,
6362×
            };
6372×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
638
        }
6391×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6400×
            return fail("the operation log changed while it was rewritten; run the command again");
6411×
        }
6421×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6431×
        Ok(())
6441×
    }
645
646
    /// Pack automatically once many loose objects have accumulated.
647635×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
648635×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6490×
            self.store.pack_loose()?;
6500×
            self.store.merge_packs()?;
651635×
        }
652635×
        Ok(())
653635×
    }
654
655
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6563201×
    pub fn id(&self) -> Result<[u8; 16]> {
6573201×
        if self.is_unbound() {
65819×
            return Ok([0; 16]);
6593182×
        }
6603182×
        let path = self.oxy.join("id");
6613182×
        match fs::read_to_string(&path) {
6623182×
            Ok(h) => hex::decode(h.trim())
6633182×
                .ok()
6643182×
                .and_then(|v| v.try_into().ok())
6653182×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6660×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6670×
                let mut id = [0u8; 16];
6680×
                rand::rngs::OsRng.fill_bytes(&mut id);
6690×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6700×
                Ok(id)
671
            }
6720×
            Err(e) => Err(e.into()),
673
        }
6743201×
    }
675
67662×
    pub fn root(&self) -> &Path {
67762×
        &self.root
67862×
    }
679492×
    pub fn store(&self) -> &Store {
680492×
        &self.store
681492×
    }
68211×
    pub fn workspace(&self) -> WorkspaceId {
68311×
        self.workspace
68411×
    }
685
686
    /// Use a different user directory for keys and the user config file
687
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
688
    /// Act as if the working copy were on another platform's file system
689
    /// (tests of Windows and macOS behaviour on any host).
690
    /// Accept certified updates as `identity` (a host's key), recording when
691
    /// (spec §14.7).
6921×
    pub fn with_acceptor(mut self, identity: Identity, sk: crate::identity::SecretKey) -> Repo {
6931×
        self.acceptor = Some(std::sync::Arc::new((identity, sk)));
6941×
        self
6951×
    }
696
6972×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
6982×
        self.platform = platform;
6992×
        self
7002×
    }
701
7020×
    pub fn platform(&self) -> crate::portable::Platform {
7030×
        self.platform
7040×
    }
705
706171×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
707171×
        let dir = dir.into();
708171×
        self.keys_dir = dir.join("keys");
709171×
        self.user_config = dir.join("config.toml");
710171×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
711171×
            self.config = c;
712171×
        }
713171×
        self.apply_workspace_bookmark();
714171×
        self
715171×
    }
716
717
    /// The workspace's current bookmark (spec §10.1) overrides the
718
    /// configured default when `oxy bookmark switch` has recorded one.
7191932×
    fn apply_workspace_bookmark(&mut self) {
7201932×
        if let Ok(b) = fs::read_to_string(
7211932×
            self.oxy
7221932×
                .join("workspaces")
7231932×
                .join(self.workspace.to_hex())
7241932×
                .join("bookmark"),
7251932×
        ) {
72635×
            let b = b.trim();
72735×
            if !b.is_empty() {
72835×
                self.config.bookmark = b.to_string();
72935×
            }
7301897×
        }
7311932×
    }
732
7332×
    pub fn user_config_path(&self) -> &Path {
7342×
        &self.user_config
7352×
    }
736
737
    /// Set a key in the user file and refresh the effective configuration.
73813×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
73913×
        Config::set_user(&self.user_config, key, value)?;
74012×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
74112×
        Ok(())
74213×
    }
743
744365×
    pub fn save_config(&self) -> Result<()> {
745365×
        self.config.save(&self.oxy.join("config"))
746365×
    }
747
7484199×
    fn author(&self) -> KeyId {
7494199×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7504199×
    }
751
}
752
753
impl Repo {
7541612×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7551612×
        let mut c = Change {
7561612×
            version: crate::objects::CHANGE_VERSION,
7571612×
            change_id: ChangeId::random(),
7581612×
            deps,
7591612×
            author: self.author(),
7601612×
            hlc: Hlc::now(),
7611612×
            message: message.into(),
7621612×
            tree_ops: vec![],
7631612×
            edits: vec![],
7641612×
            kind: ChangeKind::WorkingCopy,
7651612×
        };
7661612×
        c.normalize();
7671612×
        c
7681612×
    }
769
770
    // ------------------------------------------------------------ operation log
771
77213656×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
77313656×
        if let Some(r) = self.at_op {
7745×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
77513651×
        }
77613651×
        let r = self.head_ref()?;
77713649×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
77813649×
        Ok((r, op))
77913656×
    }
780
7819474×
    pub fn view(&self) -> Result<View> {
7829474×
        Ok(self.head_op()?.1.view)
7839474×
    }
784
7853319×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
7863319×
        self.record_op_undoing(parents, command, view, None)
7873319×
    }
788
789
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
7903322×
    fn record_op_undoing(
7913322×
        &self,
7923322×
        parents: &[ObjectRef],
7933322×
        command: &str,
7943322×
        view: View,
7953322×
        undoes: Option<ObjectRef>,
7963322×
    ) -> Result<ObjectRef> {
7973322×
        if self.at_op.is_some() {
7981×
            return fail(
799
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
800
            );
8013321×
        }
8023321×
        let op = Op {
8033321×
            parents: parents.to_vec(),
8043321×
            hlc: Hlc::now(),
8053321×
            command: command.into(),
8063321×
            view,
8073321×
            workspace: Some(self.workspace),
8083321×
            undoes,
8093321×
        };
8103321×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
811
        // The head is the commit point: everything it names must be on disk first.
8123319×
        let flushing = crate::timing::phase("op: flush the store");
8133319×
        self.store.flush()?;
8143317×
        drop(flushing);
815
        // Compare and swap (spec §12.1): when another process recorded an
816
        // operation since this one read the head, the two are merged
817
        // instead of one overwriting the other. On this disk the head moves
818
        // under a short lock; on any other store by its record's version,
819
        // and a record that moved meanwhile is read again and merged again.
8203317×
        let _lock = if self.store.is_local() {
8213309×
            Some(self.lock_ops()?)
822
        } else {
8238×
            None
824
        };
8253317×
        let Some(parent) = parents.first() else {
826
            // The first operation (init): there is no head yet.
827522×
            if !self.swap_head(&r, None)? {
8282×
                return fail(format!(
829
                    "{} already holds a repository's operation log",
8302×
                    self.store.backend().describe()
831
                ));
832520×
            }
833520×
            return Ok(r);
834
        };
8352795×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8362795×
        for _ in 0..HEAD_TRIES {
8372795×
            let (current, version) = self.read_head()?;
8382795×
            let to = if current == *parent {
8392786×
                r
840
            } else {
8419×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
8428×
                let merged = Op {
8439×
                    parents: vec![current, r],
8449×
                    hlc: Hlc::now(),
8459×
                    command: format!("{command} (merged with a concurrent operation)"),
8469×
                    view: self.merge_views(&base, &op.view, &theirs)?,
8478×
                    workspace: Some(self.workspace),
8488×
                    undoes: None,
849
                };
8508×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
8518×
                self.store.flush()?;
8528×
                m
853
            };
8542794×
            if self.swap_head(&to, version.as_ref())? {
8552788×
                return Ok(to);
8560×
            }
857
        }
8580×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8593322×
    }
860
861
    /// The operation head's lock, held only while the head pointer moves.
8623319×
    fn lock_ops(&self) -> Result<FileLock> {
8633319×
        fs::create_dir_all(self.oxy.join("ops"))?;
8643319×
        FileLock::acquire(
8653319×
            self.oxy.join("ops").join("lock"),
8663319×
            "another oxy process holds the operation log",
867
        )
8683319×
    }
869
87013653×
    fn head_ref(&self) -> Result<ObjectRef> {
87113653×
        Ok(self.read_head()?.0)
87213653×
    }
873
874
    /// The operation head, and on a store its record's version for
875
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
876
    /// any other store (a bucket, or memory in tests) it is the store's
877
    /// [`HEAD_RECORD`] reference record (oxygen#68).
87816537×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
87916537×
        if self.store.is_local() {
88016518×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
88116518×
            let r = ObjectRef::from_hex(hex.trim())
88216518×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
88316515×
            return Ok((r, None));
88419×
        }
88519×
        let backend = self.store.backend();
88619×
        match backend.read_ref(HEAD_RECORD) {
88719×
            Ok(Some((bytes, version))) => {
88819×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
8890×
                    || {
8900×
                        RepoError::Msg(format!(
8910×
                            "the operation head in {} is corrupt",
8920×
                            backend.describe()
8930×
                        ))
8940×
                    },
8950×
                )?;
89619×
                Ok((r, Some(version)))
897
            }
8980×
            Ok(None) => fail(format!(
899
                "{} holds no operation log (no {HEAD_RECORD} record)",
9000×
                backend.describe()
901
            )),
9020×
            Err(e) => fail(format!("read the operation head: {e}")),
903
        }
90416537×
    }
905
906
    /// Move the operation head to `to` from the `expected` version
907
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
908
    /// disk the caller holds the operations lock and the head always
909
    /// moves; on a store it moves only if the record is unchanged, and
910
    /// `false` says another process moved it first.
9113329×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
9123329×
        if self.store.is_local() {
9133319×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
9143313×
            return Ok(true);
91510×
        }
91610×
        match self
91710×
            .store
91810×
            .backend()
91910×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
920
        {
9217×
            Ok(_) => Ok(true),
9223×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
9230×
            Err(e) => fail(format!("move the operation head: {e}")),
924
        }
9253329×
    }
926
927
    /// Three-way merge of two views that both started from `base` (spec
928
    /// §12.1). A reference only one side changed takes that side's value.
929
    /// When both changed it differently: a bookmark keeps both sides'
930
    /// heads (it may then have several), a change beats a deletion, a
931
    /// workspace changed by both is an error (only one of them matches the
932
    /// files on disk), and otherwise this process's value wins for remote
933
    /// references and the policy, the first value for a tag (tags never
934
    /// move).
9359×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
93628×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
93728×
            b: &BTreeMap<K, V>,
93828×
            o: &BTreeMap<K, V>,
93928×
            t: &BTreeMap<K, V>,
94028×
            mut both: impl FnMut(&V, &V) -> Result<V>,
94128×
        ) -> Result<BTreeMap<K, V>> {
94228×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
94328×
            let mut out = BTreeMap::new();
94429×
            for k in keys {
94529×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
94629×
                let v = if ov == tv || tv == bv {
94713×
                    ov.cloned()
94816×
                } else if ov == bv {
9499×
                    tv.cloned()
950
                } else {
9517×
                    match (ov, tv) {
9527×
                        (Some(x), Some(y)) => Some(both(x, y)?),
9530×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
9540×
                        (None, None) => None,
955
                    }
956
                };
95728×
                if let Some(v) = v {
95828×
                    out.insert(k.clone(), v);
95928×
                }
960
            }
96127×
            Ok(out)
96228×
        }
9639×
        let bookmarks = pick(
9649×
            &base.bookmarks,
9659×
            &ours.bookmarks,
9669×
            &theirs.bookmarks,
9676×
            |x, y| {
9686×
                let mut heads = self.store.get_state(x)?.heads;
9696×
                heads.extend(self.store.get_state(y)?.heads);
9706×
                let heads = self.load_state(&heads)?.maximal(&heads);
9716×
                Ok(self.store.put_state(&StateObject::new(heads))?)
9726×
            },
9730×
        )?;
974
        // Two operations that both replaced one workspace's working copy
975
        // cannot both be right: the files on disk match only one of them.
976
        // The working-copy lock keeps this from happening; should it happen
977
        // anyway, this operation is not recorded.
9789×
        let workspaces = pick(
9799×
            &base.workspaces,
9809×
            &ours.workspaces,
9819×
            &theirs.workspaces,
9821×
            |_, _| {
9831×
                fail(
984
                    "another oxy process changed this working copy at the same time; \
985
                     this command was not recorded: check `oxy status` and run it again",
986
                )
9871×
            },
9881×
        )?;
9898×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
9908×
        let empty = BTreeMap::new();
9918×
        let names: BTreeSet<&String> = base
9928×
            .remotes
9938×
            .keys()
9948×
            .chain(ours.remotes.keys())
9958×
            .chain(theirs.remotes.keys())
9968×
            .collect();
9978×
        let mut remotes = BTreeMap::new();
9988×
        for n in names {
9992×
            let m = pick(
10002×
                base.remotes.get(n).unwrap_or(&empty),
10012×
                ours.remotes.get(n).unwrap_or(&empty),
10022×
                theirs.remotes.get(n).unwrap_or(&empty),
10030×
                |x, _| Ok(*x),
10040×
            )?;
10052×
            if !m.is_empty() {
10062×
                remotes.insert(n.clone(), m);
10072×
            }
1008
        }
10098×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
10108×
            ours.policy
10110×
        } else if ours.policy == base.policy {
10120×
            theirs.policy
1013
        } else {
10140×
            ours.policy.or(theirs.policy)
1015
        };
10168×
        self.store.flush()?;
10178×
        Ok(View {
10188×
            bookmarks,
10198×
            workspaces,
10208×
            remotes,
10218×
            policy,
10228×
            tags,
10238×
        })
10249×
    }
1025
102648×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
102748×
        let mut out = Vec::new();
102848×
        let (mut r, mut op) = self.head_op()?;
1029
        loop {
1030261×
            let next = op.parents.first().copied();
1031261×
            out.push((r, op));
1032261×
            match next {
1033213×
                Some(p) => {
1034213×
                    r = p;
1035213×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1036
                }
103748×
                None => break,
1038
            }
1039
        }
104048×
        Ok(out)
104148×
    }
1042
1043
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1044
    ///
1045
    /// The command undone is the newest one this workspace ran: operations
1046
    /// that only recorded a working-copy snapshot are skipped (the files are
1047
    /// still on disk and the next snapshot recreates them), as are pushes
1048
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1049
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1050
    /// operations are never undone, and a command an earlier undo already
1051
    /// reverted is passed over, so undoing again goes further back.
1052
    ///
1053
    /// When nothing newer came from another workspace, the operation head
1054
    /// moves back to before the command. Otherwise the command is reverted
1055
    /// in place: every reference it changed goes back to its value before
1056
    /// it, recorded as a new operation that names it, and anything another
1057
    /// workspace changed since is kept. A reference both the command and a
1058
    /// later operation of another workspace changed is not guessed at: the
1059
    /// undo is refused, naming it.
1060
    ///
1061
    /// When the working copy is clean and was clean after the command's
1062
    /// predecessor, its files follow too, since nothing on disk can be
1063
    /// lost; otherwise they stay as they are (an undone commit's edits come
1064
    /// back as uncommitted work).
106516×
    pub fn undo(&self) -> Result<Undone> {
106616×
        let _wc = self.lock_working_copy()?;
106716×
        let clean_now =
106816×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
106916×
        let (head_ref, head) = self.head_op()?;
107016×
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
107140×
        let load = |r: &ObjectRef| -> Result<Op> {
107240×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
107340×
        };
107416×
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
107516×
        let mut pending_checkout: Option<Op> = None;
107616×
        let mut others = 0usize;
107716×
        let (mut r, mut op) = (head_ref, head.clone());
107815×
        let (target_ref, target, parent) = loop {
107941×
            let parent = match op.parents.first() {
108040×
                Some(p) => Some((*p, load(p)?)),
10811×
                None => None,
1082
            };
108341×
            if skip.contains(&r) {
10841×
                pending_checkout = None;
108540×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
108610×
                // A push cannot be taken back: undoing it would only make
108710×
                // this repository forget what the remote holds.
108830×
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
108910×
                others += 1;
109020×
            } else if let Some(u) = op.undoes {
10911×
                skip.insert(u);
10921×
                pending_checkout = None;
109319×
            } else if op.command.ends_with(" (checkout)") {
10943×
                pending_checkout = Some(op.clone());
10953×
            } else {
109616×
                match parent {
109715×
                    Some((_, p)) => break (r, op, p),
10981×
                    None => return fail("nothing to undo in this workspace"),
1099
                }
1100
            }
110125×
            match parent {
110225×
                Some((pr, p)) => (r, op) = (pr, p),
11030×
                None => return fail("nothing to undo in this workspace"),
1104
            }
1105
        };
110615×
        let before = parent.view;
110715×
        let after = pending_checkout
110815×
            .map(|o| o.view)
110915×
            .unwrap_or_else(|| target.view.clone());
111015×
        let changes = self.view_changes(&before, &after)?;
111115×
        let pushed = self.pushed_by(&before, &after, &head.view)?;
111215×
        let restored_wc = before.workspaces.get(&self.workspace).copied();
111315×
        if others == 0 {
1114
            // Only this workspace's operations since: move the head back.
111510×
            let _lock = if self.store.is_local() {
111610×
                Some(self.lock_ops()?)
1117
            } else {
11180×
                None
1119
            };
112010×
            let parent_ref = *target.parents.first().expect("the target has a parent");
112110×
            let (now, version) = self.read_head()?;
112210×
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
11230×
                return fail("another oxy command ran while undoing; run undo again");
112410×
            }
1125
        } else {
11265×
            let view = self.revert_view(&head.view, &before, &after)?;
11273×
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1128
        }
112913×
        self.drop_manifest();
113013×
        if let Some(then) = restored_wc {
113113×
            if clean_now && Some(then) != wc_now {
1132
                // Past `core.snapshot-retention` the working copy may be
1133
                // gone: the files then stay as they are.
113410×
                let Ok(wc) = self.store.get_change(&then) else {
11350×
                    return Ok(Undone {
11360×
                        command: target.command,
11370×
                        changes,
11380×
                        others_kept: others,
11390×
                        pushed,
11400×
                    });
1141
                };
114210×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
11438×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1144
                    // The files differ from the restored working copy by
1145
                    // exactly what the undone command did: nothing else is
1146
                    // on disk, as the working copy was clean.
11478×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
11482×
                }
11493×
            }
11500×
        }
115113×
        Ok(Undone {
115213×
            command: target.command,
115313×
            changes,
115413×
            others_kept: others,
115513×
            pushed,
115613×
        })
115716×
    }
1158
1159
    /// Whether operation `op` was a push: it changed only what this
1160
    /// repository knows of remotes.
116131×
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
116231×
        let Some(p) = parent else {
11631×
            return false;
1164
        };
116530×
        op.command.starts_with("oxy push")
11661×
            && op.view.bookmarks == p.view.bookmarks
11671×
            && op.view.tags == p.view.tags
11681×
            && op.view.workspaces == p.view.workspaces
11691×
            && op.view.policy == p.view.policy
117031×
    }
1171
1172
    /// Whether operation `op` (whose predecessor is `parent`) was this
1173
    /// workspace's. Operations record their workspace (oxygen#99); for older
1174
    /// ones it is read from the view: one that changed only other
1175
    /// workspaces' working copies was theirs, anything else counts as ours.
117630×
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
117730×
        if let Some(w) = op.workspace {
117830×
            return w == self.workspace;
11790×
        }
11800×
        let Some(p) = parent else {
11810×
            return true;
1182
        };
11830×
        let ids: BTreeSet<&WorkspaceId> = op
11840×
            .view
11850×
            .workspaces
11860×
            .keys()
11870×
            .chain(p.view.workspaces.keys())
11880×
            .collect();
11890×
        let moved: Vec<&WorkspaceId> = ids
11900×
            .into_iter()
11910×
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
11920×
            .collect();
11930×
        moved.is_empty() || moved.contains(&&self.workspace)
119430×
    }
1195
1196
    /// `current` with what changed from `before` to `after` put back, this
1197
    /// workspace's working copy included; refused when a later operation
1198
    /// changed one of the same references again.
11995×
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
120010×
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
120110×
            cur: &mut BTreeMap<K, V>,
120210×
            before: &BTreeMap<K, V>,
120310×
            after: &BTreeMap<K, V>,
120410×
            name: impl Fn(&K) -> String,
120510×
            clashes: &mut Vec<String>,
120610×
        ) {
120710×
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
120810×
            for k in keys {
12095×
                let (b, a) = (before.get(k), after.get(k));
12105×
                if a == b {
12114×
                    continue;
12121×
                }
12131×
                if cur.get(k) != a {
12141×
                    clashes.push(name(k));
12151×
                    continue;
12160×
                }
12170×
                match b {
12180×
                    Some(v) => cur.insert(k.clone(), v.clone()),
12190×
                    None => cur.remove(k),
1220
                };
1221
            }
122210×
        }
12235×
        let mut out = current.clone();
12245×
        let mut clashes = Vec::new();
1225
        // A bookmark another workspace moved since is put back head by
1226
        // head: the heads the command added go, the heads it replaced
1227
        // return, and the other workspace's heads stay. Only when a later
1228
        // change was built on one the command added is that not possible.
12295×
        let names: BTreeSet<&String> = before
12305×
            .bookmarks
12315×
            .keys()
12325×
            .chain(after.bookmarks.keys())
12335×
            .collect();
12348×
        for name in names {
12358×
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
12368×
            let cur = current.bookmarks.get(name);
12378×
            if a == b {
12384×
                continue;
12394×
            }
12404×
            if cur == a {
12412×
                match b {
12422×
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
12430×
                    None => out.bookmarks.remove(name),
1244
                };
12452×
                continue;
12462×
            }
12472×
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
12480×
                clashes.push(format!("bookmark {name}"));
12490×
                continue;
1250
            };
12512×
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
12522×
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
12532×
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
12542×
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
12552×
            if !added.iter().all(|h| now.contains(h)) {
12561×
                clashes.push(format!(
1257
                    "bookmark {name} (a later change builds on this one)"
1258
                ));
12591×
                continue;
12601×
            }
12611×
            let mut heads: Vec<ChangeHash> = now
12621×
                .iter()
12633×
                .filter(|h| !added.contains(h))
12641×
                .chain(was.difference(&became))
12651×
                .copied()
12661×
                .collect();
12671×
            heads.sort();
12681×
            heads.dedup();
12691×
            let heads = self.load_state(&heads)?.maximal(&heads);
12701×
            out.bookmarks.insert(
12711×
                name.clone(),
12721×
                self.store.put_state(&StateObject::new(heads))?,
1273
            );
1274
        }
1275
12765×
        back(
12775×
            &mut out.tags,
12785×
            &before.tags,
12795×
            &after.tags,
12800×
            |k| format!("tag {k}"),
12815×
            &mut clashes,
1282
        );
12835×
        let mine = self.workspace;
128415×
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
128515×
            v.workspaces
128615×
                .iter()
128729×
                .filter(|(k, _)| **k != mine)
128815×
                .map(|(k, v)| (*k, *v))
128915×
                .collect()
129015×
        };
12915×
        let mut theirs = others(&out);
12925×
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
12931×
            Some(p) => format!("the workspace at {}", p.display()),
12940×
            None => format!("workspace {}", id.to_hex()),
12951×
        };
12965×
        back(
12975×
            &mut theirs,
12985×
            &others(before),
12995×
            &others(after),
13005×
            workspace_name,
13015×
            &mut clashes,
1302
        );
13035×
        let empty = BTreeMap::new();
13045×
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
13055×
        for n in names {
13060×
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
13070×
            back(
13080×
                &mut cur,
13090×
                before.remotes.get(n).unwrap_or(&empty),
13100×
                after.remotes.get(n).unwrap_or(&empty),
13110×
                |k| format!("{n}/{k}"),
13120×
                &mut clashes,
1313
            );
13140×
            if cur.is_empty() {
13150×
                out.remotes.remove(n);
13160×
            } else {
13170×
                out.remotes.insert(n.clone(), cur);
13180×
            }
1319
        }
13205×
        if before.policy != after.policy {
13210×
            if out.policy == after.policy {
13220×
                out.policy = before.policy;
13230×
            } else {
13240×
                clashes.push("the policy".into());
13250×
            }
13265×
        }
13275×
        if !clashes.is_empty() {
13282×
            return fail(format!(
1329
                "undo would also take back what another workspace has done since to {}; \
1330
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
13312×
                clashes.join(", ")
1332
            ));
13333×
        }
13343×
        out.workspaces = theirs;
13353×
        match before.workspaces.get(&mine) {
13363×
            Some(wc) => out.workspaces.insert(mine, *wc),
13370×
            None => out.workspaces.remove(&mine),
1338
        };
13393×
        Ok(out)
13405×
    }
1341
1342
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1343
    /// in `now` already holds: undoing them locally leaves them there.
134415×
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
134515×
        let mut out = Vec::new();
134618×
        for (name, st) in &after.bookmarks {
134718×
            if before.bookmarks.get(name) == Some(st) {
13484×
                continue;
134914×
            }
135014×
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
135114×
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
13520×
                None => BTreeSet::new(),
1353
            };
135414×
            let added: Vec<ChangeHash> = self
135514×
                .store
135614×
                .get_state(st)?
1357
                .heads
135814×
                .into_iter()
135920×
                .filter(|h| !had.contains(h))
136014×
                .collect();
136114×
            if added.is_empty() {
13621×
                continue;
136313×
            }
136413×
            for (remote, bookmarks) in &now.remotes {
13651×
                if let Some(rs) = bookmarks.get(name) {
13661×
                    let theirs = self.store.get_state(rs)?.heads;
13671×
                    if added.iter().any(|h| theirs.contains(h)) {
13681×
                        out.push((name.clone(), remote.clone()));
13691×
                    }
13700×
                }
1371
            }
1372
        }
137315×
        Ok(out)
137415×
    }
1375
1376
    /// The last operation that was not a snapshot.
13772×
    pub fn last_command(&self) -> Result<Op> {
13782×
        let (_, mut op) = self.head_op()?;
13794×
        while op.is_snapshot() {
13802×
            let Some(parent) = op.parents.first() else {
13810×
                break;
1382
            };
13832×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1384
        }
13852×
        Ok(op)
13862×
    }
1387
1388
    // ------------------------------------------------------------ states
1389
1390
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1391200×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1392200×
        if let Some(st) = self.load_state_checkpointed(heads)? {
13934×
            return Ok(st);
1394195×
        }
1395195×
        self.load_state_full(heads)
1396200×
    }
1397
1398
    /// The state of `heads` for its history (changes, tree, metadata) with
1399
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1400
    /// and friends. Build the graphs a command needs with
1401
    /// [`Repo::load_graphs_of`].
14021701×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
14031701×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
140431×
            return Ok(st);
14051670×
        }
14061670×
        self.load_state_replayed(heads, State::new_history_only())
14071701×
    }
1408
1409
    /// Build these file graphs in a history-only state.
14101772×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
14111772×
        state
14121772×
            .load_graphs(
14131772×
                nodes,
141454×
                |refs| {
141554×
                    self.read_blobs(refs).map_err(|e| {
14163×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14173×
                    })
141854×
                },
14191939×
                |h| self.change_bytes(h),
1420
            )
14211772×
            .map_err(|e| self.index_damage(e))
14221772×
    }
1423
1424
    /// An error building graphs, and when it is a state index found
1425
    /// damaged (a file's history that does not match its hash), the
1426
    /// workspace's state indexes removed: they are rebuilt from history by
1427
    /// the next command.
14284×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
14294×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
14303×
            return e.into();
1431
        };
14322×
        for path in self.state_indexes() {
14332×
            let _ = fs::remove_file(path);
14342×
        }
14351×
        RepoError::Msg(format!(
14361×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
14371×
        ))
14384×
    }
1439
1440
    /// The graphs of `nodes` of a history-only state, built beside it (see
1441
    /// [`State::build_graphs_detached`]).
144277×
    pub fn build_graphs_detached(
144377×
        &self,
144477×
        state: &State,
144577×
        nodes: &[crate::ids::NodeId],
144677×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
144777×
        Ok(state
144877×
            .build_graphs_detached(
144977×
                nodes,
14500×
                |refs| {
14510×
                    self.read_blobs(refs).map_err(|e| {
14520×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14530×
                    })
14540×
                },
145583×
                |h| self.change_bytes(h),
1456
            )
145777×
            .map_err(|e| self.index_damage(e))?
145877×
            .into_iter()
145977×
            .collect())
146077×
    }
1461
1462
    /// The contents of texts [`State::single_text`] gave: blobs read in
1463
    /// one go, inline ones from their changes.
1464352×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1465
        use crate::objects::TextRef;
1466352×
        let refs: Vec<ObjectRef> = texts
1467352×
            .iter()
14685539×
            .filter_map(|t| match t {
14691×
                TextRef::Blob(r, _, _) => Some(*r),
14705538×
                TextRef::Inline { .. } => None,
14715539×
            })
1472352×
            .collect();
1473352×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1474352×
        let mut out = Vec::with_capacity(texts.len());
14755539×
        for t in texts {
14765539×
            let lines = match t {
14771×
                TextRef::Blob(_, count, form) => {
14781×
                    let content = blobs
14791×
                        .next()
14801×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
14811×
                    crate::objects::text_lines(&content, *count, *form)?
1482
                }
14835538×
                TextRef::Inline { change, start, end } => {
14845538×
                    let bytes = self.change_bytes(change)?;
14855538×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
14860×
                        RepoError::Msg("an inline insert lies outside its change".into())
14870×
                    })?;
14885538×
                    crate::objects::inline_lines(range)?
1489
                }
1490
            };
14915539×
            out.push(lines.bytes().to_vec());
1492
        }
1493352×
        Ok(out)
1494352×
    }
1495
1496
    /// Build every graph a history-only state still lacks, making it full.
14971808×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
14981808×
        state
14991808×
            .load_all_graphs(
150016×
                |refs| {
150116×
                    self.read_blobs(refs).map_err(|e| {
15020×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
15030×
                    })
150416×
                },
15053765×
                |h| self.change_bytes(h),
1506
            )
15071808×
            .map_err(|e| self.index_damage(e))
15081808×
    }
1509
1510
    /// A change's encoding, for building graphs of its inline inserts. The
1511
    /// last few read are kept: a checkout building graphs a batch at a
1512
    /// time reads the same large changes for every batch, often in turn.
151311325×
    fn change_bytes(
151411325×
        &self,
151511325×
        h: &ChangeHash,
151611325×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
151711325×
        let mut cache = self.last_change.borrow_mut();
151819473×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
15198886×
            let hit = cache.remove(i);
15208886×
            let b = hit.1.clone();
15218886×
            cache.push(hit);
15228886×
            return Ok(b);
15232439×
        }
15242439×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
15250×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
15260×
        })?);
15272439×
        cache.push((*h, b.clone()));
1528
        // The last few, within a memory budget; the newest always stays.
15293937×
        while cache.len() > CHANGE_CACHE_COUNT
15302439×
            || (cache.len() > 1
15317286×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15321498×
        {
15331498×
            cache.remove(0);
15341498×
        }
15352439×
        Ok(b)
153611325×
    }
1537
1538
    /// Load the dependency closure of `heads` change by change.
1539249×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1540249×
        self.load_state_replayed(heads, State::new())
1541249×
    }
1542
15433239×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
15443239×
        let history = state.is_history_only();
15453239×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
15463239×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1547
        {
15483239×
            let _t = crate::timing::phase("load: read and add changes");
15493239×
            let (mut read, mut add, mut fetch) = (
15503239×
                std::time::Duration::ZERO,
15513239×
                std::time::Duration::ZERO,
15523239×
                std::time::Duration::ZERO,
15533239×
            );
155412696×
            while let Some(h) = stack.pop() {
1555
                // A change the state holds brings its history with it.
15569460×
                if !seen.insert(h) || state.contains(&h) {
15572109×
                    continue;
15587351×
                }
15597351×
                let t0 = std::time::Instant::now();
1560
                // A history-only state reads text only for the graphs it
1561
                // builds; either way the hash is the one asked for.
15627351×
                let (c, texts) = if history {
15636128×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
15646127×
                    fetch += t0.elapsed();
15656127×
                    Change::decode_skeleton(&bytes, h)
15666127×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1567
                } else {
15681223×
                    (self.store.get_change(&h)?, Vec::new())
1569
                };
15707348×
                read += t0.elapsed();
15717348×
                stack.extend(c.deps.iter().copied());
15727348×
                let t1 = std::time::Instant::now();
15737348×
                state.add_known(h, c, texts);
15747348×
                add += t1.elapsed();
1575
            }
15763236×
            crate::timing::record("load:   of which reading", read);
15773236×
            crate::timing::record("load:     of which fetching", fetch);
15783236×
            crate::timing::record("load:   of which applying", add);
1579
        }
15803236×
        let _t = crate::timing::phase("load: validate");
15813236×
        state.validate()?;
15823236×
        Ok(state)
15833239×
    }
1584
15852303×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
15862303×
        if self.bare {
15872×
            return fail("this is a bare repository: it has no working copy");
15882301×
        }
15892301×
        let view = self.view()?;
15902301×
        let h = *view
15912301×
            .workspaces
15922301×
            .get(&self.workspace)
15932301×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
15942300×
        Ok((h, self.store.get_change(&h)?))
15952303×
    }
1596
1597
    /// Heads of a bookmark's state (spec §10.1).
15981761×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
15991761×
        match view.bookmarks.get(bookmark) {
16001761×
            Some(st) => Ok(self.store.get_state(st)?.heads),
16010×
            None => Ok(vec![]),
1602
        }
16031761×
    }
1604
1605508×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1606508×
        self.heads_of(&self.view()?, &self.config.bookmark)
1607508×
    }
1608
1609
    // ------------------------------------------------------------ blobs
1610
1611399×
    fn blob_for(content: &[u8]) -> Blob {
1612399×
        Blob::of(content)
1613399×
    }
1614
1615246×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1616246×
        Self::blob_for(content).hash()
1617246×
    }
1618
1619151×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1620194×
        for c in crate::chunk::chunks(content) {
1621194×
            self.store.put_chunk(c)?;
1622
        }
1623151×
        Ok(self
1624151×
            .store
1625151×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1626151×
    }
1627
1628
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1629
    /// all their chunks, are read in parallel; a blob the store lacks goes
1630
    /// through [`Repo::read_blob`], which may fetch it lazily.
1631426×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1632426×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1633426×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
163480×
            blobs.push(match got {
163575×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
16360×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
16375×
                Err(crate::store::StoreError::NotFound(_)) => None,
16380×
                Err(e) => return Err(e.into()),
1639
            });
1640
        }
1641426×
        let chunk_refs: Vec<ObjectRef> = blobs
1642426×
            .iter()
1643426×
            .flatten()
1644426×
            .flat_map(|b| b.chunks.iter().copied())
1645426×
            .collect();
1646426×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1647426×
        let mut out = Vec::with_capacity(refs.len());
1648426×
        for (r, blob) in refs.iter().zip(blobs) {
164980×
            match blob {
16505×
                None => out.push(self.read_blob(r)?),
165175×
                Some(b) => {
165275×
                    let mut content = Vec::with_capacity(b.length as usize);
1653114×
                    for c in &b.chunks {
1654114×
                        match chunks.next() {
1655114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
16560×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
16570×
                            Some(Err(e)) => return Err(e.into()),
16580×
                            None => return fail("chunk list ended early"),
1659
                        }
1660
                    }
166175×
                    out.push(content);
1662
                }
1663
            }
1664
        }
1665421×
        Ok(out)
1666426×
    }
1667
1668
    /// Read a blob's content, fetching it from the remote that withheld it
1669
    /// when it is lazily absent (spec §13.5).
1670113×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1671113×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
16724×
            self.fetch_lazy_blob(r)?;
1673109×
        }
1674113×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1675108×
        let mut out = Vec::with_capacity(blob.length as usize);
1676135×
        for c in &blob.chunks {
1677135×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1678
        }
1679108×
        Ok(out)
1680113×
    }
1681
1682
    // ------------------------------------------------------------ working copy
1683
1684
    /// Attributes from the `.oxyattributes` files in the working directory.
16852×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1686
        // Nested repositories and ignored paths are left out, as in a walk.
16878×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
16882×
        let files: Vec<(String, Vec<u8>)> = listing
16892×
            .files
16902×
            .into_iter()
16912×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
16922×
            .collect();
16932×
        crate::attributes::Attributes::from_files(
16942×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1695
        )
16962×
    }
1697
1698
    /// Folders holding a repository of their own that the last look at the
1699
    /// working copy left out, not being subrepos (oxygen#43).
170029×
    pub fn untracked_nested(&self) -> Vec<String> {
170129×
        self.untracked_nested.borrow().clone()
170229×
    }
1703
1704
    /// New untracked files the last snapshot left out for being larger than
1705
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
170633×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
170733×
        self.skipped_large.borrow().clone()
170833×
    }
1709
1710
    /// Attributes from a materialized state's `.oxyattributes` files.
17113×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
17126×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
17136×
            match &f.content {
17146×
                FileContent::Text { bytes, .. }
17156×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1716
                {
17170×
                    Some((p.as_str(), bytes.as_slice()))
1718
                }
17196×
                _ => None,
1720
            }
17216×
        }))
17223×
    }
1723
1724
    /// Store a blob, raw when the path is `nocompress`.
1725132×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1726132×
        if !nocompress {
1727130×
            return self.store_blob(content);
17282×
        }
17292×
        for c in crate::chunk::chunks(content) {
17302×
            self.store.put_chunk_nocompress(c)?;
1731
        }
17322×
        Ok(self
17332×
            .store
17342×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1735132×
    }
1736
1737
    /// This workspace's state index (oxygen#41): its working copy's base,
1738
    /// saved so a snapshot reads it rather than replaying history.
1739
    /// The state index of the state with these heads: this workspace keeps
1740
    /// the last few it used, named by their heads, so moving between two
1741
    /// states finds both.
17422385×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
17432385×
        let mut heads = heads.to_vec();
17442385×
        heads.sort();
17452385×
        let mut h = blake3::Hasher::new();
17462385×
        for c in &heads {
17472347×
            h.update(&c.0);
17482347×
        }
17492385×
        self.oxy.join("index").join(format!(
17502385×
            "{}{}",
17512385×
            self.state_index_prefix(),
17522385×
            &h.finalize().to_hex()[..16]
17532385×
        ))
17542385×
    }
1755
17564677×
    fn state_index_prefix(&self) -> String {
17574677×
        format!("state-{}-", self.workspace.to_hex())
17584677×
    }
1759
1760
    /// This workspace's state indexes, newest first.
17612292×
    fn state_indexes(&self) -> Vec<PathBuf> {
17622292×
        let prefix = self.state_index_prefix();
17632292×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
17642292×
            .into_iter()
17652292×
            .flatten()
17662292×
            .flatten()
17672292×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
17682292×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
17692292×
            .collect();
17702292×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
17712292×
        found.into_iter().map(|(_, p)| p).collect()
17722292×
    }
1773
1774
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1775
    /// from this workspace's state index when it holds that history: every
1776
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1777
    /// is loaded from history and indexed for next time.
17781985×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
17791985×
        if let Some((st, heads)) = self.read_state_index(deps) {
17801592×
            let mut have = st.maximal(deps);
17811592×
            have.sort();
17821592×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1783
                // Re-encoding reads every history: one found damaged is
1784
                // left to the build that reads it, which reports it.
1785
                #[cfg(test)]
1786159×
                if let Some(mine) = st.write_index() {
1787156×
                    assert_eq!(
1788156×
                        Some(mine),
1789156×
                        self.load_state_history(deps)?.write_index(),
1790
                        "a state index holds the state history gives"
1791
                    );
17923×
                }
1793272×
                return Ok(st);
17941320×
            }
1795
            // An index a few changes behind (a commit, a pull since): add
1796
            // what it lacks, as long as all it holds is history of `deps`.
1797
            // Anything amiss (a change beyond a shallow boundary) takes the
1798
            // long way instead.
17991320×
            let (indexed, started) = (st.len(), std::time::Instant::now());
18001320×
            if let Ok(st) = self.load_state_replayed(deps, st) {
18011319×
                let mut all = deps.to_vec();
18021319×
                all.extend(heads.iter().copied());
18031319×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
18041319×
                within.sort();
18051319×
                want.sort();
18061319×
                if within == want {
1807
                    #[cfg(test)]
1808695×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1809
                    // Writing the index costs far more than replaying a
1810
                    // few small changes: it is rewritten once it falls
1811
                    // behind, or when replaying took long (large changes).
18121317×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
18131317×
                        || started.elapsed() > INDEX_REPLAY_TIME
18143×
                    {
18153×
                        self.write_state_index(deps, &st);
18161314×
                    }
18171317×
                    return Ok(st);
18182×
                }
18191×
            }
1820393×
        }
1821396×
        let st = self.load_state_history(deps)?;
1822396×
        self.write_state_index(deps, &st);
1823396×
        Ok(st)
18241985×
    }
1825
1826
    /// Two history-only states hold the same changes and render the same
1827
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1828
    /// the checkpoint's graphs as the bases of its files' histories.
1829
    #[cfg(test)]
1830695×
    fn assert_same_state(&self, a: &State, b: &State) {
18311390×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1832695×
        assert_eq!(ids(a), ids(b), "the same changes");
18331390×
        let files = |s: &State| {
18341390×
            let mut s = s.clone();
18351390×
            self.load_all_graphs(&mut s).unwrap();
18361390×
            s.materialize().files
18371390×
        };
1838695×
        assert_eq!(files(a), files(b), "the same files");
1839695×
    }
1840
1841
    /// The state index file: its heads, a hash of its changes block and one
1842
    /// of the rest, then the body [`State::write_index`] gives, whose first
1843
    /// block is the changes. Hashed in two parts so the log can read and
1844
    /// check the changes alone.
1845
    /// The index of `deps` if there is one, else the newest, which the
1846
    /// caller may bring up to date.
18471985×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1848
        use std::io::Read;
18491985×
        let _t = crate::timing::phase("load: state index");
18501985×
        let exact = self.state_index_path(deps);
18511985×
        let reading = crate::timing::phase("load:   of which reading the file");
18521985×
        let mut f = match fs::File::open(&exact) {
1853272×
            Ok(f) => {
1854
                // Used now: the newest, so the last to be dropped.
1855272×
                let _ = fs::File::options()
1856272×
                    .write(true)
1857272×
                    .open(&exact)
1858272×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1859272×
                f
1860
            }
18611713×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1862
        };
18631592×
        let total = f.metadata().ok()?.len();
18641592×
        let mut word = [0u8; 4];
18651592×
        f.read_exact(&mut word).ok()?;
18661592×
        let n = u32::from_le_bytes(word) as usize;
18671592×
        let mut head = vec![0u8; 32 * n + 64 + 8];
18681592×
        f.read_exact(&mut head).ok()?;
18691592×
        let heads: Vec<ChangeHash> = head[..32 * n]
18701592×
            .chunks_exact(32)
18711592×
            .map(|c| ObjectRef(c.try_into().unwrap()))
18721592×
            .collect();
18731592×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
18741592×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
18751592×
        let at = (4 + head.len()) as u64;
18761592×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
18770×
            return None;
18781592×
        }
1879
        // The front only: the files' histories after it are read, each
1880
        // checked by its own hash, when a command builds that file.
18811592×
        let mut front = vec![0u8; front_len as usize];
18821592×
        f.read_exact(&mut front).ok()?;
18831592×
        drop(reading);
18841592×
        let checking = crate::timing::phase("load:   of which checking the file");
18851592×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
18861592×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
18873184×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
18881592×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
18890×
            return None;
18901592×
        }
18911592×
        drop(checking);
18921592×
        let histories = crate::state::Histories::File(
18931592×
            std::sync::Arc::new(f),
18941592×
            at + front_len,
18951592×
            total - at - front_len,
18961592×
        );
18971592×
        Some((State::read_index_front(&front, histories).ok()?, heads))
18981985×
    }
1899
1900
    /// The changes of this workspace's state index (the closure of its
1901
    /// heads), read without the rest of the index.
1902
    #[allow(clippy::type_complexity)]
1903177×
    pub(crate) fn read_state_index_changes(
1904177×
        &self,
1905177×
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
1906
        use std::io::Read;
1907177×
        let _t = crate::timing::phase("load: state index changes");
1908177×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1909160×
        let mut word = [0u8; 4];
1910160×
        f.read_exact(&mut word).ok()?;
1911160×
        let n = u32::from_le_bytes(word) as usize;
1912
        // Heads, the two sums, the front's length, then the changes block.
1913160×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1914160×
        f.read_exact(&mut head).ok()?;
1915160×
        let heads: Vec<ChangeHash> = head[..32 * n]
1916160×
            .chunks_exact(32)
1917160×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1918160×
            .collect();
1919160×
        let sum = &head[32 * n..32 * n + 32];
1920160×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1921160×
        let mut changes = vec![0u8; 4 + len];
1922160×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1923160×
        f.read_exact(&mut changes[4..]).ok()?;
1924160×
        let checking = crate::timing::phase("load:   of which checking");
1925160×
        let mut h = blake3::Hasher::new();
1926160×
        h.update_rayon(&changes);
1927160×
        if h.finalize().as_bytes() != sum {
19280×
            return None;
1929160×
        }
1930160×
        drop(checking);
1931160×
        let _decoding = crate::timing::phase("load:   of which decoding");
1932160×
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
1933177×
    }
1934
1935
    /// Save `st`, the history-only state of `deps`, as this workspace's
1936
    /// state index; quietly nothing when it cannot be (it is only a cache).
1937400×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1938400×
        let _t = crate::timing::phase("write: state index");
1939400×
        let encoding = crate::timing::phase("write:   of which encoding");
1940400×
        let Some(body) = st.write_index() else {
19410×
            return;
1942
        };
1943400×
        drop(encoding);
1944
        #[cfg(test)]
1945216×
        assert_eq!(
1946216×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1947216×
            Some(body.clone()),
1948
            "a state index reads back as written"
1949
        );
1950400×
        let mut heads = st.maximal(deps);
1951400×
        heads.sort();
1952400×
        let mut w = crate::flat::Writer::default();
1953400×
        w.count(heads.len());
1954400×
        for h in &heads {
195517×
            w.object(h);
195617×
        }
1957
        // The body is the front's length, the front, then the files'
1958
        // histories, which carry their own hashes: the sums cover the
1959
        // front's changes block and the rest of the front.
1960400×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
1961400×
        let front = &body[8..8 + front_len];
1962400×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
1963800×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1964400×
        w.fixed(&sum(&front[..split]));
1965400×
        w.fixed(&sum(&front[split..]));
1966400×
        w.fixed(&body);
1967400×
        let path = self.state_index_path(&heads);
1968400×
        let _ = fs::create_dir_all(self.oxy.join("index"));
1969400×
        let _ = write_cache(&path, &w.0);
1970
        // The last two used: the index of a state moved away from stays for
1971
        // a move back. Older ones (and the unnamed one of before) go.
1972400×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
19731×
            let _ = fs::remove_file(old);
19741×
        }
1975400×
        let _ = fs::remove_file(
1976400×
            self.oxy
1977400×
                .join("index")
1978400×
                .join(format!("state-{}", self.workspace.to_hex())),
1979400×
        );
1980400×
    }
1981
19826×
    fn locks_dir(&self) -> PathBuf {
19836×
        self.oxy.join("locks")
19846×
    }
1985
1986
    /// Whether `path` is locked locally for editing (spec §18, advisory).
19873×
    pub fn is_locked(&self, path: &str) -> bool {
19883×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
19893×
    }
1990
1991
    /// Take the advisory local lock on a `lockable` file and make it writable.
19922×
    pub fn lock_path(&self, path: &str) -> Result<()> {
19932×
        let attrs = self.disk_attributes();
19942×
        if !attrs.lookup(path).lockable {
19951×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
19961×
        }
19971×
        fs::create_dir_all(self.locks_dir())?;
19981×
        write_atomic(
19991×
            &self.locks_dir().join(path.replace('/', "%2F")),
20001×
            std::process::id().to_string().as_bytes(),
20010×
        )?;
20021×
        set_readonly(&self.root.join(path), false)?;
20031×
        Ok(())
20042×
    }
2005
2006
    /// Release the local lock and make the file read-only again.
20071×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
20081×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
20091×
        if self.root.join(path).exists() {
20101×
            set_readonly(&self.root.join(path), true)?;
20110×
        }
20121×
        Ok(())
20131×
    }
2014
2015
    /// Whether a repository path is inside the sparse filter (spec §17).
201624298×
    pub fn in_scope(&self, path: &str) -> bool {
201724298×
        self.config.sparse_paths.is_empty()
201882×
            || self
201982×
                .config
202082×
                .sparse_paths
202182×
                .iter()
202299×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
202324298×
    }
2024
20251×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
20261×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
20271×
    }
2028
2029
    /// Walk the working copy; with a manifest, a file whose size and mtime
2030
    /// match it is not read: an opaque file yields its known blob, and a
2031
    /// text file whose recorded graph key equals its base graph's key in
2032
    /// `keys` (path → key) is marked unchanged; other text files are read
2033
    /// but keep their known hash. Files modified within two seconds of the
2034
    /// manifest are never trusted (a racy stat).
2035
    ///
2036
    /// `.oxyattributes` files are always read, since their content is
2037
    /// needed; and when any of them is not known unchanged (added, removed,
2038
    /// edited, or changed in the base), no text file is taken as unchanged,
2039
    /// because attributes decide how a file compares with the base.
2040
    ///
2041
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2042
    /// (the base state's files) that exists on disk is included even when
2043
    /// an ignore rule matches it, as in Git.
20441274×
    fn walk_working_copy_with(
20451274×
        &self,
20461274×
        cache: Option<&prompt::Manifest>,
20471274×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
20481274×
        keys: Option<&KeyOf>,
20491274×
    ) -> Result<BTreeMap<String, FsEntry>> {
2050
        let mut out: BTreeMap<String, FsEntry>;
20511274×
        let sparse = &self.config.sparse_paths;
20529099×
        let in_scope = |p: &str| {
20539099×
            sparse.is_empty()
20547×
                || sparse
20557×
                    .iter()
20567×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
20579099×
        };
20581274×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2059
        let walk::Listing {
20601274×
            files,
20611274×
            symlinks,
20621274×
            nested,
20631274×
            dirs,
20641274×
        } = match self.listing_cache.take() {
2065171×
            Some(l) => l,
2066
            // Ignore rules apply to untracked paths only, so the base's
2067
            // files are not matched against them (an added file is: a rule
2068
            // written after it was snapshotted leaves it out again).
20699111×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2070
        };
2071
        // A new file larger than the limit is left out and named, not taken
2072
        // in unseen (oxygen#98): a build's output or a downloaded image
2073
        // would otherwise be stored by the next status, kept by the
2074
        // operation log. Files tracked, or already in the working copy, stay.
20751274×
        let limit = self.config.max_new_file;
20761274×
        let mut skipped = Vec::new();
20771274×
        let files: Vec<_> = files
20781274×
            .into_iter()
207912072×
            .filter(|(rel, _, meta)| {
208012072×
                let new = !tracked.contains_key(rel)
20813114×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
208212072×
                if limit > 0 && new && meta.size > limit {
20833×
                    skipped.push((rel.clone(), meta.size));
20843×
                    return false;
208512069×
                }
208612069×
                true
208712072×
            })
20881274×
            .collect();
20891274×
        *self.skipped_large.borrow_mut() = skipped;
20901274×
        let keys = keys.filter(|k| {
209112057×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
20921271×
            let attrs_unchanged =
20931271×
                files
20941271×
                    .iter()
209512038×
                    .filter(|(r, _, _)| is_attributes(r))
20961271×
                    .all(|(rel, _, meta)| {
20979×
                        stat_cached(rel, meta, cache)
20989×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
20999×
                    });
21001271×
            let none_removed = tracked
21011271×
                .keys()
21029048×
                .filter(|r| is_attributes(r))
21031271×
                .all(|r| on_disk.contains(r.as_str()));
21041271×
            attrs_unchanged && none_removed
21051271×
        });
21061274×
        *self.walked_dirs.borrow_mut() =
21071274×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
21081274×
        drop(walk_phase);
21091274×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2110
        // Reading files is most of a walk's cost; do it in parallel.
2111
        {
2112
            use rayon::prelude::*;
21131274×
            let mut read: Vec<(String, FsEntry)> = files
21141274×
                .par_iter()
211512069×
                .map(|(rel, path, meta)| {
2116
                    // A key is worked out only for a file the manifest
2117
                    // knows with the same stat and a key of its own.
211812069×
                    let key = keys
211912069×
                        .filter(|_| !is_attributes(rel))
212012069×
                        .filter(|_| {
212112029×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
212212029×
                        })
212312069×
                        .and_then(|k| k(rel));
212412069×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
212512069×
                })
21261274×
                .collect::<Result<Vec<_>>>()?;
212712067×
            for (rel, e) in read.iter_mut() {
2128
                // A cached blob the store lost (gc, a partial clone): read the file after all.
212912067×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
21300×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
21310×
                    e.blob = None;
213212067×
                }
2133
            }
2134
            // The listing is in path order, so the map is built without
2135
            // searching.
21361273×
            out = read.into_iter().collect();
21371273×
            for (rel, target) in symlinks {
21382×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
21392×
            }
2140
        }
21411273×
        drop(_read_phase);
21421273×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2143
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2144
        // already tracked as subrepo nodes, they contribute their pin;
2145
        // unregistered ones are left alone.
21461273×
        let modules = self.modules_on_disk();
21471273×
        let removed = self.removed_subrepos();
21481273×
        for rel in &removed {
21493×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
21501×
                self.clear_removed_subrepo(rel);
21512×
            }
2152
        }
21531273×
        let mut untracked_nested = Vec::new();
21541273×
        for dir in nested {
215531×
            let rel = self.rel_path(&dir);
215631×
            if !self.in_scope(&rel) || removed.contains(&rel) {
21573×
                continue;
215828×
            }
215928×
            let registered = modules.entries.get(&rel);
216028×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2161
            {
21621×
                untracked_nested.push(rel);
21631×
                continue;
216427×
            }
216527×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
216627×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2167
        }
21681273×
        untracked_nested.sort();
21691273×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2170
        // Tracked paths the ignore rules hid.
21711273×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
217281×
            if !self.in_scope(rel) {
217310×
                continue;
217471×
            }
217571×
            let path = self.root.join(rel);
217671×
            if *kind == NodeKind::Subrepo {
21774×
                if removed.contains(rel) {
21782×
                    continue;
21792×
                }
21802×
                let present =
21812×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
21822×
                if present {
21830×
                    let pin = subrepos::read_pin(
21840×
                        &path,
21850×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
21860×
                    )?;
21870×
                    out.insert(
21880×
                        rel.clone(),
21890×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2190
                    );
21912×
                } else if let Some(b) = blob {
21922×
                    // Not cloned (or emptied): the pin stays as recorded, as a
21932×
                    // Git gitlink does when its directory is absent.
21942×
                    out.insert(
21952×
                        rel.clone(),
21962×
                        FsEntry {
21972×
                            blob: Some(*b),
21982×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
21992×
                        },
22002×
                    );
22012×
                }
22022×
                continue;
220367×
            }
220467×
            let Ok(meta) = fs::symlink_metadata(&path) else {
220567×
                continue;
2206
            };
22070×
            let ft = meta.file_type();
22080×
            if ft.is_symlink() {
22090×
                let target = fs::read_link(&path)?;
22100×
                out.insert(
22110×
                    rel.clone(),
22120×
                    FsEntry::new(
22130×
                        NodeKind::Symlink,
2214
                        false,
22150×
                        target.to_string_lossy().as_bytes().to_vec(),
2216
                    ),
2217
                );
22180×
            } else if ft.is_file() {
22190×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
22200×
                out.insert(rel.clone(), e);
22210×
            }
2222
        }
22231273×
        Ok(out)
22241274×
    }
2225
2226
    /// The entry for one regular file, read or served from the stat cache.
22270×
    fn file_entry(
22280×
        &self,
22290×
        rel: &str,
22300×
        path: &Path,
22310×
        meta: &walk::Stat,
22320×
        cache: Option<&prompt::Manifest>,
22330×
    ) -> Result<FsEntry> {
22340×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
22350×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
22360×
            e.content = std::sync::Arc::new(fs::read(path)?);
22370×
            e.blob = None;
22380×
        }
22390×
        Ok(e)
22400×
    }
2241
2242
    /// The non-directory paths of a snapshot with their kinds, for the
2243
    /// walker's `tracked` set.
22442×
    pub(crate) fn tracked_kinds(
22452×
        snapshot: &Snapshot,
22462×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
22472×
        snapshot
22482×
            .files
22492×
            .iter()
225012×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
22518×
            .map(|(p, f)| {
22528×
                let blob = match &f.content {
22534×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
22544×
                    _ => None,
2255
                };
22568×
                (p.clone(), (f.kind, blob))
22578×
            })
22582×
            .collect()
22592×
    }
2260
2261
    /// A path under the root as a `/`-separated relative string.
226270×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
226370×
        path.strip_prefix(&self.root)
226470×
            .unwrap_or(path)
226570×
            .components()
2266134×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
226770×
            .collect::<Vec<_>>()
226870×
            .join("/")
226970×
    }
2270
}
2271
2272
impl Repo {
2273
    /// Changes reachable from the bookmark and the working copy, newest first.
227495×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
227595×
        let heads = self.bookmark_heads()?;
227695×
        if self.bare {
22771×
            return self.log_state(&heads);
227894×
        }
227994×
        let (wc_hash, wc) = self.working_copy()?;
228094×
        let mut all = heads.clone();
228194×
        all.push(wc_hash);
228294×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
228394×
        let mut entries: Vec<LogEntry> = Vec::new();
2284
        // A shallow clone knows changes beyond its boundary from a
2285
        // checkpoint's metadata only: its log comes from the state.
228694×
        let metas = if self.is_shallow() {
22871×
            self.load_state_history(&all)?
22881×
                .changes()
22899×
                .map(|(h, m)| (*h, m.clone()))
22901×
                .collect()
2291
        } else {
2292
            // The working copy's change is in hand, and is never in the
2293
            // state index: its metadata is not looked up again.
229493×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
229593×
            below.extend(wc.deps.iter().copied());
229693×
            let _t = crate::timing::phase("log: metadata");
229793×
            let mut metas = self.metas_of(&below)?;
2298325×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
229993×
                // First, where the log puts it, so the order may hold.
230093×
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
230193×
            }
230293×
            metas
2303
        };
230494×
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2305427×
            hash: h,
2306427×
            change: meta,
2307427×
            is_working_copy: h == wc_hash,
2308427×
            is_head: head_set.contains(&h),
2309427×
        }));
231094×
        let _sorting = crate::timing::phase("log: sort");
2311
        // The hash makes the order total, so an unstable sort gives the same.
2312
        // From the state index the order already holds (oxygen#94).
2313708×
        let order = |a: &LogEntry, b: &LogEntry| {
2314708×
            b.is_working_copy
2315708×
                .cmp(&a.is_working_copy)
2316708×
                .then(crate::state::log_order(
2317708×
                    (&a.hash, &a.change.hlc),
2318708×
                    (&b.hash, &b.change.hlc),
2319
                ))
2320708×
        };
2321188×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
232253×
            entries.sort_unstable_by(order);
232353×
        }
232494×
        Ok(entries)
232595×
    }
2326
2327
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2328
    /// count, for paginated views.
23290×
    pub fn log_window(
23300×
        &self,
23310×
        heads: &[ChangeHash],
23320×
        offset: usize,
23330×
        limit: usize,
23340×
    ) -> Result<(Vec<LogEntry>, usize)> {
23350×
        let all = self.log_state(heads)?;
23360×
        let total = all.len();
23370×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
23380×
    }
2339
2340
    /// The log of the state with these heads, newest first, with no working
2341
    /// copy involved (for hosted repositories and any explicit state).
234210×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2343
        // The log needs change metadata only: neither graphs nor the tree.
234410×
        if self.is_shallow() {
23450×
            return Ok(self.log_of(&self.load_state_history(heads)?));
234610×
        }
234710×
        let metas = self.metas_of(heads)?;
234810×
        let depended: BTreeSet<ChangeHash> = metas
234910×
            .iter()
235030×
            .flat_map(|(_, m)| m.deps.iter().copied())
235110×
            .collect();
235210×
        let mut entries: Vec<LogEntry> = metas
235310×
            .into_iter()
235410×
            .map(|(h, meta)| LogEntry {
235530×
                hash: h,
235630×
                is_head: !depended.contains(&h),
235730×
                change: meta,
2358
                is_working_copy: false,
235930×
            })
236010×
            .collect();
236138×
        let order = |a: &LogEntry, b: &LogEntry| {
236238×
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
236338×
        };
236412×
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
23654×
            entries.sort_unstable_by(order);
23666×
        }
236710×
        Ok(entries)
236810×
    }
2369
2370
    /// Every change of the state with these heads and its metadata, read
2371
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2372
    /// a shallow clone's boundary is left out.
2373177×
    pub fn metas_of(
2374177×
        &self,
2375177×
        heads: &[ChangeHash],
2376177×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2377177×
        let boundary = self.boundary();
2378
        // The state index holds the metadata of its heads' closure: a
2379
        // change found there is not read from the store (a change object
2380
        // can be as large as the tree it adds).
2381177×
        let read = self.read_state_index_changes();
2382
        // Every one of `heads` in the index, and every head of the index
2383
        // among them: their closure is the index's changes, all of them
2384
        // (it is closed), and no walk is needed to find it.
2385177×
        if let Some((index_heads, all)) = &read {
2386160×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2387160×
            let in_index = || {
2388160×
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2389160×
                    index_heads.iter().collect();
2390
                // Usually the heads asked are the index's: no set of all.
2391160×
                heads.iter().all(|h| index_heads.contains(h)) || {
2392160×
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2393160×
                        all.iter().map(|(h, _)| h).collect();
2394160×
                    heads.iter().all(|h| all.contains(h))
2395
                }
2396160×
            };
2397160×
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
23980×
                let (_, all) = read.expect("matched above");
2399
                #[cfg(test)]
2400
                {
2401
                    // The walk the shortcut saves finds the same changes.
24020×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
24030×
                    let mut stack = heads.to_vec();
24040×
                    while let Some(h) = stack.pop() {
24050×
                        if seen.insert(h) {
24060×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
24070×
                        }
2408
                    }
24090×
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
2410
                }
24110×
                return Ok(all);
2412160×
            }
241317×
        }
2414177×
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2415177×
            read.map(|(_, all)| all.into_iter().collect());
2416177×
        let _walk = crate::timing::phase("metadata: walk");
2417177×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2418177×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2419177×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2420177×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
24211277×
        while let Some(h) = stack.pop() {
24221100×
            if !seen.insert(h) {
2423461×
                continue;
2424639×
            }
2425
            // Taken out of the index's map, each once: not copied.
2426639×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2427
                #[cfg(test)]
24280×
                assert_eq!(
2429
                    meta,
24300×
                    self.store.get_change_meta(&h)?,
2431
                    "the state index holds a change's metadata"
2432
                );
24330×
                stack.extend(meta.deps.iter().copied());
24340×
                out.push((h, meta));
24350×
                continue;
2436639×
            }
2437639×
            let started = std::time::Instant::now();
2438639×
            let meta = match self.store.get_change_meta(&h) {
2439639×
                Ok(m) => m,
24400×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
24410×
                Err(e) => return Err(e.into()),
2442
            };
2443639×
            stored += 1;
2444639×
            from_store += started.elapsed();
2445639×
            stack.extend(meta.deps.iter().copied());
2446639×
            out.push((h, meta));
2447
        }
2448177×
        if stored > 0 && crate::timing::enabled() {
24490×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2450177×
        }
2451177×
        Ok(out)
2452177×
    }
2453
2454
    /// The log of a state already loaded, newest first.
2455
    /// The history of lines `first..=last` (1-based) of `path` in the
2456
    /// state `heads` make (spec §27): every change that inserted or
2457
    /// deleted one of their atoms, or an atom deleted from between them,
2458
    /// newest first. Exact, as atoms keep their identity across edits.
24596×
    pub fn line_history(
24606×
        &self,
24616×
        heads: &[ChangeHash],
24626×
        path: &str,
24636×
        first: usize,
24646×
        last: usize,
24656×
    ) -> Result<Vec<LogEntry>> {
24666×
        if first == 0 || last < first {
24671×
            return fail(format!(
2468
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2469
            ));
24705×
        }
24715×
        let mut state = self.load_state_history(heads)?;
24725×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
24731×
            return fail(format!("{path} is not in that state"));
2474
        };
24754×
        self.load_graphs_of(&mut state, &[node])?;
24764×
        let live = state.live_lines(&node);
24774×
        if last > live.len() {
24781×
            return fail(format!(
2479
                "{path} has {} lines; asked for {first},{last}",
24801×
                live.len()
2481
            ));
24823×
        }
24833×
        let Some(g) = state.file(&node) else {
24840×
            return fail(format!("{path} is not a text file"));
2485
        };
24863×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
24873×
        let touched = g.touching(&atoms);
24883×
        Ok(self
24893×
            .log_of(&state)
24903×
            .into_iter()
249113×
            .filter(|e| touched.contains(&e.hash))
24923×
            .collect())
24936×
    }
2494
24958×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
24968×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
24978×
        let mut entries: Vec<LogEntry> = state
24988×
            .changes()
24998×
            .map(|(h, meta)| LogEntry {
250031×
                hash: *h,
250131×
                change: meta.clone(),
2502
                is_working_copy: false,
250331×
                is_head: head_set.contains(h),
250431×
            })
25058×
            .collect();
250636×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
25078×
        entries
25088×
    }
2509
2510
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2511
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2512
    /// (`resolve_change`).
251367×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
251467×
        let view = self.view()?;
251567×
        if let Some(st) = view.bookmarks.get(spec) {
251639×
            return Ok(self.store.get_state(st)?.heads);
251728×
        }
251828×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
25192×
            return Ok(self.store.get_state(&st)?.heads);
252026×
        }
252126×
        if let Some(heads) = self.tag_heads(spec)? {
25222×
            return Ok(heads);
252324×
        }
252424×
        Ok(vec![self.resolve_change(spec)?])
252567×
    }
2526
2527
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2528
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
252936×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
253036×
        if spec == "@" {
25310×
            return Ok(self.working_copy()?.0);
253236×
        }
253336×
        let view = self.view()?;
253436×
        let named = match view.bookmarks.get(spec) {
25351×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
253635×
            None => match remote_bookmark(&view, spec) {
25371×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
253834×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2539
            },
2540
        };
254136×
        if let Some((kind, heads)) = named {
25423×
            return match heads.len() {
25433×
                1 => Ok(heads[0]),
25440×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2545
            };
254633×
        }
254733×
        if spec.is_empty() || spec == "#" {
25480×
            return fail("empty change specifier");
254933×
        }
255033×
        let entries = self.log()?;
2551
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2552
        // cannot be a ChangeId, which has 32 (oxygen#103).
255333×
        let full_hash =
2554128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
255533×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
255627×
            entries
255727×
                .iter()
2558109×
                .filter(|e| e.hash.starts_with_hex(hp))
255927×
                .collect()
2560
        } else {
25616×
            entries
25626×
                .iter()
256321×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
25646×
                .collect()
2565
        };
256633×
        match matches.len() {
256728×
            1 => Ok(matches[0].hash),
25685×
            0 => match self.resolve_in_remotes(spec)? {
25691×
                Some(h) => Ok(h),
25704×
                None => fail(format!("no change matches {spec:?}")),
2571
            },
2572
            _ => {
25730×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
25740×
                if ids.len() == 1 {
25750×
                    fail(format!(
2576
                        "change {spec} is divergent: {} variants",
25770×
                        matches.len()
2578
                    ))
2579
                } else {
25800×
                    fail(format!("{spec:?} is ambiguous"))
2581
                }
2582
            }
2583
        }
258436×
    }
2585
2586
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2587
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2588
    /// `None` when none matches, or more than one.
25895×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
25905×
        let view = self.view()?;
25915×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
25925×
        for bookmarks in view.remotes.values() {
25933×
            for st in bookmarks.values() {
25943×
                let heads = self.store.get_state(st)?.heads;
25957×
                for e in self.log_state(&heads)? {
25967×
                    let hit = match spec.strip_prefix('#') {
25972×
                        Some(hp) => e.hash.starts_with_hex(hp),
25985×
                        None => e.change.change_id.starts_with_hex(spec),
2599
                    };
26007×
                    if hit {
26011×
                        found.insert(e.hash);
26026×
                    }
2603
                }
2604
            }
2605
        }
26065×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
26075×
    }
2608
2609
    /// Where a change is when no local bookmark or the working copy holds
2610
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2611
    /// it is held locally, or nowhere.
26123×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
26136×
        if self.log()?.iter().any(|e| e.hash == *hash) {
26142×
            return Ok(None);
26151×
        }
26161×
        let view = self.view()?;
26171×
        for (remote, bookmarks) in &view.remotes {
26181×
            for (name, st) in bookmarks {
26191×
                let heads = self.store.get_state(st)?.heads;
26201×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
26211×
                    return Ok(Some(format!("{remote}/{name}")));
26220×
                }
2623
            }
2624
        }
26250×
        Ok(None)
26263×
    }
2627
2628
    /// Human-readable description of what a change does, with line content.
26293×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
26303×
        let change = self.store.get_change(hash)?;
26313×
        let (base, base_snapshot) = self.change_base(&change)?;
26323×
        Ok(render_change(&change, &base, &base_snapshot))
26333×
    }
2634
2635
    /// The base state of `change` (its dependencies) and its rendering, as
2636
    /// much as showing the change needs: the whole tree, and the graphs and
2637
    /// contents of the files the change edits. Other text files are left
2638
    /// unrendered ([`Snapshot::unrendered`]).
26396×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
26406×
        let base = self.load_state_history(&change.deps)?;
26416×
        self.render_base_for(change, base)
26426×
    }
2643
2644
    /// The base for showing `change` alone: the graphs of the files it
2645
    /// edits built, and the base's tree with no file rendered, which is
2646
    /// all [`render_change`](snapshot::render_change) and
2647
    /// [`diff_files_of`](snapshot::diff_files_of) read.
26483×
    pub(crate) fn tree_base_for(
26493×
        &self,
26503×
        change: &Change,
26513×
        mut base: State,
26523×
    ) -> Result<(State, Snapshot)> {
26533×
        let _t = crate::timing::phase("diff: the base's tree");
26543×
        let edited: std::collections::HashSet<NodeId> =
26558×
            change.edits.iter().map(|e| e.node()).collect();
26563×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
26573×
        self.load_graphs_of(&mut base, &nodes)?;
26583×
        let snapshot = Snapshot {
26593×
            tree: base.tree().view(),
26603×
            files: BTreeMap::new(),
26613×
            unrendered: BTreeSet::new(),
26623×
        };
26633×
        Ok((base, snapshot))
26643×
    }
2665
2666
    /// [`Repo::change_base`] with the base already loaded (the working
2667
    /// copy's comes from the state index).
2668206×
    pub(crate) fn render_base_for(
2669206×
        &self,
2670206×
        change: &Change,
2671206×
        mut base: State,
2672206×
    ) -> Result<(State, Snapshot)> {
2673206×
        let _t = crate::timing::phase("diff: render the base");
2674206×
        let edited: std::collections::HashSet<NodeId> =
2675371×
            change.edits.iter().map(|e| e.node()).collect();
2676206×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2677206×
        self.load_graphs_of(&mut base, &nodes)?;
2678206×
        let snapshot = {
2679206×
            let _t = crate::timing::phase("diff:   of which materialize");
2680206×
            base.materialize_nodes(&edited)
2681
        };
2682206×
        Ok((base, snapshot))
2683206×
    }
2684
}
2685
26860×
fn remove_any(path: &Path) -> std::io::Result<()> {
26870×
    let m = fs::symlink_metadata(path)?;
26880×
    if m.is_dir() {
26890×
        fs::remove_dir_all(path)
2690
    } else {
26910×
        fs::remove_file(path)
2692
    }
26930×
}
2694
26955×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
26965×
    let mut perms = fs::metadata(path)?.permissions();
26975×
    perms.set_readonly(readonly);
26985×
    fs::set_permissions(path, perms)
26995×
}
2700
2701
#[cfg(unix)]
27025857×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2703
    use std::os::unix::fs::PermissionsExt;
27045857×
    let mut perms = fs::metadata(path)?.permissions();
27055857×
    let mode = perms.mode();
27065857×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
27075857×
    if want != mode {
27084×
        perms.set_mode(want);
27094×
        fs::set_permissions(path, perms)?;
27105853×
    }
27115857×
    Ok(())
27125857×
}
2713
#[cfg(not(unix))]
2714
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2715
    Ok(())
2716
}
2717
2718
#[cfg(unix)]
271916291×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2720
    use std::os::unix::fs::PermissionsExt;
272116291×
    m.permissions().mode() & 0o111 != 0
272216291×
}
2723
#[cfg(not(unix))]
2724
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2725
    false
2726
}
2727
272812829×
fn op_ref(k: OpKey) -> OpRef {
272912829×
    OpRef {
273012829×
        change: k.0,
273112829×
        index: k.1,
273212829×
    }
273312829×
}
2734
27356039×
fn split_path(path: &str) -> (&str, &str) {
27366039×
    match path.rfind('/') {
27375059×
        Some(i) => (&path[..i], &path[i + 1..]),
2738980×
        None => ("", path),
2739
    }
27406039×
}
2741
2742
/// Whether `rel` is an attributes file (spec §7.6).
274367241×
fn is_attributes(rel: &str) -> bool {
274467241×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
274567241×
}
2746
2747
/// The manifest entry for `rel` when its size and mtime match it outside
2748
/// the racy window.
274924107×
fn stat_cached<'m>(
275024107×
    rel: &str,
275124107×
    meta: &walk::Stat,
275224107×
    cache: Option<&'m prompt::Manifest>,
275324107×
) -> Option<&'m prompt::ManifestEntry> {
275424107×
    let m = cache?;
275519159×
    let e = m.entries.get(rel)?;
275617814×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
275717814×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
275824107×
}
2759
2760
/// Read one working-copy file, or serve it from the stat cache (spec
2761
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2762
/// an opaque file is not read at all (its stored blob stands in), and a
2763
/// text file the manifest recorded equal to a base graph whose key is
2764
/// `key`, the key the base has now, is not read either: equal keys mean
2765
/// equal renderings, so it still equals the base. Touches no repository
2766
/// state, so the walk runs it in parallel; the caller checks that a cached
2767
/// blob is still in the store.
276812069×
fn read_file_entry(
276912069×
    rel: &str,
277012069×
    path: &Path,
277112069×
    meta: &walk::Stat,
277212069×
    cache: Option<&prompt::Manifest>,
277312069×
    key: Option<[u8; 32]>,
277412069×
) -> Result<FsEntry> {
277512069×
    let exec = meta.exec;
277612069×
    let stat = Some((meta.size, meta.mtime_ns));
277712069×
    let mut e = match stat_cached(rel, meta, cache) {
27784249×
        Some(e) if e.blob.is_some() => FsEntry {
27791×
            blob: e.blob,
27801×
            content_hash: Some(e.hash),
27811×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27821×
        },
27834248×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
27844243×
            content_hash: Some(e.hash),
27854243×
            unchanged: true,
27864243×
            graph_key: e.graph,
27874243×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27884243×
        },
27895×
        Some(e) => FsEntry {
27905×
            content_hash: Some(e.hash),
27915×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2792
        },
27937820×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2794
    };
2795
    // The stat the manifest records: taken before the read, so a file that
2796
    // changes meanwhile is read again next time.
279712068×
    e.stat = stat;
279812068×
    Ok(e)
279912069×
}
2800
2801
/// Two maps side by side in key order: each key of either, with its value
2802
/// in each. Linear, with no lookups, for maps of a whole tree.
28032557×
pub(crate) fn join<'a, A, B>(
28042557×
    a: &'a BTreeMap<String, A>,
28052557×
    b: &'a BTreeMap<String, B>,
28062557×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
28072557×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
280835616×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
28092557×
        (None, None) => None,
28102936×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
28115819×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
281224304×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2813330×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2814302×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2815
            std::cmp::Ordering::Equal => {
281623672×
                let (k, va) = a.next()?;
281723672×
                let (_, vb) = b.next()?;
281823672×
                Some((k, Some(va), Some(vb)))
2819
            }
2820
        },
282135616×
    })
28222557×
}
2823
2824
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2825
/// lookups.
28261274×
pub(crate) fn missing_from<'a, A, B>(
28271274×
    a: &'a BTreeMap<String, A>,
28281274×
    b: &BTreeMap<String, B>,
28291274×
) -> Vec<(&'a String, &'a A)> {
28301274×
    let mut keys = b.keys().peekable();
28311274×
    a.iter()
28329058×
        .filter(|(k, _)| {
283317444×
            while keys.next_if(|kb| *kb < *k).is_some() {}
28349058×
            keys.peek() != Some(k)
28359058×
        })
28361274×
        .collect()
28371274×
}