OXYGENHUB

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

1576 of 1751 lines run, 387 of 618 functions · run #261 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.
752341×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762341×
    let Some(url) = &config.storage_url else {
772336×
        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×
    )?)
1002341×
}
101
102151×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103151×
    Err(RepoError::Msg(s.into()))
104151×
}
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, 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};
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.
1643804×
pub(crate) fn name_file(name: &str) -> String {
1653804×
    name.replace('%', "%25").replace('/', "%2F")
1663804×
}
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
1736556×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1746556×
    Ok(crate::durable::write_atomic(path, data)?)
1756556×
}
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
1912632×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1922632×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1932632×
    fs::write(&tmp, data)?;
1942632×
    fs::rename(&tmp, path)?;
1952632×
    Ok(())
1962632×
}
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 {
23622426×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
23722426×
        FsEntry {
23822426×
            kind,
23922426×
            exec,
24022426×
            content: std::sync::Arc::new(content),
24122426×
            blob: None,
24222426×
            content_hash: None,
24322426×
            unchanged: false,
24422426×
            graph_key: None,
24522426×
            stat: None,
24622426×
        }
24722426×
    }
248
}
249
250
pub struct Repo {
251
    /// Oxygen-pinned subrepos skipped by the running Git export.
252
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
253
    /// The manifest as last read, with the file identity it was read from,
254
    /// so one command parses it once (see `read_manifest`).
255
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
256
    /// A listing of the working copy left by a failed clean check, for the
257
    /// snapshot that follows it to reuse; taken by the next walk and
258
    /// dropped whenever the manifest is written.
259
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
260
    /// The nested repositories the last walk left out, being neither
261
    /// registered nor tracked subrepos (oxygen#43).
262
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
263
    root: PathBuf,
264
    oxy: PathBuf,
265
    store: Store,
266
    workspace: WorkspaceId,
267
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
268
    bare: bool,
269
    keys_dir: PathBuf,
270
    user_config: PathBuf,
271
    pub config: Config,
272
    /// What the working copy's file system can represent (spec §7.7).
273
    platform: crate::portable::Platform,
274
    /// The encodings of the changes last read for their inline inserts,
275
    /// oldest first.
276
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
277
    /// `--at-op`: read the repository as it was after this operation;
278
    /// recording an operation is refused.
279
    at_op: Option<ObjectRef>,
280
    /// The directories (with their times) and nested repositories of the
281
    /// last walk, for the manifest written from it.
282
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
283
    /// The directories a manifest check listed, for its restamp only.
284
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
285
}
286
287
/// A walk's directories with their times, and its nested repositories.
288
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
289
290
/// Marker file of a bare repository, inside `.oxy/`.
291
const BARE_MARKER: &str = "bare";
292
/// Marker of a hosted repository that has no id yet: the first push binds
293
/// it to the pusher's id (spec §16.1).
294
const UNBOUND_MARKER: &str = "unbound";
295
296
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
297
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
2987252×
pub fn default_home() -> PathBuf {
2997252×
    if let Ok(h) = std::env::var("OXY_HOME") {
3007249×
        return PathBuf::from(h);
3013×
    }
3023×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3030×
        return PathBuf::from(x).join("oxy");
3043×
    }
305
    // Windows has no HOME as a rule: the roaming profile's application
306
    // data, as Windows programs keep theirs.
307
    #[cfg(windows)]
308
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
309
        return PathBuf::from(d).join("oxy");
310
    }
3113×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3123×
    PathBuf::from(home).join(".config").join("oxy")
3137252×
}
314
3152341×
pub fn default_keys_dir() -> PathBuf {
3162341×
    default_home().join("keys")
3172341×
}
318
3194682×
pub fn default_user_config() -> PathBuf {
3204682×
    default_home().join("config.toml")
3214682×
}
322
323
/// Where `create_identity` records the author.
324
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
325
pub enum IdentityScope {
326
    /// The user file: every repository of this user signs with it.
327
    User,
328
    /// This repository only.
329
    Repo,
330
}
331
332
impl Repo {
333
    // ------------------------------------------------------------ lifecycle
334
335205×
    pub fn init(root: &Path) -> Result<Repo> {
336205×
        let mut id = [0u8; 16];
337205×
        rand::rngs::OsRng.fill_bytes(&mut id);
338205×
        Self::init_with_id(root, id)
339205×
    }
340
341
    /// Initialize a repository with a given repository ID (clones share the
342
    /// ID of their origin, spec §14.4).
343440×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
344440×
        Self::init_on(root, id, None)
345440×
    }
346
347
    /// A new repository with a fresh id, bare or not, on `storage` or in
348
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
34912×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
35012×
        let mut id = [0u8; 16];
35112×
        rand::rngs::OsRng.fill_bytes(&mut id);
35212×
        if bare {
3530×
            Self::init_bare_on(root, id, storage)
354
        } else {
35512×
            Self::init_on(root, id, storage)
356
        }
35712×
    }
358
359
    /// Initialize a repository whose objects and operation head are kept
360
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
361455×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
362455×
        fs::create_dir_all(root)?;
363455×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
364455×
        let oxy = root.join(OXY_DIR);
365455×
        if oxy.exists() {
3661×
            return fail(format!("{} is already an oxy repository", root.display()));
367454×
        }
368454×
        fs::create_dir_all(oxy.join("ops"))?;
369454×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
370454×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
371454×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
372454×
        if let Some(url) = storage {
3733×
            config.set("storage.url", url)?;
374451×
        }
375454×
        config.save(&oxy.join("config"))?;
376454×
        let workspace = WorkspaceId::random();
377454×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
378454×
        let store = open_objects(&oxy, &config)?;
379453×
        let repo = Repo {
380453×
            last_change: Default::default(),
381453×
            at_op: None,
382453×
            walked_dirs: Default::default(),
383453×
            listed_dirs: Default::default(),
384453×
            git_export_skipped: Default::default(),
385453×
            manifest_cache: Default::default(),
386453×
            listing_cache: Default::default(),
387453×
            untracked_nested: Default::default(),
388453×
            root,
389453×
            oxy,
390453×
            store,
391453×
            workspace,
392453×
            bare: false,
393453×
            keys_dir: default_keys_dir(),
394453×
            platform: crate::portable::Platform::current(),
395453×
            user_config: default_user_config(),
396453×
            config,
397453×
        };
398453×
        repo.register_workspace(&workspace, &repo.root)?;
399
400453×
        let wc = repo.new_working_copy(vec![], "");
401453×
        let wc_hash = repo.store.put_change(&wc)?;
402453×
        let mut view = View::default();
403453×
        view.bookmarks.insert(
404453×
            repo.config.bookmark.clone(),
405453×
            repo.store.put_state(&StateObject::new(vec![]))?,
406
        );
407453×
        view.workspaces.insert(workspace, wc_hash);
408453×
        repo.record_op(&[], "oxy init", view)?;
409451×
        Ok(repo)
410455×
    }
411
412
    /// Create a bare repository: an object store, operation log and
413
    /// references with no workspace and no working copy, for hosting
414
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4155×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4165×
        let mut id = [0u8; 16];
4175×
        rand::rngs::OsRng.fill_bytes(&mut id);
4185×
        Self::init_bare_with_id(root, id)
4195×
    }
420
42137×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
42237×
        Self::init_bare_on(root, id, None)
42337×
    }
424
425
    /// [`Repo::init_on`] for a bare repository.
42637×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
42737×
        fs::create_dir_all(root)?;
42837×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
42937×
        let oxy = root.join(OXY_DIR);
43037×
        if oxy.exists() {
4310×
            return fail(format!("{} is already an oxy repository", root.display()));
43237×
        }
43337×
        fs::create_dir_all(oxy.join("ops"))?;
43437×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
43537×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
43637×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
43737×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
43837×
        if let Some(url) = storage {
4390×
            config.set("storage.url", url)?;
44037×
        }
44137×
        config.save(&oxy.join("config"))?;
44237×
        let store = open_objects(&oxy, &config)?;
44337×
        let repo = Repo {
44437×
            last_change: Default::default(),
44537×
            at_op: None,
44637×
            walked_dirs: Default::default(),
44737×
            listed_dirs: Default::default(),
44837×
            git_export_skipped: Default::default(),
44937×
            manifest_cache: Default::default(),
45037×
            listing_cache: Default::default(),
45137×
            untracked_nested: Default::default(),
45237×
            root,
45337×
            oxy,
45437×
            store,
45537×
            workspace: WorkspaceId::ZERO,
45637×
            bare: true,
45737×
            keys_dir: default_keys_dir(),
45837×
            platform: crate::portable::Platform::current(),
45937×
            user_config: default_user_config(),
46037×
            config,
46137×
        };
46237×
        let mut view = View::default();
46337×
        view.bookmarks.insert(
46437×
            repo.config.bookmark.clone(),
46537×
            repo.store.put_state(&StateObject::new(vec![]))?,
466
        );
46737×
        repo.record_op(&[], "oxy init --bare", view)?;
46837×
        Ok(repo)
46937×
    }
470
471
    /// A bare repository with no id yet. Its `id()` is all zero until the
472
    /// first push binds it (`bind_id`), so an existing repository can be
473
    /// pushed to a freshly created hosted one and keep its identity.
47411×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
47511×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
47611×
        fs::remove_file(repo.oxy.join("id"))?;
47711×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
47811×
        Ok(repo)
47911×
    }
480
4813331×
    pub fn is_unbound(&self) -> bool {
4823331×
        self.oxy.join(UNBOUND_MARKER).is_file()
4833331×
    }
484
485
    /// Give an unbound repository its id.
48610×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
48710×
        if !self.is_unbound() {
4880×
            return fail("this repository already has an id");
48910×
        }
49010×
        if id == [0; 16] {
4910×
            return fail("a repository id cannot be all zero");
49210×
        }
49310×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
49410×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
49510×
        Ok(())
49610×
    }
497
498
    /// Whether this repository has no working copy (`init_bare`).
49975×
    pub fn is_bare(&self) -> bool {
50075×
        self.bare
50175×
    }
502
503
    /// Open the repository containing `start` (searching upwards).
5041850×
    pub fn open(start: &Path) -> Result<Repo> {
5051850×
        let start = start.canonicalize()?;
5061850×
        let mut dir: Option<&Path> = Some(&start);
5071850×
        while let Some(d) = dir {
5081850×
            let oxy = d.join(OXY_DIR);
5091850×
            if oxy.is_file() {
510
                // A secondary workspace (spec §12.2): the file points at the repository.
5116×
                let text = fs::read_to_string(&oxy)?;
5126×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5130×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
514
                };
5156×
                let format = fs::read_to_string(shared.join("format"))?;
5166×
                if format != FORMAT_LINE {
5170×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5186×
                }
5196×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5206×
                let store = open_objects(&shared, &config)?;
5216×
                let mut repo = Repo {
5226×
                    last_change: Default::default(),
5236×
                    at_op: None,
5246×
                    walked_dirs: Default::default(),
5256×
                    listed_dirs: Default::default(),
5266×
                    git_export_skipped: Default::default(),
5276×
                    manifest_cache: Default::default(),
5286×
                    listing_cache: Default::default(),
5296×
                    untracked_nested: Default::default(),
5306×
                    root: d.to_path_buf(),
5316×
                    oxy: shared,
5326×
                    store,
5336×
                    workspace,
5346×
                    bare: false,
5356×
                    keys_dir: default_keys_dir(),
5366×
                    platform: crate::portable::Platform::current(),
5376×
                    user_config: default_user_config(),
5386×
                    config,
5396×
                };
5406×
                repo.apply_workspace_bookmark();
5416×
                return Ok(repo);
5421844×
            }
5431844×
            if oxy.is_dir() {
5441844×
                let format = fs::read_to_string(oxy.join("format"))?;
5451844×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5461844×
                let bare = oxy.join(BARE_MARKER).is_file();
5471844×
                let workspace = if bare {
548141×
                    WorkspaceId::ZERO
549
                } else {
5501703×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5511703×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
552
                };
5531844×
                let store = open_objects(&oxy, &config)?;
5541844×
                let mut repo = Repo {
5551844×
                    last_change: Default::default(),
5561844×
                    at_op: None,
5571844×
                    walked_dirs: Default::default(),
5581844×
                    listed_dirs: Default::default(),
5591844×
                    git_export_skipped: Default::default(),
5601844×
                    manifest_cache: Default::default(),
5611844×
                    listing_cache: Default::default(),
5621844×
                    untracked_nested: Default::default(),
5631844×
                    root: d.to_path_buf(),
5641844×
                    oxy,
5651844×
                    store,
5661844×
                    workspace,
5671844×
                    bare,
5681844×
                    keys_dir: default_keys_dir(),
5691844×
                    platform: crate::portable::Platform::current(),
5701844×
                    user_config: default_user_config(),
5711844×
                    config,
5721844×
                };
5731844×
                if !bare {
5741703×
                    repo.apply_workspace_bookmark();
5751703×
                }
5761844×
                if format == FORMAT1_LINE {
5771×
                    repo.migrate_format1()?;
5781843×
                } else if format != FORMAT_LINE {
5790×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5801843×
                }
5811844×
                return Ok(repo);
5820×
            }
5830×
            dir = d.parent();
584
        }
5850×
        fail(format!(
586
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
5870×
            start.display()
588
        ))
5891850×
    }
590
591
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
592
    /// into format 2, where each bookmark names a `state` object.
5931×
    fn migrate_format1(&self) -> Result<()> {
5941×
        let (head, version) = self.read_head()?;
595
        // Collect the chain root-first.
5961×
        let mut chain: Vec<Format1Op> = Vec::new();
5971×
        let mut cur = Some(head);
5983×
        while let Some(r) = cur {
5992×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
6002×
            cur = op.parents.first().copied();
6012×
            chain.push(op);
602
        }
6031×
        chain.reverse();
6041×
        let mut new_parent: Option<ObjectRef> = None;
6052×
        for old in chain {
6062×
            let mut view = View::default();
6072×
            for (name, heads) in &old.view.bookmarks {
6082×
                view.bookmarks.insert(
6092×
                    name.clone(),
6102×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
611
                );
612
            }
6132×
            view.workspaces = old.view.workspaces.clone();
6142×
            let op = Op {
6152×
                parents: new_parent.into_iter().collect(),
6162×
                hlc: old.hlc,
6172×
                command: old.command,
6182×
                view,
6192×
            };
6202×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
621
        }
6221×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6230×
            return fail("the operation log changed while it was rewritten; run the command again");
6241×
        }
6251×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6261×
        Ok(())
6271×
    }
628
629
    /// Pack automatically once many loose objects have accumulated.
630600×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
631600×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6320×
            self.store.pack_loose()?;
6330×
            self.store.merge_packs()?;
634600×
        }
635600×
        Ok(())
636600×
    }
637
638
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6393062×
    pub fn id(&self) -> Result<[u8; 16]> {
6403062×
        if self.is_unbound() {
64116×
            return Ok([0; 16]);
6423046×
        }
6433046×
        let path = self.oxy.join("id");
6443046×
        match fs::read_to_string(&path) {
6453046×
            Ok(h) => hex::decode(h.trim())
6463046×
                .ok()
6473046×
                .and_then(|v| v.try_into().ok())
6483046×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6490×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6500×
                let mut id = [0u8; 16];
6510×
                rand::rngs::OsRng.fill_bytes(&mut id);
6520×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6530×
                Ok(id)
654
            }
6550×
            Err(e) => Err(e.into()),
656
        }
6573062×
    }
658
65962×
    pub fn root(&self) -> &Path {
66062×
        &self.root
66162×
    }
662470×
    pub fn store(&self) -> &Store {
663470×
        &self.store
664470×
    }
66510×
    pub fn workspace(&self) -> WorkspaceId {
66610×
        self.workspace
66710×
    }
668
669
    /// Use a different user directory for keys and the user config file
670
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
671
    /// Act as if the working copy were on another platform's file system
672
    /// (tests of Windows and macOS behaviour on any host).
6732×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
6742×
        self.platform = platform;
6752×
        self
6762×
    }
677
6780×
    pub fn platform(&self) -> crate::portable::Platform {
6790×
        self.platform
6800×
    }
681
682155×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
683155×
        let dir = dir.into();
684155×
        self.keys_dir = dir.join("keys");
685155×
        self.user_config = dir.join("config.toml");
686155×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
687155×
            self.config = c;
688155×
        }
689155×
        self.apply_workspace_bookmark();
690155×
        self
691155×
    }
692
693
    /// The workspace's current bookmark (spec §10.1) overrides the
694
    /// configured default when `oxy bookmark switch` has recorded one.
6951864×
    fn apply_workspace_bookmark(&mut self) {
6961864×
        if let Ok(b) = fs::read_to_string(
6971864×
            self.oxy
6981864×
                .join("workspaces")
6991864×
                .join(self.workspace.to_hex())
7001864×
                .join("bookmark"),
7011864×
        ) {
70229×
            let b = b.trim();
70329×
            if !b.is_empty() {
70429×
                self.config.bookmark = b.to_string();
70529×
            }
7061835×
        }
7071864×
    }
708
7091×
    pub fn user_config_path(&self) -> &Path {
7101×
        &self.user_config
7111×
    }
712
713
    /// Set a key in the user file and refresh the effective configuration.
71412×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
71512×
        Config::set_user(&self.user_config, key, value)?;
71611×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
71711×
        Ok(())
71812×
    }
719
720346×
    pub fn save_config(&self) -> Result<()> {
721346×
        self.config.save(&self.oxy.join("config"))
722346×
    }
723
7243972×
    fn author(&self) -> KeyId {
7253972×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7263972×
    }
727
}
728
729
impl Repo {
7301524×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7311524×
        let mut c = Change {
7321524×
            version: crate::objects::CHANGE_VERSION,
7331524×
            change_id: ChangeId::random(),
7341524×
            deps,
7351524×
            author: self.author(),
7361524×
            hlc: Hlc::now(),
7371524×
            message: message.into(),
7381524×
            tree_ops: vec![],
7391524×
            edits: vec![],
7401524×
            kind: ChangeKind::WorkingCopy,
7411524×
        };
7421524×
        c.normalize();
7431524×
        c
7441524×
    }
745
746
    // ------------------------------------------------------------ operation log
747
74813071×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
74913071×
        if let Some(r) = self.at_op {
7505×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
75113066×
        }
75213066×
        let r = self.head_ref()?;
75313064×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
75413064×
        Ok((r, op))
75513071×
    }
756
7579098×
    pub fn view(&self) -> Result<View> {
7589098×
        Ok(self.head_op()?.1.view)
7599098×
    }
760
7613154×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
7623154×
        if self.at_op.is_some() {
7631×
            return fail(
764
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
765
            );
7663153×
        }
7673153×
        let op = Op {
7683153×
            parents: parents.to_vec(),
7693153×
            hlc: Hlc::now(),
7703153×
            command: command.into(),
7713153×
            view,
7723153×
        };
7733153×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
774
        // The head is the commit point: everything it names must be on disk first.
7753151×
        let flushing = crate::timing::phase("op: flush the store");
7763151×
        self.store.flush()?;
7773149×
        drop(flushing);
778
        // Compare and swap (spec §12.1): when another process recorded an
779
        // operation since this one read the head, the two are merged
780
        // instead of one overwriting the other. On this disk the head moves
781
        // under a short lock; on any other store by its record's version,
782
        // and a record that moved meanwhile is read again and merged again.
7833149×
        let _lock = if self.store.is_local() {
7843141×
            Some(self.lock_ops()?)
785
        } else {
7868×
            None
787
        };
7883149×
        let Some(parent) = parents.first() else {
789
            // The first operation (init): there is no head yet.
790490×
            if !self.swap_head(&r, None)? {
7912×
                return fail(format!(
792
                    "{} already holds a repository's operation log",
7932×
                    self.store.backend().describe()
794
                ));
795488×
            }
796488×
            return Ok(r);
797
        };
7982659×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
7992659×
        for _ in 0..HEAD_TRIES {
8002659×
            let (current, version) = self.read_head()?;
8012659×
            let to = if current == *parent {
8022649×
                r
803
            } else {
80410×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
8059×
                let merged = Op {
80610×
                    parents: vec![current, r],
80710×
                    hlc: Hlc::now(),
80810×
                    command: format!("{command} (merged with a concurrent operation)"),
80910×
                    view: self.merge_views(&base, &op.view, &theirs)?,
810
                };
8119×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
8129×
                self.store.flush()?;
8139×
                m
814
            };
8152658×
            if self.swap_head(&to, version.as_ref())? {
8162652×
                return Ok(to);
8170×
            }
818
        }
8190×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8203154×
    }
821
822
    /// The operation head's lock, held only while the head pointer moves.
8233150×
    fn lock_ops(&self) -> Result<FileLock> {
8243150×
        fs::create_dir_all(self.oxy.join("ops"))?;
8253150×
        FileLock::acquire(
8263150×
            self.oxy.join("ops").join("lock"),
8273150×
            "another oxy process holds the operation log",
828
        )
8293150×
    }
830
83113068×
    fn head_ref(&self) -> Result<ObjectRef> {
83213068×
        Ok(self.read_head()?.0)
83313068×
    }
834
835
    /// The operation head, and on a store its record's version for
836
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
837
    /// any other store (a bucket, or memory in tests) it is the store's
838
    /// [`HEAD_RECORD`] reference record (oxygen#68).
83915814×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
84015814×
        if self.store.is_local() {
84115795×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
84215795×
            let r = ObjectRef::from_hex(hex.trim())
84315795×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
84415792×
            return Ok((r, None));
84519×
        }
84619×
        let backend = self.store.backend();
84719×
        match backend.read_ref(HEAD_RECORD) {
84819×
            Ok(Some((bytes, version))) => {
84919×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
8500×
                    || {
8510×
                        RepoError::Msg(format!(
8520×
                            "the operation head in {} is corrupt",
8530×
                            backend.describe()
8540×
                        ))
8550×
                    },
8560×
                )?;
85719×
                Ok((r, Some(version)))
858
            }
8590×
            Ok(None) => fail(format!(
860
                "{} holds no operation log (no {HEAD_RECORD} record)",
8610×
                backend.describe()
862
            )),
8630×
            Err(e) => fail(format!("read the operation head: {e}")),
864
        }
86515814×
    }
866
867
    /// Move the operation head to `to` from the `expected` version
868
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
869
    /// disk the caller holds the operations lock and the head always
870
    /// moves; on a store it moves only if the record is unchanged, and
871
    /// `false` says another process moved it first.
8723160×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
8733160×
        if self.store.is_local() {
8743150×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
8753144×
            return Ok(true);
87610×
        }
87710×
        match self
87810×
            .store
87910×
            .backend()
88010×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
881
        {
8827×
            Ok(_) => Ok(true),
8833×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
8840×
            Err(e) => fail(format!("move the operation head: {e}")),
885
        }
8863160×
    }
887
888
    /// Three-way merge of two views that both started from `base` (spec
889
    /// §12.1). A reference only one side changed takes that side's value.
890
    /// When both changed it differently: a bookmark keeps both sides'
891
    /// heads (it may then have several), a change beats a deletion, a
892
    /// workspace changed by both is an error (only one of them matches the
893
    /// files on disk), and otherwise this process's value wins for remote
894
    /// references and the policy, the first value for a tag (tags never
895
    /// move).
89610×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
89734×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
89834×
            b: &BTreeMap<K, V>,
89934×
            o: &BTreeMap<K, V>,
90034×
            t: &BTreeMap<K, V>,
90134×
            mut both: impl FnMut(&V, &V) -> Result<V>,
90234×
        ) -> Result<BTreeMap<K, V>> {
90334×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
90434×
            let mut out = BTreeMap::new();
90535×
            for k in keys {
90635×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
90735×
                let v = if ov == tv || tv == bv {
90818×
                    ov.cloned()
90917×
                } else if ov == bv {
91010×
                    tv.cloned()
911
                } else {
9127×
                    match (ov, tv) {
9137×
                        (Some(x), Some(y)) => Some(both(x, y)?),
9140×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
9150×
                        (None, None) => None,
916
                    }
917
                };
91834×
                if let Some(v) = v {
91934×
                    out.insert(k.clone(), v);
92034×
                }
921
            }
92233×
            Ok(out)
92334×
        }
92410×
        let bookmarks = pick(
92510×
            &base.bookmarks,
92610×
            &ours.bookmarks,
92710×
            &theirs.bookmarks,
9286×
            |x, y| {
9296×
                let mut heads = self.store.get_state(x)?.heads;
9306×
                heads.extend(self.store.get_state(y)?.heads);
9316×
                let heads = self.load_state(&heads)?.maximal(&heads);
9326×
                Ok(self.store.put_state(&StateObject::new(heads))?)
9336×
            },
9340×
        )?;
935
        // Two operations that both replaced one workspace's working copy
936
        // cannot both be right: the files on disk match only one of them.
937
        // The working-copy lock keeps this from happening; should it happen
938
        // anyway, this operation is not recorded.
93910×
        let workspaces = pick(
94010×
            &base.workspaces,
94110×
            &ours.workspaces,
94210×
            &theirs.workspaces,
9431×
            |_, _| {
9441×
                fail(
945
                    "another oxy process changed this working copy at the same time; \
946
                     this command was not recorded: check `oxy status` and run it again",
947
                )
9481×
            },
9491×
        )?;
9509×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
9519×
        let empty = BTreeMap::new();
9529×
        let names: BTreeSet<&String> = base
9539×
            .remotes
9549×
            .keys()
9559×
            .chain(ours.remotes.keys())
9569×
            .chain(theirs.remotes.keys())
9579×
            .collect();
9589×
        let mut remotes = BTreeMap::new();
9599×
        for n in names {
9605×
            let m = pick(
9615×
                base.remotes.get(n).unwrap_or(&empty),
9625×
                ours.remotes.get(n).unwrap_or(&empty),
9635×
                theirs.remotes.get(n).unwrap_or(&empty),
9640×
                |x, _| Ok(*x),
9650×
            )?;
9665×
            if !m.is_empty() {
9675×
                remotes.insert(n.clone(), m);
9685×
            }
969
        }
9709×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
9719×
            ours.policy
9720×
        } else if ours.policy == base.policy {
9730×
            theirs.policy
974
        } else {
9750×
            ours.policy.or(theirs.policy)
976
        };
9779×
        self.store.flush()?;
9789×
        Ok(View {
9799×
            bookmarks,
9809×
            workspaces,
9819×
            remotes,
9829×
            policy,
9839×
            tags,
9849×
        })
98510×
    }
986
98742×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
98842×
        let mut out = Vec::new();
98942×
        let (mut r, mut op) = self.head_op()?;
990
        loop {
991241×
            let next = op.parents.first().copied();
992241×
            out.push((r, op));
993241×
            match next {
994199×
                Some(p) => {
995199×
                    r = p;
996199×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
997
                }
99842×
                None => break,
999
            }
1000
        }
100142×
        Ok(out)
100242×
    }
1003
1004
    /// Undo the last user command (spec §12.1). Operations that only recorded
1005
    /// a working-copy snapshot are skipped, since the files are still on disk
1006
    /// and the next snapshot recreates them, and a command's own checkout
1007
    /// (`… (checkout)`) goes with the command. When the working copy is
1008
    /// clean and was clean after the operation undone to, its files follow
1009
    /// too, since nothing on disk can be lost; otherwise they stay as they
1010
    /// are (an undone commit's edits come back as uncommitted work).
101110×
    pub fn undo(&self) -> Result<Op> {
101210×
        let _wc = self.lock_working_copy()?;
101310×
        let clean_now =
101410×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
101510×
        let (read_head, mut op) = self.head_op()?;
101610×
        let wc_now = op.view.workspaces.get(&self.workspace).copied();
101710×
        let up = |op: Op| -> Result<Option<Op>> {
10187×
            match op.parents.first() {
10197×
                Some(p) => Ok(Some(Op::decode(&self.store.get_typed(p, ObjectType::Op)?)?)),
10200×
                None => Ok(None),
1021
            }
10227×
        };
1023
        loop {
102417×
            while op.is_snapshot() {
10255×
                match up(op.clone())? {
10265×
                    Some(p) => op = p,
10270×
                    None => break,
1028
                }
1029
            }
103012×
            if !op.command.ends_with(" (checkout)") {
103110×
                break;
10322×
            }
10332×
            match up(op.clone())? {
10342×
                Some(p) => op = p,
10350×
                None => break,
1036
            }
1037
        }
103810×
        let Some(parent) = op.parents.first() else {
10391×
            return fail("nothing to undo");
1040
        };
10419×
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1042
        {
10439×
            let _lock = if self.store.is_local() {
10449×
                Some(self.lock_ops()?)
1045
            } else {
10460×
                None
1047
            };
10489×
            let (now, version) = self.read_head()?;
10499×
            if now != read_head || !self.swap_head(parent, version.as_ref())? {
10500×
                return fail("another oxy command ran while undoing; run undo again");
10519×
            }
1052
        }
10539×
        self.drop_manifest();
10549×
        if let Some(then) = parent_op.view.workspaces.get(&self.workspace) {
10559×
            if clean_now && Some(*then) != wc_now {
10566×
                let wc = self.store.get_change(then)?;
10576×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
10584×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1059
                    // The files differ from the restored working copy by
1060
                    // exactly what the undone command did: nothing else is
1061
                    // on disk, as the working copy was clean.
10624×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
10632×
                }
10643×
            }
10650×
        }
10669×
        Ok(parent_op)
106710×
    }
1068
1069
    /// The last operation that was not a snapshot.
10702×
    pub fn last_command(&self) -> Result<Op> {
10712×
        let (_, mut op) = self.head_op()?;
10724×
        while op.is_snapshot() {
10732×
            let Some(parent) = op.parents.first() else {
10740×
                break;
1075
            };
10762×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1077
        }
10782×
        Ok(op)
10792×
    }
1080
1081
    // ------------------------------------------------------------ states
1082
1083
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1084192×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1085192×
        if let Some(st) = self.load_state_checkpointed(heads)? {
10864×
            return Ok(st);
1087187×
        }
1088187×
        self.load_state_full(heads)
1089192×
    }
1090
1091
    /// The state of `heads` for its history (changes, tree, metadata) with
1092
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1093
    /// and friends. Build the graphs a command needs with
1094
    /// [`Repo::load_graphs_of`].
10951602×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
10961602×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
109731×
            return Ok(st);
10981571×
        }
10991571×
        self.load_state_replayed(heads, State::new_history_only())
11001602×
    }
1101
1102
    /// Build these file graphs in a history-only state.
11031687×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
11041687×
        state
11051687×
            .load_graphs(
11061687×
                nodes,
110754×
                |refs| {
110854×
                    self.read_blobs(refs).map_err(|e| {
11093×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
11103×
                    })
111154×
                },
11121962×
                |h| self.change_bytes(h),
1113
            )
11141687×
            .map_err(|e| self.index_damage(e))
11151687×
    }
1116
1117
    /// An error building graphs, and when it is a state index found
1118
    /// damaged (a file's history that does not match its hash), the
1119
    /// workspace's state indexes removed: they are rebuilt from history by
1120
    /// the next command.
11214×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
11224×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
11233×
            return e.into();
1124
        };
11252×
        for path in self.state_indexes() {
11262×
            let _ = fs::remove_file(path);
11272×
        }
11281×
        RepoError::Msg(format!(
11291×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
11301×
        ))
11314×
    }
1132
1133
    /// The graphs of `nodes` of a history-only state, built beside it (see
1134
    /// [`State::build_graphs_detached`]).
113575×
    pub fn build_graphs_detached(
113675×
        &self,
113775×
        state: &State,
113875×
        nodes: &[crate::ids::NodeId],
113975×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
114075×
        Ok(state
114175×
            .build_graphs_detached(
114275×
                nodes,
11430×
                |refs| {
11440×
                    self.read_blobs(refs).map_err(|e| {
11450×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
11460×
                    })
11470×
                },
114881×
                |h| self.change_bytes(h),
1149
            )
115075×
            .map_err(|e| self.index_damage(e))?
115175×
            .into_iter()
115275×
            .collect())
115375×
    }
1154
1155
    /// The contents of texts [`State::single_text`] gave: blobs read in
1156
    /// one go, inline ones from their changes.
1157343×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1158
        use crate::objects::TextRef;
1159343×
        let refs: Vec<ObjectRef> = texts
1160343×
            .iter()
11615529×
            .filter_map(|t| match t {
11621×
                TextRef::Blob(r, _, _) => Some(*r),
11635528×
                TextRef::Inline { .. } => None,
11645529×
            })
1165343×
            .collect();
1166343×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1167343×
        let mut out = Vec::with_capacity(texts.len());
11685529×
        for t in texts {
11695529×
            let lines = match t {
11701×
                TextRef::Blob(_, count, form) => {
11711×
                    let content = blobs
11721×
                        .next()
11731×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
11741×
                    crate::objects::text_lines(&content, *count, *form)?
1175
                }
11765528×
                TextRef::Inline { change, start, end } => {
11775528×
                    let bytes = self.change_bytes(change)?;
11785528×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
11790×
                        RepoError::Msg("an inline insert lies outside its change".into())
11800×
                    })?;
11815528×
                    crate::objects::inline_lines(range)?
1182
                }
1183
            };
11845529×
            out.push(lines.bytes().to_vec());
1185
        }
1186343×
        Ok(out)
1187343×
    }
1188
1189
    /// Build every graph a history-only state still lacks, making it full.
11901696×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
11911696×
        state
11921696×
            .load_all_graphs(
119316×
                |refs| {
119416×
                    self.read_blobs(refs).map_err(|e| {
11950×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
11960×
                    })
119716×
                },
11983642×
                |h| self.change_bytes(h),
1199
            )
12001696×
            .map_err(|e| self.index_damage(e))
12011696×
    }
1202
1203
    /// A change's encoding, for building graphs of its inline inserts. The
1204
    /// last few read are kept: a checkout building graphs a batch at a
1205
    /// time reads the same large changes for every batch, often in turn.
120611213×
    fn change_bytes(
120711213×
        &self,
120811213×
        h: &ChangeHash,
120911213×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
121011213×
        let mut cache = self.last_change.borrow_mut();
121119504×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
12128758×
            let hit = cache.remove(i);
12138758×
            let b = hit.1.clone();
12148758×
            cache.push(hit);
12158758×
            return Ok(b);
12162455×
        }
12172455×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
12180×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
12190×
        })?);
12202455×
        cache.push((*h, b.clone()));
1221
        // The last few, within a memory budget; the newest always stays.
12223988×
        while cache.len() > CHANGE_CACHE_COUNT
12232455×
            || (cache.len() > 1
12247444×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
12251533×
        {
12261533×
            cache.remove(0);
12271533×
        }
12282455×
        Ok(b)
122911213×
    }
1230
1231
    /// Load the dependency closure of `heads` change by change.
1232241×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1233241×
        self.load_state_replayed(heads, State::new())
1234241×
    }
1235
12363086×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
12373086×
        let history = state.is_history_only();
12383086×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
12393086×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1240
        {
12413086×
            let _t = crate::timing::phase("load: read and add changes");
12423086×
            let (mut read, mut add, mut fetch) = (
12433086×
                std::time::Duration::ZERO,
12443086×
                std::time::Duration::ZERO,
12453086×
                std::time::Duration::ZERO,
12463086×
            );
124712553×
            while let Some(h) = stack.pop() {
1248
                // A change the state holds brings its history with it.
12499470×
                if !seen.insert(h) || state.contains(&h) {
12502244×
                    continue;
12517226×
                }
12527226×
                let t0 = std::time::Instant::now();
1253
                // A history-only state reads text only for the graphs it
1254
                // builds; either way the hash is the one asked for.
12557226×
                let (c, texts) = if history {
12565975×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
12575974×
                    fetch += t0.elapsed();
12585974×
                    Change::decode_skeleton(&bytes, h)
12595974×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1260
                } else {
12611251×
                    (self.store.get_change(&h)?, Vec::new())
1262
                };
12637223×
                read += t0.elapsed();
12647223×
                stack.extend(c.deps.iter().copied());
12657223×
                let t1 = std::time::Instant::now();
12667223×
                state.add_known(h, c, texts);
12677223×
                add += t1.elapsed();
1268
            }
12693083×
            crate::timing::record("load:   of which reading", read);
12703083×
            crate::timing::record("load:     of which fetching", fetch);
12713083×
            crate::timing::record("load:   of which applying", add);
1272
        }
12733083×
        let _t = crate::timing::phase("load: validate");
12743083×
        state.validate()?;
12753083×
        Ok(state)
12763086×
    }
1277
12782194×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
12792194×
        if self.bare {
12802×
            return fail("this is a bare repository: it has no working copy");
12812192×
        }
12822192×
        let view = self.view()?;
12832192×
        let h = *view
12842192×
            .workspaces
12852192×
            .get(&self.workspace)
12862192×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
12872191×
        Ok((h, self.store.get_change(&h)?))
12882194×
    }
1289
1290
    /// Heads of a bookmark's state (spec §10.1).
12911695×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
12921695×
        match view.bookmarks.get(bookmark) {
12931695×
            Some(st) => Ok(self.store.get_state(st)?.heads),
12940×
            None => Ok(vec![]),
1295
        }
12961695×
    }
1297
1298492×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1299492×
        self.heads_of(&self.view()?, &self.config.bookmark)
1300492×
    }
1301
1302
    // ------------------------------------------------------------ blobs
1303
1304388×
    fn blob_for(content: &[u8]) -> Blob {
1305388×
        Blob::of(content)
1306388×
    }
1307
1308244×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1309244×
        Self::blob_for(content).hash()
1310244×
    }
1311
1312142×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1313165×
        for c in crate::chunk::chunks(content) {
1314165×
            self.store.put_chunk(c)?;
1315
        }
1316142×
        Ok(self
1317142×
            .store
1318142×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1319142×
    }
1320
1321
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1322
    /// all their chunks, are read in parallel; a blob the store lacks goes
1323
    /// through [`Repo::read_blob`], which may fetch it lazily.
1324417×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1325417×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1326417×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
132780×
            blobs.push(match got {
132875×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
13290×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
13305×
                Err(crate::store::StoreError::NotFound(_)) => None,
13310×
                Err(e) => return Err(e.into()),
1332
            });
1333
        }
1334417×
        let chunk_refs: Vec<ObjectRef> = blobs
1335417×
            .iter()
1336417×
            .flatten()
1337417×
            .flat_map(|b| b.chunks.iter().copied())
1338417×
            .collect();
1339417×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1340417×
        let mut out = Vec::with_capacity(refs.len());
1341417×
        for (r, blob) in refs.iter().zip(blobs) {
134280×
            match blob {
13435×
                None => out.push(self.read_blob(r)?),
134475×
                Some(b) => {
134575×
                    let mut content = Vec::with_capacity(b.length as usize);
1346114×
                    for c in &b.chunks {
1347114×
                        match chunks.next() {
1348114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
13490×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
13500×
                            Some(Err(e)) => return Err(e.into()),
13510×
                            None => return fail("chunk list ended early"),
1352
                        }
1353
                    }
135475×
                    out.push(content);
1355
                }
1356
            }
1357
        }
1358412×
        Ok(out)
1359417×
    }
1360
1361
    /// Read a blob's content, fetching it from the remote that withheld it
1362
    /// when it is lazily absent (spec §13.5).
1363111×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1364111×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
13654×
            self.fetch_lazy_blob(r)?;
1366107×
        }
1367111×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1368106×
        let mut out = Vec::with_capacity(blob.length as usize);
1369113×
        for c in &blob.chunks {
1370113×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1371
        }
1372106×
        Ok(out)
1373111×
    }
1374
1375
    // ------------------------------------------------------------ working copy
1376
1377
    /// Attributes from the `.oxyattributes` files in the working directory.
13782×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1379
        // Nested repositories and ignored paths are left out, as in a walk.
13808×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
13812×
        let files: Vec<(String, Vec<u8>)> = listing
13822×
            .files
13832×
            .into_iter()
13842×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
13852×
            .collect();
13862×
        crate::attributes::Attributes::from_files(
13872×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1388
        )
13892×
    }
1390
1391
    /// Folders holding a repository of their own that the last look at the
1392
    /// working copy left out, not being subrepos (oxygen#43).
139329×
    pub fn untracked_nested(&self) -> Vec<String> {
139429×
        self.untracked_nested.borrow().clone()
139529×
    }
1396
1397
    /// Attributes from a materialized state's `.oxyattributes` files.
13983×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
13996×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
14006×
            match &f.content {
14016×
                FileContent::Text { bytes, .. }
14026×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1403
                {
14040×
                    Some((p.as_str(), bytes.as_slice()))
1405
                }
14066×
                _ => None,
1407
            }
14086×
        }))
14093×
    }
1410
1411
    /// Store a blob, raw when the path is `nocompress`.
1412126×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1413126×
        if !nocompress {
1414124×
            return self.store_blob(content);
14152×
        }
14162×
        for c in crate::chunk::chunks(content) {
14172×
            self.store.put_chunk_nocompress(c)?;
1418
        }
14192×
        Ok(self
14202×
            .store
14212×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1422126×
    }
1423
1424
    /// This workspace's state index (oxygen#41): its working copy's base,
1425
    /// saved so a snapshot reads it rather than replaying history.
1426
    /// The state index of the state with these heads: this workspace keeps
1427
    /// the last few it used, named by their heads, so moving between two
1428
    /// states finds both.
14292269×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
14302269×
        let mut heads = heads.to_vec();
14312269×
        heads.sort();
14322269×
        let mut h = blake3::Hasher::new();
14332269×
        for c in &heads {
14342240×
            h.update(&c.0);
14352240×
        }
14362269×
        self.oxy.join("index").join(format!(
14372269×
            "{}{}",
14382269×
            self.state_index_prefix(),
14392269×
            &h.finalize().to_hex()[..16]
14402269×
        ))
14412269×
    }
1442
14434460×
    fn state_index_prefix(&self) -> String {
14444460×
        format!("state-{}-", self.workspace.to_hex())
14454460×
    }
1446
1447
    /// This workspace's state indexes, newest first.
14482191×
    fn state_indexes(&self) -> Vec<PathBuf> {
14492191×
        let prefix = self.state_index_prefix();
14502191×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
14512191×
            .into_iter()
14522191×
            .flatten()
14532191×
            .flatten()
14542191×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
14552191×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
14562191×
            .collect();
14572191×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
14582191×
        found.into_iter().map(|(_, p)| p).collect()
14592191×
    }
1460
1461
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1462
    /// from this workspace's state index when it holds that history: every
1463
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1464
    /// is loaded from history and indexed for next time.
14651891×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
14661891×
        if let Some((st, heads)) = self.read_state_index(deps) {
14671523×
            let mut have = st.maximal(deps);
14681523×
            have.sort();
14691523×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1470
                // Re-encoding reads every history: one found damaged is
1471
                // left to the build that reads it, which reports it.
1472
                #[cfg(test)]
1473139×
                if let Some(mine) = st.write_index() {
1474138×
                    assert_eq!(
1475138×
                        Some(mine),
1476138×
                        self.load_state_history(deps)?.write_index(),
1477
                        "a state index holds the state history gives"
1478
                    );
14791×
                }
1480249×
                return Ok(st);
14811274×
            }
1482
            // An index a few changes behind (a commit, a pull since): add
1483
            // what it lacks, as long as all it holds is history of `deps`.
1484
            // Anything amiss (a change beyond a shallow boundary) takes the
1485
            // long way instead.
14861274×
            let (indexed, started) = (st.len(), std::time::Instant::now());
14871274×
            if let Ok(st) = self.load_state_replayed(deps, st) {
14881273×
                let mut all = deps.to_vec();
14891273×
                all.extend(heads.iter().copied());
14901273×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
14911273×
                within.sort();
14921273×
                want.sort();
14931273×
                if within == want {
1494
                    #[cfg(test)]
1495646×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1496
                    // Writing the index costs far more than replaying a
1497
                    // few small changes: it is rewritten once it falls
1498
                    // behind, or when replaying took long (large changes).
14991271×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
15001271×
                        || started.elapsed() > INDEX_REPLAY_TIME
15016×
                    {
15026×
                        self.write_state_index(deps, &st);
15031265×
                    }
15041271×
                    return Ok(st);
15052×
                }
15061×
            }
1507368×
        }
1508371×
        let st = self.load_state_history(deps)?;
1509371×
        self.write_state_index(deps, &st);
1510371×
        Ok(st)
15111891×
    }
1512
1513
    /// Two history-only states hold the same changes and render the same
1514
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1515
    /// the checkpoint's graphs as the bases of its files' histories.
1516
    #[cfg(test)]
1517646×
    fn assert_same_state(&self, a: &State, b: &State) {
15181292×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1519646×
        assert_eq!(ids(a), ids(b), "the same changes");
15201292×
        let files = |s: &State| {
15211292×
            let mut s = s.clone();
15221292×
            self.load_all_graphs(&mut s).unwrap();
15231292×
            s.materialize().files
15241292×
        };
1525646×
        assert_eq!(files(a), files(b), "the same files");
1526646×
    }
1527
1528
    /// The state index file: its heads, a hash of its changes block and one
1529
    /// of the rest, then the body [`State::write_index`] gives, whose first
1530
    /// block is the changes. Hashed in two parts so the log can read and
1531
    /// check the changes alone.
1532
    /// The index of `deps` if there is one, else the newest, which the
1533
    /// caller may bring up to date.
15341891×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1535
        use std::io::Read;
15361891×
        let _t = crate::timing::phase("load: state index");
15371891×
        let exact = self.state_index_path(deps);
15381891×
        let reading = crate::timing::phase("load:   of which reading the file");
15391891×
        let mut f = match fs::File::open(&exact) {
1540249×
            Ok(f) => {
1541
                // Used now: the newest, so the last to be dropped.
1542249×
                let _ = fs::File::options()
1543249×
                    .write(true)
1544249×
                    .open(&exact)
1545249×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1546249×
                f
1547
            }
15481642×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1549
        };
15501523×
        let total = f.metadata().ok()?.len();
15511523×
        let mut word = [0u8; 4];
15521523×
        f.read_exact(&mut word).ok()?;
15531523×
        let n = u32::from_le_bytes(word) as usize;
15541523×
        let mut head = vec![0u8; 32 * n + 64 + 8];
15551523×
        f.read_exact(&mut head).ok()?;
15561523×
        let heads: Vec<ChangeHash> = head[..32 * n]
15571523×
            .chunks_exact(32)
15581523×
            .map(|c| ObjectRef(c.try_into().unwrap()))
15591523×
            .collect();
15601523×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
15611523×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
15621523×
        let at = (4 + head.len()) as u64;
15631523×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
15640×
            return None;
15651523×
        }
1566
        // The front only: the files' histories after it are read, each
1567
        // checked by its own hash, when a command builds that file.
15681523×
        let mut front = vec![0u8; front_len as usize];
15691523×
        f.read_exact(&mut front).ok()?;
15701523×
        drop(reading);
15711523×
        let checking = crate::timing::phase("load:   of which checking the file");
15721523×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
15731523×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
15743046×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
15751523×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
15760×
            return None;
15771523×
        }
15781523×
        drop(checking);
15791523×
        let histories = crate::state::Histories::File(
15801523×
            std::sync::Arc::new(f),
15811523×
            at + front_len,
15821523×
            total - at - front_len,
15831523×
        );
15841523×
        Some((State::read_index_front(&front, histories).ok()?, heads))
15851891×
    }
1586
1587
    /// The changes of this workspace's state index (the closure of its
1588
    /// heads), read without the rest of the index.
1589169×
    pub(crate) fn read_state_index_changes(
1590169×
        &self,
1591169×
    ) -> Option<crate::fasthash::FastMap<ChangeHash, std::sync::Arc<crate::state::ChangeMeta>>>
1592
    {
1593
        use std::io::Read;
1594169×
        let _t = crate::timing::phase("load: state index changes");
1595169×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1596154×
        let mut word = [0u8; 4];
1597154×
        f.read_exact(&mut word).ok()?;
1598154×
        let n = u32::from_le_bytes(word) as usize;
1599
        // Heads, the two sums, the front's length, then the changes block.
1600154×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1601154×
        f.read_exact(&mut head).ok()?;
1602154×
        let sum = &head[32 * n..32 * n + 32];
1603154×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1604154×
        let mut changes = vec![0u8; 4 + len];
1605154×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1606154×
        f.read_exact(&mut changes[4..]).ok()?;
1607154×
        let checking = crate::timing::phase("load:   of which checking");
1608154×
        let mut h = blake3::Hasher::new();
1609154×
        h.update_rayon(&changes);
1610154×
        if h.finalize().as_bytes() != sum {
16110×
            return None;
1612154×
        }
1613154×
        drop(checking);
1614154×
        let _decoding = crate::timing::phase("load:   of which decoding");
1615154×
        State::read_index_changes(&changes[4..]).ok()
1616169×
    }
1617
1618
    /// Save `st`, the history-only state of `deps`, as this workspace's
1619
    /// state index; quietly nothing when it cannot be (it is only a cache).
1620378×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1621378×
        let _t = crate::timing::phase("write: state index");
1622378×
        let encoding = crate::timing::phase("write:   of which encoding");
1623378×
        let Some(body) = st.write_index() else {
16240×
            return;
1625
        };
1626378×
        drop(encoding);
1627
        #[cfg(test)]
1628194×
        assert_eq!(
1629194×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1630194×
            Some(body.clone()),
1631
            "a state index reads back as written"
1632
        );
1633378×
        let mut heads = st.maximal(deps);
1634378×
        heads.sort();
1635378×
        let mut w = crate::flat::Writer::default();
1636378×
        w.count(heads.len());
1637378×
        for h in &heads {
163817×
            w.object(h);
163917×
        }
1640
        // The body is the front's length, the front, then the files'
1641
        // histories, which carry their own hashes: the sums cover the
1642
        // front's changes block and the rest of the front.
1643378×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
1644378×
        let front = &body[8..8 + front_len];
1645378×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
1646756×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1647378×
        w.fixed(&sum(&front[..split]));
1648378×
        w.fixed(&sum(&front[split..]));
1649378×
        w.fixed(&body);
1650378×
        let path = self.state_index_path(&heads);
1651378×
        let _ = fs::create_dir_all(self.oxy.join("index"));
1652378×
        let _ = write_cache(&path, &w.0);
1653
        // The last two used: the index of a state moved away from stays for
1654
        // a move back. Older ones (and the unnamed one of before) go.
1655378×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
16561×
            let _ = fs::remove_file(old);
16571×
        }
1658378×
        let _ = fs::remove_file(
1659378×
            self.oxy
1660378×
                .join("index")
1661378×
                .join(format!("state-{}", self.workspace.to_hex())),
1662378×
        );
1663378×
    }
1664
16656×
    fn locks_dir(&self) -> PathBuf {
16666×
        self.oxy.join("locks")
16676×
    }
1668
1669
    /// Whether `path` is locked locally for editing (spec §18, advisory).
16703×
    pub fn is_locked(&self, path: &str) -> bool {
16713×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
16723×
    }
1673
1674
    /// Take the advisory local lock on a `lockable` file and make it writable.
16752×
    pub fn lock_path(&self, path: &str) -> Result<()> {
16762×
        let attrs = self.disk_attributes();
16772×
        if !attrs.lookup(path).lockable {
16781×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
16791×
        }
16801×
        fs::create_dir_all(self.locks_dir())?;
16811×
        write_atomic(
16821×
            &self.locks_dir().join(path.replace('/', "%2F")),
16831×
            std::process::id().to_string().as_bytes(),
16840×
        )?;
16851×
        set_readonly(&self.root.join(path), false)?;
16861×
        Ok(())
16872×
    }
1688
1689
    /// Release the local lock and make the file read-only again.
16901×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
16911×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
16921×
        if self.root.join(path).exists() {
16931×
            set_readonly(&self.root.join(path), true)?;
16940×
        }
16951×
        Ok(())
16961×
    }
1697
1698
    /// Whether a repository path is inside the sparse filter (spec §17).
169924128×
    pub fn in_scope(&self, path: &str) -> bool {
170024128×
        self.config.sparse_paths.is_empty()
170182×
            || self
170282×
                .config
170382×
                .sparse_paths
170482×
                .iter()
170599×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
170624128×
    }
1707
17081×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
17091×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
17101×
    }
1711
1712
    /// Walk the working copy; with a manifest, a file whose size and mtime
1713
    /// match it is not read: an opaque file yields its known blob, and a
1714
    /// text file whose recorded graph key equals its base graph's key in
1715
    /// `keys` (path → key) is marked unchanged; other text files are read
1716
    /// but keep their known hash. Files modified within two seconds of the
1717
    /// manifest are never trusted (a racy stat).
1718
    ///
1719
    /// `.oxyattributes` files are always read, since their content is
1720
    /// needed; and when any of them is not known unchanged (added, removed,
1721
    /// edited, or changed in the base), no text file is taken as unchanged,
1722
    /// because attributes decide how a file compares with the base.
1723
    ///
1724
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
1725
    /// (the base state's files) that exists on disk is included even when
1726
    /// an ignore rule matches it, as in Git.
17271205×
    fn walk_working_copy_with(
17281205×
        &self,
17291205×
        cache: Option<&prompt::Manifest>,
17301205×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
17311205×
        keys: Option<&KeyOf>,
17321205×
    ) -> Result<BTreeMap<String, FsEntry>> {
1733
        let mut out: BTreeMap<String, FsEntry>;
17341205×
        let sparse = &self.config.sparse_paths;
17359032×
        let in_scope = |p: &str| {
17369032×
            sparse.is_empty()
17377×
                || sparse
17387×
                    .iter()
17397×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
17409032×
        };
17411205×
        let walk_phase = crate::timing::phase("walk:   of which listing");
1742
        let walk::Listing {
17431205×
            files,
17441205×
            symlinks,
17451205×
            nested,
17461205×
            dirs,
17471205×
        } = match self.listing_cache.take() {
1748152×
            Some(l) => l,
1749
            // Ignore rules apply to untracked paths only, so the base's
1750
            // files are not matched against them (an added file is: a rule
1751
            // written after it was snapshotted leaves it out again).
17529044×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
1753
        };
17541205×
        let keys = keys.filter(|k| {
175511946×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
17561202×
            let attrs_unchanged =
17571202×
                files
17581202×
                    .iter()
175911927×
                    .filter(|(r, _, _)| is_attributes(r))
17601202×
                    .all(|(rel, _, meta)| {
17619×
                        stat_cached(rel, meta, cache)
17629×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
17639×
                    });
17641202×
            let none_removed = tracked
17651202×
                .keys()
17668976×
                .filter(|r| is_attributes(r))
17671202×
                .all(|r| on_disk.contains(r.as_str()));
17681202×
            attrs_unchanged && none_removed
17691202×
        });
17701205×
        *self.walked_dirs.borrow_mut() =
17711205×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
17721205×
        drop(walk_phase);
17731205×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
1774
        // Reading files is most of a walk's cost; do it in parallel.
1775
        {
1776
            use rayon::prelude::*;
17771205×
            let mut read: Vec<(String, FsEntry)> = files
17781205×
                .par_iter()
177911958×
                .map(|(rel, path, meta)| {
1780
                    // A key is worked out only for a file the manifest
1781
                    // knows with the same stat and a key of its own.
178211958×
                    let key = keys
178311958×
                        .filter(|_| !is_attributes(rel))
178411958×
                        .filter(|_| {
178511918×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
178611918×
                        })
178711958×
                        .and_then(|k| k(rel));
178811958×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
178911958×
                })
17901205×
                .collect::<Result<Vec<_>>>()?;
179111956×
            for (rel, e) in read.iter_mut() {
1792
                // A cached blob the store lost (gc, a partial clone): read the file after all.
179311956×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
17940×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
17950×
                    e.blob = None;
179611956×
                }
1797
            }
1798
            // The listing is in path order, so the map is built without
1799
            // searching.
18001204×
            out = read.into_iter().collect();
18011204×
            for (rel, target) in symlinks {
18022×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
18032×
            }
1804
        }
18051204×
        drop(_read_phase);
18061204×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
1807
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
1808
        // already tracked as subrepo nodes, they contribute their pin;
1809
        // unregistered ones are left alone.
18101204×
        let modules = self.modules_on_disk();
18111204×
        let removed = self.removed_subrepos();
18121204×
        for rel in &removed {
18133×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
18141×
                self.clear_removed_subrepo(rel);
18152×
            }
1816
        }
18171204×
        let mut untracked_nested = Vec::new();
18181204×
        for dir in nested {
181930×
            let rel = self.rel_path(&dir);
182030×
            if !self.in_scope(&rel) || removed.contains(&rel) {
18213×
                continue;
182227×
            }
182327×
            let registered = modules.entries.get(&rel);
182427×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
1825
            {
18261×
                untracked_nested.push(rel);
18271×
                continue;
182826×
            }
182926×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
183026×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
1831
        }
18321204×
        untracked_nested.sort();
18331204×
        *self.untracked_nested.borrow_mut() = untracked_nested;
1834
        // Tracked paths the ignore rules hid.
18351204×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
183676×
            if !self.in_scope(rel) {
183710×
                continue;
183866×
            }
183966×
            let path = self.root.join(rel);
184066×
            if *kind == NodeKind::Subrepo {
18414×
                if removed.contains(rel) {
18422×
                    continue;
18432×
                }
18442×
                let present =
18452×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
18462×
                if present {
18470×
                    let pin = subrepos::read_pin(
18480×
                        &path,
18490×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
18500×
                    )?;
18510×
                    out.insert(
18520×
                        rel.clone(),
18530×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
1854
                    );
18552×
                } else if let Some(b) = blob {
18562×
                    // Not cloned (or emptied): the pin stays as recorded, as a
18572×
                    // Git gitlink does when its directory is absent.
18582×
                    out.insert(
18592×
                        rel.clone(),
18602×
                        FsEntry {
18612×
                            blob: Some(*b),
18622×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
18632×
                        },
18642×
                    );
18652×
                }
18662×
                continue;
186762×
            }
186862×
            let Ok(meta) = fs::symlink_metadata(&path) else {
186962×
                continue;
1870
            };
18710×
            let ft = meta.file_type();
18720×
            if ft.is_symlink() {
18730×
                let target = fs::read_link(&path)?;
18740×
                out.insert(
18750×
                    rel.clone(),
18760×
                    FsEntry::new(
18770×
                        NodeKind::Symlink,
1878
                        false,
18790×
                        target.to_string_lossy().as_bytes().to_vec(),
1880
                    ),
1881
                );
18820×
            } else if ft.is_file() {
18830×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
18840×
                out.insert(rel.clone(), e);
18850×
            }
1886
        }
18871204×
        Ok(out)
18881205×
    }
1889
1890
    /// The entry for one regular file, read or served from the stat cache.
18910×
    fn file_entry(
18920×
        &self,
18930×
        rel: &str,
18940×
        path: &Path,
18950×
        meta: &walk::Stat,
18960×
        cache: Option<&prompt::Manifest>,
18970×
    ) -> Result<FsEntry> {
18980×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
18990×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
19000×
            e.content = std::sync::Arc::new(fs::read(path)?);
19010×
            e.blob = None;
19020×
        }
19030×
        Ok(e)
19040×
    }
1905
1906
    /// The non-directory paths of a snapshot with their kinds, for the
1907
    /// walker's `tracked` set.
19082×
    pub(crate) fn tracked_kinds(
19092×
        snapshot: &Snapshot,
19102×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
19112×
        snapshot
19122×
            .files
19132×
            .iter()
191412×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
19158×
            .map(|(p, f)| {
19168×
                let blob = match &f.content {
19174×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
19184×
                    _ => None,
1919
                };
19208×
                (p.clone(), (f.kind, blob))
19218×
            })
19222×
            .collect()
19232×
    }
1924
1925
    /// A path under the root as a `/`-separated relative string.
192668×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
192768×
        path.strip_prefix(&self.root)
192868×
            .unwrap_or(path)
192968×
            .components()
1930130×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
193168×
            .collect::<Vec<_>>()
193268×
            .join("/")
193368×
    }
1934
}
1935
1936
impl Repo {
1937
    /// Changes reachable from the bookmark and the working copy, newest first.
193890×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
193990×
        let heads = self.bookmark_heads()?;
194090×
        if self.bare {
19411×
            return self.log_state(&heads);
194289×
        }
194389×
        let (wc_hash, wc) = self.working_copy()?;
194489×
        let mut all = heads.clone();
194589×
        all.push(wc_hash);
194689×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
194789×
        let mut entries: Vec<LogEntry> = Vec::new();
1948
        // A shallow clone knows changes beyond its boundary from a
1949
        // checkpoint's metadata only: its log comes from the state.
195089×
        let metas = if self.is_shallow() {
19511×
            self.load_state_history(&all)?
19521×
                .changes()
19539×
                .map(|(h, m)| (*h, m.clone()))
19541×
                .collect()
1955
        } else {
1956
            // The working copy's change is in hand, and is never in the
1957
            // state index: its metadata is not looked up again.
195888×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
195988×
            below.extend(wc.deps.iter().copied());
196088×
            let _t = crate::timing::phase("log: metadata");
196188×
            let mut metas = self.metas_of(&below)?;
1962320×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
196388×
                metas.push((wc_hash, crate::state::ChangeMeta::of(&wc)));
196488×
            }
196588×
            metas
1966
        };
1967417×
        for (h, meta) in metas {
1968417×
            entries.push(LogEntry {
1969417×
                hash: h,
1970417×
                change: meta,
1971417×
                is_working_copy: h == wc_hash,
1972417×
                is_head: head_set.contains(&h),
1973417×
            });
1974417×
        }
197589×
        let _sorting = crate::timing::phase("log: sort");
1976
        // The hash makes the order total, so an unstable sort gives the same.
1977837×
        entries.sort_unstable_by(|a, b| {
1978837×
            b.is_working_copy
1979837×
                .cmp(&a.is_working_copy)
1980837×
                .then(b.change.hlc.cmp(&a.change.hlc))
1981837×
                .then(b.hash.cmp(&a.hash))
1982837×
        });
198389×
        Ok(entries)
198490×
    }
1985
1986
    /// A window of `log_state`: entries `offset..offset+limit` and the total
1987
    /// count, for paginated views.
19880×
    pub fn log_window(
19890×
        &self,
19900×
        heads: &[ChangeHash],
19910×
        offset: usize,
19920×
        limit: usize,
19930×
    ) -> Result<(Vec<LogEntry>, usize)> {
19940×
        let all = self.log_state(heads)?;
19950×
        let total = all.len();
19960×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
19970×
    }
1998
1999
    /// The log of the state with these heads, newest first, with no working
2000
    /// copy involved (for hosted repositories and any explicit state).
20017×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2002
        // The log needs change metadata only: neither graphs nor the tree.
20037×
        if self.is_shallow() {
20040×
            return Ok(self.log_of(&self.load_state_history(heads)?));
20057×
        }
20067×
        let metas = self.metas_of(heads)?;
20077×
        let depended: BTreeSet<ChangeHash> = metas
20087×
            .iter()
200916×
            .flat_map(|(_, m)| m.deps.iter().copied())
20107×
            .collect();
20117×
        let mut entries: Vec<LogEntry> = metas
20127×
            .into_iter()
20137×
            .map(|(h, meta)| LogEntry {
201416×
                hash: h,
201516×
                is_head: !depended.contains(&h),
201616×
                change: meta,
2017
                is_working_copy: false,
201816×
            })
20197×
            .collect();
202011×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
20217×
        Ok(entries)
20227×
    }
2023
2024
    /// Every change of the state with these heads and its metadata, read
2025
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2026
    /// a shallow clone's boundary is left out.
2027169×
    pub fn metas_of(
2028169×
        &self,
2029169×
        heads: &[ChangeHash],
2030169×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2031169×
        let boundary = self.boundary();
2032
        // The state index holds the metadata of its heads' closure: a
2033
        // change found there is not read from the store (a change object
2034
        // can be as large as the tree it adds).
2035169×
        let mut indexed = self.read_state_index_changes();
2036169×
        let _walk = crate::timing::phase("metadata: walk");
2037169×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2038169×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2039169×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2040169×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
20411245×
        while let Some(h) = stack.pop() {
20421076×
            if !seen.insert(h) {
2043456×
                continue;
2044620×
            }
2045
            // Taken out of the index's map, each once: not copied.
2046620×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2047
                #[cfg(test)]
20480×
                assert_eq!(
20490×
                    *meta,
20500×
                    self.store.get_change_meta(&h)?,
2051
                    "the state index holds a change's metadata"
2052
                );
20530×
                let meta = std::sync::Arc::unwrap_or_clone(meta);
20540×
                stack.extend(meta.deps.iter().copied());
20550×
                out.push((h, meta));
20560×
                continue;
2057620×
            }
2058620×
            let started = std::time::Instant::now();
2059620×
            let meta = match self.store.get_change_meta(&h) {
2060620×
                Ok(m) => m,
20610×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
20620×
                Err(e) => return Err(e.into()),
2063
            };
2064620×
            stored += 1;
2065620×
            from_store += started.elapsed();
2066620×
            stack.extend(meta.deps.iter().copied());
2067620×
            out.push((h, meta));
2068
        }
2069169×
        if stored > 0 && crate::timing::enabled() {
20700×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2071169×
        }
2072169×
        Ok(out)
2073169×
    }
2074
2075
    /// The log of a state already loaded, newest first.
2076
    /// The history of lines `first..=last` (1-based) of `path` in the
2077
    /// state `heads` make (spec §27): every change that inserted or
2078
    /// deleted one of their atoms, or an atom deleted from between them,
2079
    /// newest first. Exact, as atoms keep their identity across edits.
20806×
    pub fn line_history(
20816×
        &self,
20826×
        heads: &[ChangeHash],
20836×
        path: &str,
20846×
        first: usize,
20856×
        last: usize,
20866×
    ) -> Result<Vec<LogEntry>> {
20876×
        if first == 0 || last < first {
20881×
            return fail(format!(
2089
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2090
            ));
20915×
        }
20925×
        let mut state = self.load_state_history(heads)?;
20935×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
20941×
            return fail(format!("{path} is not in that state"));
2095
        };
20964×
        self.load_graphs_of(&mut state, &[node])?;
20974×
        let live = state.live_lines(&node);
20984×
        if last > live.len() {
20991×
            return fail(format!(
2100
                "{path} has {} lines; asked for {first},{last}",
21011×
                live.len()
2102
            ));
21033×
        }
21043×
        let Some(g) = state.file(&node) else {
21050×
            return fail(format!("{path} is not a text file"));
2106
        };
21073×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
21083×
        let touched = g.touching(&atoms);
21093×
        Ok(self
21103×
            .log_of(&state)
21113×
            .into_iter()
211213×
            .filter(|e| touched.contains(&e.hash))
21133×
            .collect())
21146×
    }
2115
21168×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
21178×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
21188×
        let mut entries: Vec<LogEntry> = state
21198×
            .changes()
21208×
            .map(|(h, meta)| LogEntry {
212131×
                hash: *h,
212231×
                change: meta.clone(),
2123
                is_working_copy: false,
212431×
                is_head: head_set.contains(h),
212531×
            })
21268×
            .collect();
212737×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
21288×
        entries
21298×
    }
2130
2131
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2132
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2133
    /// (`resolve_change`).
213465×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
213565×
        let view = self.view()?;
213665×
        if let Some(st) = view.bookmarks.get(spec) {
213737×
            return Ok(self.store.get_state(st)?.heads);
213828×
        }
213928×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
21402×
            return Ok(self.store.get_state(&st)?.heads);
214126×
        }
214226×
        if let Some(heads) = self.tag_heads(spec)? {
21432×
            return Ok(heads);
214424×
        }
214524×
        Ok(vec![self.resolve_change(spec)?])
214665×
    }
2147
2148
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2149
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
215033×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
215133×
        if spec == "@" {
21520×
            return Ok(self.working_copy()?.0);
215333×
        }
215433×
        let view = self.view()?;
215533×
        let named = match view.bookmarks.get(spec) {
21561×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
215732×
            None => match remote_bookmark(&view, spec) {
21581×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
215931×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2160
            },
2161
        };
216233×
        if let Some((kind, heads)) = named {
21633×
            return match heads.len() {
21643×
                1 => Ok(heads[0]),
21650×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2166
            };
216730×
        }
216830×
        if spec.is_empty() || spec == "#" {
21690×
            return fail("empty change specifier");
217030×
        }
217130×
        let entries = self.log()?;
217230×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
217324×
            entries
217424×
                .iter()
2175103×
                .filter(|e| e.hash.starts_with_hex(hp))
217624×
                .collect()
2177
        } else {
21786×
            entries
21796×
                .iter()
218021×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
21816×
                .collect()
2182
        };
218330×
        match matches.len() {
218426×
            1 => Ok(matches[0].hash),
21854×
            0 => match self.resolve_in_remotes(spec)? {
21861×
                Some(h) => Ok(h),
21873×
                None => fail(format!("no change matches {spec:?}")),
2188
            },
2189
            _ => {
21900×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
21910×
                if ids.len() == 1 {
21920×
                    fail(format!(
2193
                        "change {spec} is divergent: {} variants",
21940×
                        matches.len()
2195
                    ))
2196
                } else {
21970×
                    fail(format!("{spec:?} is ambiguous"))
2198
                }
2199
            }
2200
        }
220133×
    }
2202
2203
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2204
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2205
    /// `None` when none matches, or more than one.
22064×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
22074×
        let view = self.view()?;
22084×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
22094×
        for bookmarks in view.remotes.values() {
22103×
            for st in bookmarks.values() {
22113×
                let heads = self.store.get_state(st)?.heads;
22127×
                for e in self.log_state(&heads)? {
22137×
                    let hit = match spec.strip_prefix('#') {
22142×
                        Some(hp) => e.hash.starts_with_hex(hp),
22155×
                        None => e.change.change_id.starts_with_hex(spec),
2216
                    };
22177×
                    if hit {
22181×
                        found.insert(e.hash);
22196×
                    }
2220
                }
2221
            }
2222
        }
22234×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
22244×
    }
2225
2226
    /// Where a change is when no local bookmark or the working copy holds
2227
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2228
    /// it is held locally, or nowhere.
22293×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
22306×
        if self.log()?.iter().any(|e| e.hash == *hash) {
22312×
            return Ok(None);
22321×
        }
22331×
        let view = self.view()?;
22341×
        for (remote, bookmarks) in &view.remotes {
22351×
            for (name, st) in bookmarks {
22361×
                let heads = self.store.get_state(st)?.heads;
22371×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
22381×
                    return Ok(Some(format!("{remote}/{name}")));
22390×
                }
2240
            }
2241
        }
22420×
        Ok(None)
22433×
    }
2244
2245
    /// Human-readable description of what a change does, with line content.
22463×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
22473×
        let change = self.store.get_change(hash)?;
22483×
        let (base, base_snapshot) = self.change_base(&change)?;
22493×
        Ok(render_change(&change, &base, &base_snapshot))
22503×
    }
2251
2252
    /// The base state of `change` (its dependencies) and its rendering, as
2253
    /// much as showing the change needs: the whole tree, and the graphs and
2254
    /// contents of the files the change edits. Other text files are left
2255
    /// unrendered ([`Snapshot::unrendered`]).
22566×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
22576×
        let base = self.load_state_history(&change.deps)?;
22586×
        self.render_base_for(change, base)
22596×
    }
2260
2261
    /// The base for showing `change` alone: the graphs of the files it
2262
    /// edits built, and the base's tree with no file rendered, which is
2263
    /// all [`render_change`](snapshot::render_change) and
2264
    /// [`diff_files_of`](snapshot::diff_files_of) read.
22652×
    pub(crate) fn tree_base_for(
22662×
        &self,
22672×
        change: &Change,
22682×
        mut base: State,
22692×
    ) -> Result<(State, Snapshot)> {
22702×
        let _t = crate::timing::phase("diff: the base's tree");
22712×
        let edited: std::collections::HashSet<NodeId> =
22728×
            change.edits.iter().map(|e| e.node()).collect();
22732×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
22742×
        self.load_graphs_of(&mut base, &nodes)?;
22752×
        let snapshot = Snapshot {
22762×
            tree: base.tree().view(),
22772×
            files: BTreeMap::new(),
22782×
            unrendered: BTreeSet::new(),
22792×
        };
22802×
        Ok((base, snapshot))
22812×
    }
2282
2283
    /// [`Repo::change_base`] with the base already loaded (the working
2284
    /// copy's comes from the state index).
2285204×
    pub(crate) fn render_base_for(
2286204×
        &self,
2287204×
        change: &Change,
2288204×
        mut base: State,
2289204×
    ) -> Result<(State, Snapshot)> {
2290204×
        let _t = crate::timing::phase("diff: render the base");
2291204×
        let edited: std::collections::HashSet<NodeId> =
2292407×
            change.edits.iter().map(|e| e.node()).collect();
2293204×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2294204×
        self.load_graphs_of(&mut base, &nodes)?;
2295204×
        let snapshot = {
2296204×
            let _t = crate::timing::phase("diff:   of which materialize");
2297204×
            base.materialize_nodes(&edited)
2298
        };
2299204×
        Ok((base, snapshot))
2300204×
    }
2301
}
2302
23030×
fn remove_any(path: &Path) -> std::io::Result<()> {
23040×
    let m = fs::symlink_metadata(path)?;
23050×
    if m.is_dir() {
23060×
        fs::remove_dir_all(path)
2307
    } else {
23080×
        fs::remove_file(path)
2309
    }
23100×
}
2311
23125×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
23135×
    let mut perms = fs::metadata(path)?.permissions();
23145×
    perms.set_readonly(readonly);
23155×
    fs::set_permissions(path, perms)
23165×
}
2317
2318
#[cfg(unix)]
23195841×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2320
    use std::os::unix::fs::PermissionsExt;
23215841×
    let mut perms = fs::metadata(path)?.permissions();
23225841×
    let mode = perms.mode();
23235841×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
23245841×
    if want != mode {
23254×
        perms.set_mode(want);
23264×
        fs::set_permissions(path, perms)?;
23275837×
    }
23285841×
    Ok(())
23295841×
}
2330
#[cfg(not(unix))]
2331
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2332
    Ok(())
2333
}
2334
2335
#[cfg(unix)]
233616139×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2337
    use std::os::unix::fs::PermissionsExt;
233816139×
    m.permissions().mode() & 0o111 != 0
233916139×
}
2340
#[cfg(not(unix))]
2341
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2342
    false
2343
}
2344
234512713×
fn op_ref(k: OpKey) -> OpRef {
234612713×
    OpRef {
234712713×
        change: k.0,
234812713×
        index: k.1,
234912713×
    }
235012713×
}
2351
23525954×
fn split_path(path: &str) -> (&str, &str) {
23535954×
    match path.rfind('/') {
23545059×
        Some(i) => (&path[..i], &path[i + 1..]),
2355895×
        None => ("", path),
2356
    }
23575954×
}
2358
2359
/// Whether `rel` is an attributes file (spec §7.6).
236066788×
fn is_attributes(rel: &str) -> bool {
236166788×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
236266788×
}
2363
2364
/// The manifest entry for `rel` when its size and mtime match it outside
2365
/// the racy window.
236623885×
fn stat_cached<'m>(
236723885×
    rel: &str,
236823885×
    meta: &walk::Stat,
236923885×
    cache: Option<&'m prompt::Manifest>,
237023885×
) -> Option<&'m prompt::ManifestEntry> {
237123885×
    let m = cache?;
237218981×
    let e = m.entries.get(rel)?;
237317680×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
237417680×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
237523885×
}
2376
2377
/// Read one working-copy file, or serve it from the stat cache (spec
2378
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2379
/// an opaque file is not read at all (its stored blob stands in), and a
2380
/// text file the manifest recorded equal to a base graph whose key is
2381
/// `key`, the key the base has now, is not read either: equal keys mean
2382
/// equal renderings, so it still equals the base. Touches no repository
2383
/// state, so the walk runs it in parallel; the caller checks that a cached
2384
/// blob is still in the store.
238511958×
fn read_file_entry(
238611958×
    rel: &str,
238711958×
    path: &Path,
238811958×
    meta: &walk::Stat,
238911958×
    cache: Option<&prompt::Manifest>,
239011958×
    key: Option<[u8; 32]>,
239111958×
) -> Result<FsEntry> {
239211958×
    let exec = meta.exec;
239311958×
    let stat = Some((meta.size, meta.mtime_ns));
239411958×
    let mut e = match stat_cached(rel, meta, cache) {
23954249×
        Some(e) if e.blob.is_some() => FsEntry {
23961×
            blob: e.blob,
23971×
            content_hash: Some(e.hash),
23981×
            ..FsEntry::new(NodeKind::File, exec, vec![])
23991×
        },
24004248×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
24014243×
            content_hash: Some(e.hash),
24024243×
            unchanged: true,
24034243×
            graph_key: e.graph,
24044243×
            ..FsEntry::new(NodeKind::File, exec, vec![])
24054243×
        },
24065×
        Some(e) => FsEntry {
24075×
            content_hash: Some(e.hash),
24085×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2409
        },
24107709×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2411
    };
2412
    // The stat the manifest records: taken before the read, so a file that
2413
    // changes meanwhile is read again next time.
241411957×
    e.stat = stat;
241511957×
    Ok(e)
241611958×
}
2417
2418
/// Two maps side by side in key order: each key of either, with its value
2419
/// in each. Linear, with no lookups, for maps of a whole tree.
24202392×
pub(crate) fn join<'a, A, B>(
24212392×
    a: &'a BTreeMap<String, A>,
24222392×
    b: &'a BTreeMap<String, B>,
24232392×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
24242392×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
242535196×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
24262392×
        (None, None) => None,
24272898×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
24285752×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
242924154×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2430318×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2431284×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2432
            std::cmp::Ordering::Equal => {
243323552×
                let (k, va) = a.next()?;
243423552×
                let (_, vb) = b.next()?;
243523552×
                Some((k, Some(va), Some(vb)))
2436
            }
2437
        },
243835196×
    })
24392392×
}
2440
2441
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2442
/// lookups.
24431205×
pub(crate) fn missing_from<'a, A, B>(
24441205×
    a: &'a BTreeMap<String, A>,
24451205×
    b: &BTreeMap<String, B>,
24461205×
) -> Vec<(&'a String, &'a A)> {
24471205×
    let mut keys = b.keys().peekable();
24481205×
    a.iter()
24498986×
        .filter(|(k, _)| {
245017332×
            while keys.next_if(|kb| *kb < *k).is_some() {}
24518986×
            keys.peek() != Some(k)
24528986×
        })
24531205×
        .collect()
24541205×
}