OXYGENHUB

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

1520 of 1693 lines run, 372 of 591 functions · run #251 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.
752223×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762223×
    let Some(url) = &config.storage_url else {
772218×
        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×
    )?)
1002223×
}
101
102158×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103158×
    Err(RepoError::Msg(s.into()))
104158×
}
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 walk;
132
mod workspace;
133
134
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
135
pub use checkout::CheckoutReport;
136
pub use config::{parse_size, read_config_file, Config};
137
pub use doctor::{Check, DoctorReport, Health};
138
pub use fsck::{FsckReport, Problem, Severity};
139
pub use gc::GcReport;
140
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
141
pub use hooks::{json_array, json_str, HookOutcome};
142
pub use hosted::FileEdit;
143
pub use identity::{Rotation, SignatureStatus};
144
pub use inspect::{BisectStep, BlameLine, Description};
145
pub use ops::{RestoreReport, RevertReport, ViewChange};
146
pub use policy::PolicyUpdate;
147
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
148
pub use receipts::ReceiptInfo;
149
pub use revset::{Revset, REVSET_BUDGET};
150
pub use snapshot::{
151
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
152
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
153
    Selection, SnapshotResult,
154
};
155
pub use subrepos::{SubrepoInfo, SubrepoSync};
156
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated};
157
pub use tags::TagInfo;
158
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
159
160
/// The file name under which per-bookmark or per-tag data is kept: `/`
161
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
162
/// than a directory that would clash with it.
1633569×
pub(crate) fn name_file(name: &str) -> String {
1643569×
    name.replace('%', "%25").replace('/', "%2F")
1653569×
}
166
167
/// The name a [`name_file`] file name stands for.
16842×
pub(crate) fn file_name_to_name(file: &str) -> String {
16942×
    file.replace("%2F", "/").replace("%25", "%")
17042×
}
171
1726363×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1736363×
    Ok(crate::durable::write_atomic(path, data)?)
1746363×
}
175
176
/// Replace a cache file: whole or not at all, but without waiting for the
177
/// disk. A cache checks its own bytes when read, so one a crash leaves
178
/// short or stale is rebuilt rather than trusted.
179
/// How many changes a state index may fall behind its working copy before
180
/// it is written again; until then each load replays them.
181
const INDEX_REPLAY_LIMIT: usize = 16;
182
/// The changes whose encodings are kept for building graphs: a batch of
183
/// files often takes inline text from a few changes in turn.
184
const CHANGE_CACHE_COUNT: usize = 4;
185
const CHANGE_CACHE_BYTES: usize = 512 << 20;
186
/// How many state indexes a workspace keeps.
187
const STATE_INDEXES_KEPT: usize = 2;
188
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
189
1902595×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1912595×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1922595×
    fs::write(&tmp, data)?;
1932595×
    fs::rename(&tmp, path)?;
1942595×
    Ok(())
1952595×
}
196
197
pub struct LogEntry {
198
    pub hash: ChangeHash,
199
    /// Metadata from the state; the full change may be absent in a shallow repository.
200
    pub change: crate::state::ChangeMeta,
201
    pub is_working_copy: bool,
202
    pub is_head: bool,
203
}
204
205
/// A text file's base graph key, by path, as a walk asks for it.
206
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
207
208
/// A file as found on disk or in an imported tree.
209
#[derive(Clone)]
210
pub(crate) struct FsEntry {
211
    pub kind: NodeKind,
212
    pub exec: bool,
213
    /// File content, or a symlink's target. Empty when `blob` is set.
214
    /// Shared, so a new file's insert holds it without a copy.
215
    pub content: std::sync::Arc<Vec<u8>>,
216
    /// The stored blob of an opaque file whose size and mtime are unchanged
217
    /// since the last manifest (spec §12.3 stat cache); the content was not
218
    /// read.
219
    pub blob: Option<ObjectRef>,
220
    /// BLAKE3 of the content, carried over from the manifest when the stat
221
    /// is unchanged, so the manifest can be rewritten without rehashing.
222
    pub content_hash: Option<[u8; 32]>,
223
    /// A text file known equal to the base's rendering without reading it:
224
    /// its stat matches the manifest and the manifest recorded it equal to
225
    /// a base file graph with the same key (spec §12.3). `content` is empty.
226
    pub unchanged: bool,
227
    /// The base graph key this file equals, for the next manifest.
228
    pub graph_key: Option<[u8; 32]>,
229
    /// Size and mtime already known to be current (a checkout leaving the
230
    /// file as it was), so the manifest need not stat it again.
231
    pub stat: Option<(u64, u128)>,
232
}
233
234
impl FsEntry {
23522498×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
23622498×
        FsEntry {
23722498×
            kind,
23822498×
            exec,
23922498×
            content: std::sync::Arc::new(content),
24022498×
            blob: None,
24122498×
            content_hash: None,
24222498×
            unchanged: false,
24322498×
            graph_key: None,
24422498×
            stat: None,
24522498×
        }
24622498×
    }
247
}
248
249
pub struct Repo {
250
    /// Oxygen-pinned subrepos skipped by the running Git export.
251
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
252
    /// The manifest as last read, with the file identity it was read from,
253
    /// so one command parses it once (see `read_manifest`).
254
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
255
    /// A listing of the working copy left by a failed clean check, for the
256
    /// snapshot that follows it to reuse; taken by the next walk and
257
    /// dropped whenever the manifest is written.
258
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
259
    /// The nested repositories the last walk left out, being neither
260
    /// registered nor tracked subrepos (oxygen#43).
261
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
262
    root: PathBuf,
263
    oxy: PathBuf,
264
    store: Store,
265
    workspace: WorkspaceId,
266
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
267
    bare: bool,
268
    keys_dir: PathBuf,
269
    user_config: PathBuf,
270
    pub config: Config,
271
    /// What the working copy's file system can represent (spec §7.7).
272
    platform: crate::portable::Platform,
273
    /// The encodings of the changes last read for their inline inserts,
274
    /// oldest first.
275
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
276
    /// `--at-op`: read the repository as it was after this operation;
277
    /// recording an operation is refused.
278
    at_op: Option<ObjectRef>,
279
    /// The directories (with their times) and nested repositories of the
280
    /// last walk, for the manifest written from it.
281
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
282
    /// The directories a manifest check listed, for its restamp only.
283
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
284
}
285
286
/// A walk's directories with their times, and its nested repositories.
287
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
288
289
/// Marker file of a bare repository, inside `.oxy/`.
290
const BARE_MARKER: &str = "bare";
291
/// Marker of a hosted repository that has no id yet: the first push binds
292
/// it to the pusher's id (spec §16.1).
293
const UNBOUND_MARKER: &str = "unbound";
294
295
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
296
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
2976893×
pub fn default_home() -> PathBuf {
2986893×
    if let Ok(h) = std::env::var("OXY_HOME") {
2996890×
        return PathBuf::from(h);
3003×
    }
3013×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3020×
        return PathBuf::from(x).join("oxy");
3033×
    }
304
    // Windows has no HOME as a rule: the roaming profile's application
305
    // data, as Windows programs keep theirs.
306
    #[cfg(windows)]
307
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
308
        return PathBuf::from(d).join("oxy");
309
    }
3103×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3113×
    PathBuf::from(home).join(".config").join("oxy")
3126893×
}
313
3142223×
pub fn default_keys_dir() -> PathBuf {
3152223×
    default_home().join("keys")
3162223×
}
317
3184446×
pub fn default_user_config() -> PathBuf {
3194446×
    default_home().join("config.toml")
3204446×
}
321
322
/// Where `create_identity` records the author.
323
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
324
pub enum IdentityScope {
325
    /// The user file: every repository of this user signs with it.
326
    User,
327
    /// This repository only.
328
    Repo,
329
}
330
331
impl Repo {
332
    // ------------------------------------------------------------ lifecycle
333
334190×
    pub fn init(root: &Path) -> Result<Repo> {
335190×
        let mut id = [0u8; 16];
336190×
        rand::rngs::OsRng.fill_bytes(&mut id);
337190×
        Self::init_with_id(root, id)
338190×
    }
339
340
    /// Initialize a repository with a given repository ID (clones share the
341
    /// ID of their origin, spec §14.4).
342417×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
343417×
        Self::init_on(root, id, None)
344417×
    }
345
346
    /// A new repository with a fresh id, bare or not, on `storage` or in
347
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
34811×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
34911×
        let mut id = [0u8; 16];
35011×
        rand::rngs::OsRng.fill_bytes(&mut id);
35111×
        if bare {
3520×
            Self::init_bare_on(root, id, storage)
353
        } else {
35411×
            Self::init_on(root, id, storage)
355
        }
35611×
    }
357
358
    /// Initialize a repository whose objects and operation head are kept
359
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
360431×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
361431×
        fs::create_dir_all(root)?;
362431×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
363431×
        let oxy = root.join(OXY_DIR);
364431×
        if oxy.exists() {
3651×
            return fail(format!("{} is already an oxy repository", root.display()));
366430×
        }
367430×
        fs::create_dir_all(oxy.join("ops"))?;
368430×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
369430×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
370430×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
371430×
        if let Some(url) = storage {
3723×
            config.set("storage.url", url)?;
373427×
        }
374430×
        config.save(&oxy.join("config"))?;
375430×
        let workspace = WorkspaceId::random();
376430×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
377430×
        let store = open_objects(&oxy, &config)?;
378429×
        let repo = Repo {
379429×
            last_change: Default::default(),
380429×
            at_op: None,
381429×
            walked_dirs: Default::default(),
382429×
            listed_dirs: Default::default(),
383429×
            git_export_skipped: Default::default(),
384429×
            manifest_cache: Default::default(),
385429×
            listing_cache: Default::default(),
386429×
            untracked_nested: Default::default(),
387429×
            root,
388429×
            oxy,
389429×
            store,
390429×
            workspace,
391429×
            bare: false,
392429×
            keys_dir: default_keys_dir(),
393429×
            platform: crate::portable::Platform::current(),
394429×
            user_config: default_user_config(),
395429×
            config,
396429×
        };
397429×
        repo.register_workspace(&workspace, &repo.root)?;
398
399429×
        let wc = repo.new_working_copy(vec![], "");
400429×
        let wc_hash = repo.store.put_change(&wc)?;
401429×
        let mut view = View::default();
402429×
        view.bookmarks.insert(
403429×
            repo.config.bookmark.clone(),
404429×
            repo.store.put_state(&StateObject::new(vec![]))?,
405
        );
406429×
        view.workspaces.insert(workspace, wc_hash);
407429×
        repo.record_op(&[], "oxy init", view)?;
408427×
        Ok(repo)
409431×
    }
410
411
    /// Create a bare repository: an object store, operation log and
412
    /// references with no workspace and no working copy, for hosting
413
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4145×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4155×
        let mut id = [0u8; 16];
4165×
        rand::rngs::OsRng.fill_bytes(&mut id);
4175×
        Self::init_bare_with_id(root, id)
4185×
    }
419
42037×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
42137×
        Self::init_bare_on(root, id, None)
42237×
    }
423
424
    /// [`Repo::init_on`] for a bare repository.
42537×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
42637×
        fs::create_dir_all(root)?;
42737×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
42837×
        let oxy = root.join(OXY_DIR);
42937×
        if oxy.exists() {
4300×
            return fail(format!("{} is already an oxy repository", root.display()));
43137×
        }
43237×
        fs::create_dir_all(oxy.join("ops"))?;
43337×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
43437×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
43537×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
43637×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
43737×
        if let Some(url) = storage {
4380×
            config.set("storage.url", url)?;
43937×
        }
44037×
        config.save(&oxy.join("config"))?;
44137×
        let store = open_objects(&oxy, &config)?;
44237×
        let repo = Repo {
44337×
            last_change: Default::default(),
44437×
            at_op: None,
44537×
            walked_dirs: Default::default(),
44637×
            listed_dirs: Default::default(),
44737×
            git_export_skipped: Default::default(),
44837×
            manifest_cache: Default::default(),
44937×
            listing_cache: Default::default(),
45037×
            untracked_nested: Default::default(),
45137×
            root,
45237×
            oxy,
45337×
            store,
45437×
            workspace: WorkspaceId::ZERO,
45537×
            bare: true,
45637×
            keys_dir: default_keys_dir(),
45737×
            platform: crate::portable::Platform::current(),
45837×
            user_config: default_user_config(),
45937×
            config,
46037×
        };
46137×
        let mut view = View::default();
46237×
        view.bookmarks.insert(
46337×
            repo.config.bookmark.clone(),
46437×
            repo.store.put_state(&StateObject::new(vec![]))?,
465
        );
46637×
        repo.record_op(&[], "oxy init --bare", view)?;
46737×
        Ok(repo)
46837×
    }
469
470
    /// A bare repository with no id yet. Its `id()` is all zero until the
471
    /// first push binds it (`bind_id`), so an existing repository can be
472
    /// pushed to a freshly created hosted one and keep its identity.
47311×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
47411×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
47511×
        fs::remove_file(repo.oxy.join("id"))?;
47611×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
47711×
        Ok(repo)
47811×
    }
479
4803235×
    pub fn is_unbound(&self) -> bool {
4813235×
        self.oxy.join(UNBOUND_MARKER).is_file()
4823235×
    }
483
484
    /// Give an unbound repository its id.
48510×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
48610×
        if !self.is_unbound() {
4870×
            return fail("this repository already has an id");
48810×
        }
48910×
        if id == [0; 16] {
4900×
            return fail("a repository id cannot be all zero");
49110×
        }
49210×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
49310×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
49410×
        Ok(())
49510×
    }
496
497
    /// Whether this repository has no working copy (`init_bare`).
49843×
    pub fn is_bare(&self) -> bool {
49943×
        self.bare
50043×
    }
501
502
    /// Open the repository containing `start` (searching upwards).
5031756×
    pub fn open(start: &Path) -> Result<Repo> {
5041756×
        let start = start.canonicalize()?;
5051756×
        let mut dir: Option<&Path> = Some(&start);
5061756×
        while let Some(d) = dir {
5071756×
            let oxy = d.join(OXY_DIR);
5081756×
            if oxy.is_file() {
509
                // A secondary workspace (spec §12.2): the file points at the repository.
5106×
                let text = fs::read_to_string(&oxy)?;
5116×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5120×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
513
                };
5146×
                let format = fs::read_to_string(shared.join("format"))?;
5156×
                if format != FORMAT_LINE {
5160×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5176×
                }
5186×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5196×
                let store = open_objects(&shared, &config)?;
5206×
                let mut repo = Repo {
5216×
                    last_change: Default::default(),
5226×
                    at_op: None,
5236×
                    walked_dirs: Default::default(),
5246×
                    listed_dirs: Default::default(),
5256×
                    git_export_skipped: Default::default(),
5266×
                    manifest_cache: Default::default(),
5276×
                    listing_cache: Default::default(),
5286×
                    untracked_nested: Default::default(),
5296×
                    root: d.to_path_buf(),
5306×
                    oxy: shared,
5316×
                    store,
5326×
                    workspace,
5336×
                    bare: false,
5346×
                    keys_dir: default_keys_dir(),
5356×
                    platform: crate::portable::Platform::current(),
5366×
                    user_config: default_user_config(),
5376×
                    config,
5386×
                };
5396×
                repo.apply_workspace_bookmark();
5406×
                return Ok(repo);
5411750×
            }
5421750×
            if oxy.is_dir() {
5431750×
                let format = fs::read_to_string(oxy.join("format"))?;
5441750×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5451750×
                let bare = oxy.join(BARE_MARKER).is_file();
5461750×
                let workspace = if bare {
547141×
                    WorkspaceId::ZERO
548
                } else {
5491609×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5501609×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
551
                };
5521750×
                let store = open_objects(&oxy, &config)?;
5531750×
                let mut repo = Repo {
5541750×
                    last_change: Default::default(),
5551750×
                    at_op: None,
5561750×
                    walked_dirs: Default::default(),
5571750×
                    listed_dirs: Default::default(),
5581750×
                    git_export_skipped: Default::default(),
5591750×
                    manifest_cache: Default::default(),
5601750×
                    listing_cache: Default::default(),
5611750×
                    untracked_nested: Default::default(),
5621750×
                    root: d.to_path_buf(),
5631750×
                    oxy,
5641750×
                    store,
5651750×
                    workspace,
5661750×
                    bare,
5671750×
                    keys_dir: default_keys_dir(),
5681750×
                    platform: crate::portable::Platform::current(),
5691750×
                    user_config: default_user_config(),
5701750×
                    config,
5711750×
                };
5721750×
                if !bare {
5731609×
                    repo.apply_workspace_bookmark();
5741609×
                }
5751750×
                if format == FORMAT1_LINE {
5761×
                    repo.migrate_format1()?;
5771749×
                } else if format != FORMAT_LINE {
5780×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5791749×
                }
5801750×
                return Ok(repo);
5810×
            }
5820×
            dir = d.parent();
583
        }
5840×
        fail(format!(
585
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
5860×
            start.display()
587
        ))
5881756×
    }
589
590
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
591
    /// into format 2, where each bookmark names a `state` object.
5921×
    fn migrate_format1(&self) -> Result<()> {
5931×
        let (head, version) = self.read_head()?;
594
        // Collect the chain root-first.
5951×
        let mut chain: Vec<Format1Op> = Vec::new();
5961×
        let mut cur = Some(head);
5973×
        while let Some(r) = cur {
5982×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
5992×
            cur = op.parents.first().copied();
6002×
            chain.push(op);
601
        }
6021×
        chain.reverse();
6031×
        let mut new_parent: Option<ObjectRef> = None;
6042×
        for old in chain {
6052×
            let mut view = View::default();
6062×
            for (name, heads) in &old.view.bookmarks {
6072×
                view.bookmarks.insert(
6082×
                    name.clone(),
6092×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
610
                );
611
            }
6122×
            view.workspaces = old.view.workspaces.clone();
6132×
            let op = Op {
6142×
                parents: new_parent.into_iter().collect(),
6152×
                hlc: old.hlc,
6162×
                command: old.command,
6172×
                view,
6182×
            };
6192×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
620
        }
6211×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6220×
            return fail("the operation log changed while it was rewritten; run the command again");
6231×
        }
6241×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6251×
        Ok(())
6261×
    }
627
628
    /// Pack automatically once many loose objects have accumulated.
629594×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
630594×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6310×
            self.store.pack_loose()?;
6320×
            self.store.merge_packs()?;
633594×
        }
634594×
        Ok(())
635594×
    }
636
637
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6382980×
    pub fn id(&self) -> Result<[u8; 16]> {
6392980×
        if self.is_unbound() {
64016×
            return Ok([0; 16]);
6412964×
        }
6422964×
        let path = self.oxy.join("id");
6432964×
        match fs::read_to_string(&path) {
6442964×
            Ok(h) => hex::decode(h.trim())
6452964×
                .ok()
6462964×
                .and_then(|v| v.try_into().ok())
6472964×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6480×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6490×
                let mut id = [0u8; 16];
6500×
                rand::rngs::OsRng.fill_bytes(&mut id);
6510×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6520×
                Ok(id)
653
            }
6540×
            Err(e) => Err(e.into()),
655
        }
6562980×
    }
657
65861×
    pub fn root(&self) -> &Path {
65961×
        &self.root
66061×
    }
661484×
    pub fn store(&self) -> &Store {
662484×
        &self.store
663484×
    }
66410×
    pub fn workspace(&self) -> WorkspaceId {
66510×
        self.workspace
66610×
    }
667
668
    /// Use a different user directory for keys and the user config file
669
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
670
    /// Act as if the working copy were on another platform's file system
671
    /// (tests of Windows and macOS behaviour on any host).
6722×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
6732×
        self.platform = platform;
6742×
        self
6752×
    }
676
6770×
    pub fn platform(&self) -> crate::portable::Platform {
6780×
        self.platform
6790×
    }
680
681143×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
682143×
        let dir = dir.into();
683143×
        self.keys_dir = dir.join("keys");
684143×
        self.user_config = dir.join("config.toml");
685143×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
686143×
            self.config = c;
687143×
        }
688143×
        self.apply_workspace_bookmark();
689143×
        self
690143×
    }
691
692
    /// The workspace's current bookmark (spec §10.1) overrides the
693
    /// configured default when `oxy bookmark switch` has recorded one.
6941758×
    fn apply_workspace_bookmark(&mut self) {
6951758×
        if let Ok(b) = fs::read_to_string(
6961758×
            self.oxy
6971758×
                .join("workspaces")
6981758×
                .join(self.workspace.to_hex())
6991758×
                .join("bookmark"),
7001758×
        ) {
70124×
            let b = b.trim();
70224×
            if !b.is_empty() {
70324×
                self.config.bookmark = b.to_string();
70424×
            }
7051734×
        }
7061758×
    }
707
7081×
    pub fn user_config_path(&self) -> &Path {
7091×
        &self.user_config
7101×
    }
711
712
    /// Set a key in the user file and refresh the effective configuration.
71312×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
71412×
        Config::set_user(&self.user_config, key, value)?;
71511×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
71611×
        Ok(())
71712×
    }
718
719337×
    pub fn save_config(&self) -> Result<()> {
720337×
        self.config.save(&self.oxy.join("config"))
721337×
    }
722
7233884×
    fn author(&self) -> KeyId {
7243884×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7253884×
    }
726
}
727
728
impl Repo {
7291483×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7301483×
        let mut c = Change {
7311483×
            version: crate::objects::CHANGE_VERSION,
7321483×
            change_id: ChangeId::random(),
7331483×
            deps,
7341483×
            author: self.author(),
7351483×
            hlc: Hlc::now(),
7361483×
            message: message.into(),
7371483×
            tree_ops: vec![],
7381483×
            edits: vec![],
7391483×
            kind: ChangeKind::WorkingCopy,
7401483×
        };
7411483×
        c.normalize();
7421483×
        c
7431483×
    }
744
745
    // ------------------------------------------------------------ operation log
746
74712715×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
74812715×
        if let Some(r) = self.at_op {
7495×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
75012710×
        }
75112710×
        let r = self.head_ref()?;
75212708×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
75312708×
        Ok((r, op))
75412715×
    }
755
7568842×
    pub fn view(&self) -> Result<View> {
7578842×
        Ok(self.head_op()?.1.view)
7588842×
    }
759
7603095×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
7613095×
        if self.at_op.is_some() {
7621×
            return fail(
763
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
764
            );
7653094×
        }
7663094×
        let op = Op {
7673094×
            parents: parents.to_vec(),
7683094×
            hlc: Hlc::now(),
7693094×
            command: command.into(),
7703094×
            view,
7713094×
        };
7723094×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
773
        // The head is the commit point: everything it names must be on disk first.
7743092×
        let flushing = crate::timing::phase("op: flush the store");
7753092×
        self.store.flush()?;
7763090×
        drop(flushing);
777
        // Compare and swap (spec §12.1): when another process recorded an
778
        // operation since this one read the head, the two are merged
779
        // instead of one overwriting the other. On this disk the head moves
780
        // under a short lock; on any other store by its record's version,
781
        // and a record that moved meanwhile is read again and merged again.
7823090×
        let _lock = if self.store.is_local() {
7833082×
            Some(self.lock_ops()?)
784
        } else {
7858×
            None
786
        };
7873090×
        let Some(parent) = parents.first() else {
788
            // The first operation (init): there is no head yet.
789466×
            if !self.swap_head(&r, None)? {
7902×
                return fail(format!(
791
                    "{} already holds a repository's operation log",
7922×
                    self.store.backend().describe()
793
                ));
794464×
            }
795464×
            return Ok(r);
796
        };
7972624×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
7982624×
        for _ in 0..HEAD_TRIES {
7992624×
            let (current, version) = self.read_head()?;
8002624×
            let to = if current == *parent {
8012613×
                r
802
            } else {
80311×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
80410×
                let merged = Op {
80511×
                    parents: vec![current, r],
80611×
                    hlc: Hlc::now(),
80711×
                    command: format!("{command} (merged with a concurrent operation)"),
80811×
                    view: self.merge_views(&base, &op.view, &theirs)?,
809
                };
81010×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
81110×
                self.store.flush()?;
81210×
                m
813
            };
8142623×
            if self.swap_head(&to, version.as_ref())? {
8152617×
                return Ok(to);
8160×
            }
817
        }
8180×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8193095×
    }
820
821
    /// The operation head's lock, held only while the head pointer moves.
8223091×
    fn lock_ops(&self) -> Result<FileLock> {
8233091×
        fs::create_dir_all(self.oxy.join("ops"))?;
8243091×
        FileLock::acquire(
8253091×
            self.oxy.join("ops").join("lock"),
8263091×
            "another oxy process holds the operation log",
827
        )
8283091×
    }
829
83012712×
    fn head_ref(&self) -> Result<ObjectRef> {
83112712×
        Ok(self.read_head()?.0)
83212712×
    }
833
834
    /// The operation head, and on a store its record's version for
835
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
836
    /// any other store (a bucket, or memory in tests) it is the store's
837
    /// [`HEAD_RECORD`] reference record (oxygen#68).
83815423×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
83915423×
        if self.store.is_local() {
84015404×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
84115404×
            let r = ObjectRef::from_hex(hex.trim())
84215404×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
84315401×
            return Ok((r, None));
84419×
        }
84519×
        let backend = self.store.backend();
84619×
        match backend.read_ref(HEAD_RECORD) {
84719×
            Ok(Some((bytes, version))) => {
84819×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
8490×
                    || {
8500×
                        RepoError::Msg(format!(
8510×
                            "the operation head in {} is corrupt",
8520×
                            backend.describe()
8530×
                        ))
8540×
                    },
8550×
                )?;
85619×
                Ok((r, Some(version)))
857
            }
8580×
            Ok(None) => fail(format!(
859
                "{} holds no operation log (no {HEAD_RECORD} record)",
8600×
                backend.describe()
861
            )),
8620×
            Err(e) => fail(format!("read the operation head: {e}")),
863
        }
86415423×
    }
865
866
    /// Move the operation head to `to` from the `expected` version
867
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
868
    /// disk the caller holds the operations lock and the head always
869
    /// moves; on a store it moves only if the record is unchanged, and
870
    /// `false` says another process moved it first.
8713101×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
8723101×
        if self.store.is_local() {
8733091×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
8743085×
            return Ok(true);
87510×
        }
87610×
        match self
87710×
            .store
87810×
            .backend()
87910×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
880
        {
8817×
            Ok(_) => Ok(true),
8823×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
8830×
            Err(e) => fail(format!("move the operation head: {e}")),
884
        }
8853101×
    }
886
887
    /// Three-way merge of two views that both started from `base` (spec
888
    /// §12.1). A reference only one side changed takes that side's value.
889
    /// When both changed it differently: a bookmark keeps both sides'
890
    /// heads (it may then have several), a change beats a deletion, a
891
    /// workspace changed by both is an error (only one of them matches the
892
    /// files on disk), and otherwise this process's value wins for remote
893
    /// references and the policy, the first value for a tag (tags never
894
    /// move).
89511×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
89638×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
89738×
            b: &BTreeMap<K, V>,
89838×
            o: &BTreeMap<K, V>,
89938×
            t: &BTreeMap<K, V>,
90038×
            mut both: impl FnMut(&V, &V) -> Result<V>,
90138×
        ) -> Result<BTreeMap<K, V>> {
90238×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
90338×
            let mut out = BTreeMap::new();
90439×
            for k in keys {
90539×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
90639×
                let v = if ov == tv || tv == bv {
90719×
                    ov.cloned()
90820×
                } else if ov == bv {
90912×
                    tv.cloned()
910
                } else {
9118×
                    match (ov, tv) {
9128×
                        (Some(x), Some(y)) => Some(both(x, y)?),
9130×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
9140×
                        (None, None) => None,
915
                    }
916
                };
91738×
                if let Some(v) = v {
91838×
                    out.insert(k.clone(), v);
91938×
                }
920
            }
92137×
            Ok(out)
92238×
        }
92311×
        let bookmarks = pick(
92411×
            &base.bookmarks,
92511×
            &ours.bookmarks,
92611×
            &theirs.bookmarks,
9277×
            |x, y| {
9287×
                let mut heads = self.store.get_state(x)?.heads;
9297×
                heads.extend(self.store.get_state(y)?.heads);
9307×
                let heads = self.load_state(&heads)?.maximal(&heads);
9317×
                Ok(self.store.put_state(&StateObject::new(heads))?)
9327×
            },
9330×
        )?;
934
        // Two operations that both replaced one workspace's working copy
935
        // cannot both be right: the files on disk match only one of them.
936
        // The working-copy lock keeps this from happening; should it happen
937
        // anyway, this operation is not recorded.
93811×
        let workspaces = pick(
93911×
            &base.workspaces,
94011×
            &ours.workspaces,
94111×
            &theirs.workspaces,
9421×
            |_, _| {
9431×
                fail(
944
                    "another oxy process changed this working copy at the same time; \
945
                     this command was not recorded: check `oxy status` and run it again",
946
                )
9471×
            },
9481×
        )?;
94910×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
95010×
        let empty = BTreeMap::new();
95110×
        let names: BTreeSet<&String> = base
95210×
            .remotes
95310×
            .keys()
95410×
            .chain(ours.remotes.keys())
95510×
            .chain(theirs.remotes.keys())
95610×
            .collect();
95710×
        let mut remotes = BTreeMap::new();
95810×
        for n in names {
9596×
            let m = pick(
9606×
                base.remotes.get(n).unwrap_or(&empty),
9616×
                ours.remotes.get(n).unwrap_or(&empty),
9626×
                theirs.remotes.get(n).unwrap_or(&empty),
9630×
                |x, _| Ok(*x),
9640×
            )?;
9656×
            if !m.is_empty() {
9666×
                remotes.insert(n.clone(), m);
9676×
            }
968
        }
96910×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
97010×
            ours.policy
9710×
        } else if ours.policy == base.policy {
9720×
            theirs.policy
973
        } else {
9740×
            ours.policy.or(theirs.policy)
975
        };
97610×
        self.store.flush()?;
97710×
        Ok(View {
97810×
            bookmarks,
97910×
            workspaces,
98010×
            remotes,
98110×
            policy,
98210×
            tags,
98310×
        })
98411×
    }
985
98642×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
98742×
        let mut out = Vec::new();
98842×
        let (mut r, mut op) = self.head_op()?;
989
        loop {
990241×
            let next = op.parents.first().copied();
991241×
            out.push((r, op));
992241×
            match next {
993199×
                Some(p) => {
994199×
                    r = p;
995199×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
996
                }
99742×
                None => break,
998
            }
999
        }
100042×
        Ok(out)
100142×
    }
1002
1003
    /// Undo the last user command (spec §12.1). Operations that only recorded
1004
    /// a working-copy snapshot are skipped, since the files are still on disk
1005
    /// and the next snapshot recreates them, and a command's own checkout
1006
    /// (`… (checkout)`) goes with the command. When the working copy is
1007
    /// clean and was clean after the operation undone to, its files follow
1008
    /// too, since nothing on disk can be lost; otherwise they stay as they
1009
    /// are (an undone commit's edits come back as uncommitted work).
101010×
    pub fn undo(&self) -> Result<Op> {
101110×
        let _wc = self.lock_working_copy()?;
101210×
        let clean_now =
101310×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
101410×
        let (read_head, mut op) = self.head_op()?;
101510×
        let wc_now = op.view.workspaces.get(&self.workspace).copied();
101610×
        let up = |op: Op| -> Result<Option<Op>> {
10177×
            match op.parents.first() {
10187×
                Some(p) => Ok(Some(Op::decode(&self.store.get_typed(p, ObjectType::Op)?)?)),
10190×
                None => Ok(None),
1020
            }
10217×
        };
1022
        loop {
102317×
            while op.is_snapshot() {
10245×
                match up(op.clone())? {
10255×
                    Some(p) => op = p,
10260×
                    None => break,
1027
                }
1028
            }
102912×
            if !op.command.ends_with(" (checkout)") {
103010×
                break;
10312×
            }
10322×
            match up(op.clone())? {
10332×
                Some(p) => op = p,
10340×
                None => break,
1035
            }
1036
        }
103710×
        let Some(parent) = op.parents.first() else {
10381×
            return fail("nothing to undo");
1039
        };
10409×
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1041
        {
10429×
            let _lock = if self.store.is_local() {
10439×
                Some(self.lock_ops()?)
1044
            } else {
10450×
                None
1046
            };
10479×
            let (now, version) = self.read_head()?;
10489×
            if now != read_head || !self.swap_head(parent, version.as_ref())? {
10490×
                return fail("another oxy command ran while undoing; run undo again");
10509×
            }
1051
        }
10529×
        self.drop_manifest();
10539×
        if let Some(then) = parent_op.view.workspaces.get(&self.workspace) {
10549×
            if clean_now && Some(*then) != wc_now {
10556×
                let wc = self.store.get_change(then)?;
10566×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
10574×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1058
                    // The files differ from the restored working copy by
1059
                    // exactly what the undone command did: nothing else is
1060
                    // on disk, as the working copy was clean.
10614×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
10622×
                }
10633×
            }
10640×
        }
10659×
        Ok(parent_op)
106610×
    }
1067
1068
    /// The last operation that was not a snapshot.
10692×
    pub fn last_command(&self) -> Result<Op> {
10702×
        let (_, mut op) = self.head_op()?;
10714×
        while op.is_snapshot() {
10722×
            let Some(parent) = op.parents.first() else {
10730×
                break;
1074
            };
10752×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1076
        }
10772×
        Ok(op)
10782×
    }
1079
1080
    // ------------------------------------------------------------ states
1081
1082
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1083196×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1084196×
        if let Some(st) = self.load_state_checkpointed(heads)? {
10854×
            return Ok(st);
1086191×
        }
1087191×
        self.load_state_full(heads)
1088196×
    }
1089
1090
    /// The state of `heads` for its history (changes, tree, metadata) with
1091
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1092
    /// and friends. Build the graphs a command needs with
1093
    /// [`Repo::load_graphs_of`].
10941392×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
10951392×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
109630×
            return Ok(st);
10971362×
        }
10981362×
        self.load_state_replayed(heads, State::new_history_only())
10991392×
    }
1100
1101
    /// Build these file graphs in a history-only state.
11021618×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
11031618×
        Ok(state.load_graphs(
11041618×
            nodes,
110554×
            |refs| {
110654×
                self.read_blobs(refs).map_err(|e| {
11073×
                    crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
11083×
                })
110954×
            },
11101918×
            |h| self.change_bytes(h),
11113×
        )?)
11121618×
    }
1113
1114
    /// The graphs of `nodes` of a history-only state, built beside it (see
1115
    /// [`State::build_graphs_detached`]).
111673×
    pub fn build_graphs_detached(
111773×
        &self,
111873×
        state: &State,
111973×
        nodes: &[crate::ids::NodeId],
112073×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
112173×
        Ok(state
112273×
            .build_graphs_detached(
112373×
                nodes,
11240×
                |refs| {
11250×
                    self.read_blobs(refs).map_err(|e| {
11260×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
11270×
                    })
11280×
                },
112985×
                |h| self.change_bytes(h),
11300×
            )?
113173×
            .into_iter()
113273×
            .collect())
113373×
    }
1134
1135
    /// The contents of texts [`State::single_text`] gave: blobs read in
1136
    /// one go, inline ones from their changes.
1137340×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1138
        use crate::objects::TextRef;
1139340×
        let refs: Vec<ObjectRef> = texts
1140340×
            .iter()
11415556×
            .filter_map(|t| match t {
11421×
                TextRef::Blob(r, _, _) => Some(*r),
11435555×
                TextRef::Inline { .. } => None,
11445556×
            })
1145340×
            .collect();
1146340×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1147340×
        let mut out = Vec::with_capacity(texts.len());
11485556×
        for t in texts {
11495556×
            let lines = match t {
11501×
                TextRef::Blob(_, count, form) => {
11511×
                    let content = blobs
11521×
                        .next()
11531×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
11541×
                    crate::objects::text_lines(&content, *count, *form)?
1155
                }
11565555×
                TextRef::Inline { change, start, end } => {
11575555×
                    let bytes = self.change_bytes(change)?;
11585555×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
11590×
                        RepoError::Msg("an inline insert lies outside its change".into())
11600×
                    })?;
11615555×
                    crate::objects::inline_lines(range)?
1162
                }
1163
            };
11645556×
            out.push(lines.bytes().to_vec());
1165
        }
1166340×
        Ok(out)
1167340×
    }
1168
1169
    /// Build every graph a history-only state still lacks, making it full.
11701605×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
11711605×
        Ok(state.load_all_graphs(
117216×
            |refs| {
117316×
                self.read_blobs(refs).map_err(|e| {
11740×
                    crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
11750×
                })
117616×
            },
11773461×
            |h| self.change_bytes(h),
11780×
        )?)
11791605×
    }
1180
1181
    /// A change's encoding, for building graphs of its inline inserts. The
1182
    /// last few read are kept: a checkout building graphs a batch at a
1183
    /// time reads the same large changes for every batch, often in turn.
118411019×
    fn change_bytes(
118511019×
        &self,
118611019×
        h: &ChangeHash,
118711019×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
118811019×
        let mut cache = self.last_change.borrow_mut();
118919445×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
11908546×
            let hit = cache.remove(i);
11918546×
            let b = hit.1.clone();
11928546×
            cache.push(hit);
11938546×
            return Ok(b);
11942473×
        }
11952473×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
11960×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
11970×
        })?);
11982473×
        cache.push((*h, b.clone()));
1199
        // The last few, within a memory budget; the newest always stays.
12004023×
        while cache.len() > CHANGE_CACHE_COUNT
12012473×
            || (cache.len() > 1
12027594×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
12031550×
        {
12041550×
            cache.remove(0);
12051550×
        }
12062473×
        Ok(b)
120711019×
    }
1208
1209
    /// Load the dependency closure of `heads` change by change.
1210245×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1211245×
        self.load_state_replayed(heads, State::new())
1212245×
    }
1213
12142873×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
12152873×
        let history = state.is_history_only();
12162873×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
12172873×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1218
        {
12192873×
            let _t = crate::timing::phase("load: read and add changes");
12202873×
            let (mut read, mut add, mut fetch) = (
12212873×
                std::time::Duration::ZERO,
12222873×
                std::time::Duration::ZERO,
12232873×
                std::time::Duration::ZERO,
12242873×
            );
122511798×
            while let Some(h) = stack.pop() {
1226
                // A change the state holds brings its history with it.
12278928×
                if !seen.insert(h) || state.contains(&h) {
12282128×
                    continue;
12296800×
                }
12306800×
                let t0 = std::time::Instant::now();
1231
                // A history-only state reads text only for the graphs it
1232
                // builds; either way the hash is the one asked for.
12336800×
                let (c, texts) = if history {
12345488×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
12355487×
                    fetch += t0.elapsed();
12365487×
                    Change::decode_skeleton(&bytes, h)
12375487×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1238
                } else {
12391312×
                    (self.store.get_change(&h)?, Vec::new())
1240
                };
12416797×
                read += t0.elapsed();
12426797×
                stack.extend(c.deps.iter().copied());
12436797×
                let t1 = std::time::Instant::now();
12446797×
                state.add_known(h, c, texts);
12456797×
                add += t1.elapsed();
1246
            }
12472870×
            crate::timing::record("load:   of which reading", read);
12482870×
            crate::timing::record("load:     of which fetching", fetch);
12492870×
            crate::timing::record("load:   of which applying", add);
1250
        }
12512870×
        let _t = crate::timing::phase("load: validate");
12522870×
        state.validate()?;
12532870×
        Ok(state)
12542873×
    }
1255
12562092×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
12572092×
        if self.bare {
12582×
            return fail("this is a bare repository: it has no working copy");
12592090×
        }
12602090×
        let view = self.view()?;
12612090×
        let h = *view
12622090×
            .workspaces
12632090×
            .get(&self.workspace)
12642090×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
12652089×
        Ok((h, self.store.get_change(&h)?))
12662092×
    }
1267
1268
    /// Heads of a bookmark's state (spec §10.1).
12691661×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
12701661×
        match view.bookmarks.get(bookmark) {
12711661×
            Some(st) => Ok(self.store.get_state(st)?.heads),
12720×
            None => Ok(vec![]),
1273
        }
12741661×
    }
1275
1276465×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1277465×
        self.heads_of(&self.view()?, &self.config.bookmark)
1278465×
    }
1279
1280
    // ------------------------------------------------------------ blobs
1281
1282364×
    fn blob_for(content: &[u8]) -> Blob {
1283364×
        Blob::of(content)
1284364×
    }
1285
1286233×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1287233×
        Self::blob_for(content).hash()
1288233×
    }
1289
1290129×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1291152×
        for c in crate::chunk::chunks(content) {
1292152×
            self.store.put_chunk(c)?;
1293
        }
1294129×
        Ok(self
1295129×
            .store
1296129×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1297129×
    }
1298
1299
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1300
    /// all their chunks, are read in parallel; a blob the store lacks goes
1301
    /// through [`Repo::read_blob`], which may fetch it lazily.
1302414×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1303414×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1304414×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
130580×
            blobs.push(match got {
130675×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
13070×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
13085×
                Err(crate::store::StoreError::NotFound(_)) => None,
13090×
                Err(e) => return Err(e.into()),
1310
            });
1311
        }
1312414×
        let chunk_refs: Vec<ObjectRef> = blobs
1313414×
            .iter()
1314414×
            .flatten()
1315414×
            .flat_map(|b| b.chunks.iter().copied())
1316414×
            .collect();
1317414×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1318414×
        let mut out = Vec::with_capacity(refs.len());
1319414×
        for (r, blob) in refs.iter().zip(blobs) {
132080×
            match blob {
13215×
                None => out.push(self.read_blob(r)?),
132275×
                Some(b) => {
132375×
                    let mut content = Vec::with_capacity(b.length as usize);
1324114×
                    for c in &b.chunks {
1325114×
                        match chunks.next() {
1326114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
13270×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
13280×
                            Some(Err(e)) => return Err(e.into()),
13290×
                            None => return fail("chunk list ended early"),
1330
                        }
1331
                    }
133275×
                    out.push(content);
1333
                }
1334
            }
1335
        }
1336409×
        Ok(out)
1337414×
    }
1338
1339
    /// Read a blob's content, fetching it from the remote that withheld it
1340
    /// when it is lazily absent (spec §13.5).
1341107×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1342107×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
13434×
            self.fetch_lazy_blob(r)?;
1344103×
        }
1345107×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1346102×
        let mut out = Vec::with_capacity(blob.length as usize);
1347109×
        for c in &blob.chunks {
1348109×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1349
        }
1350102×
        Ok(out)
1351107×
    }
1352
1353
    // ------------------------------------------------------------ working copy
1354
1355
    /// Attributes from the `.oxyattributes` files in the working directory.
13562×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1357
        // Nested repositories and ignored paths are left out, as in a walk.
13588×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
13592×
        let files: Vec<(String, Vec<u8>)> = listing
13602×
            .files
13612×
            .into_iter()
13622×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
13632×
            .collect();
13642×
        crate::attributes::Attributes::from_files(
13652×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1366
        )
13672×
    }
1368
1369
    /// Folders holding a repository of their own that the last look at the
1370
    /// working copy left out, not being subrepos (oxygen#43).
137124×
    pub fn untracked_nested(&self) -> Vec<String> {
137224×
        self.untracked_nested.borrow().clone()
137324×
    }
1374
1375
    /// Attributes from a materialized state's `.oxyattributes` files.
13763×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
13776×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
13786×
            match &f.content {
13796×
                FileContent::Text { bytes, .. }
13806×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1381
                {
13820×
                    Some((p.as_str(), bytes.as_slice()))
1383
                }
13846×
                _ => None,
1385
            }
13866×
        }))
13873×
    }
1388
1389
    /// Store a blob, raw when the path is `nocompress`.
1390113×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1391113×
        if !nocompress {
1392111×
            return self.store_blob(content);
13932×
        }
13942×
        for c in crate::chunk::chunks(content) {
13952×
            self.store.put_chunk_nocompress(c)?;
1396
        }
13972×
        Ok(self
13982×
            .store
13992×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1400113×
    }
1401
1402
    /// This workspace's state index (oxygen#41): its working copy's base,
1403
    /// saved so a snapshot reads it rather than replaying history.
1404
    /// The state index of the state with these heads: this workspace keeps
1405
    /// the last few it used, named by their heads, so moving between two
1406
    /// states finds both.
14072190×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
14082190×
        let mut heads = heads.to_vec();
14092190×
        heads.sort();
14102190×
        let mut h = blake3::Hasher::new();
14112259×
        for c in &heads {
14122259×
            h.update(&c.0);
14132259×
        }
14142190×
        self.oxy.join("index").join(format!(
14152190×
            "{}{}",
14162190×
            self.state_index_prefix(),
14172190×
            &h.finalize().to_hex()[..16]
14182190×
        ))
14192190×
    }
1420
14214321×
    fn state_index_prefix(&self) -> String {
14224321×
        format!("state-{}-", self.workspace.to_hex())
14234321×
    }
1424
1425
    /// This workspace's state indexes, newest first.
14262131×
    fn state_indexes(&self) -> Vec<PathBuf> {
14272131×
        let prefix = self.state_index_prefix();
14282131×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
14292131×
            .into_iter()
14302131×
            .flatten()
14312131×
            .flatten()
14322131×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
14332131×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
14342131×
            .collect();
14352131×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
14362131×
        found.into_iter().map(|(_, p)| p).collect()
14372131×
    }
1438
1439
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1440
    /// from this workspace's state index when it holds that history: every
1441
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1442
    /// is loaded from history and indexed for next time.
14431833×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
14441833×
        if let Some((st, heads)) = self.read_state_index(deps) {
14451482×
            let mut have = st.maximal(deps);
14461482×
            have.sort();
14471482×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1448
                #[cfg(test)]
1449106×
                assert_eq!(
1450106×
                    st.write_index(),
1451106×
                    self.load_state_history(deps)?.write_index(),
1452
                    "a state index holds the state history gives"
1453
                );
1454216×
                return Ok(st);
14551266×
            }
1456
            // An index a few changes behind (a commit, a pull since): add
1457
            // what it lacks, as long as all it holds is history of `deps`.
1458
            // Anything amiss (a change beyond a shallow boundary) takes the
1459
            // long way instead.
14601266×
            let (indexed, started) = (st.len(), std::time::Instant::now());
14611266×
            if let Ok(st) = self.load_state_replayed(deps, st) {
14621265×
                let mut all = deps.to_vec();
14631265×
                all.extend(heads.iter().copied());
14641265×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
14651265×
                within.sort();
14661265×
                want.sort();
14671265×
                if within == want {
1468
                    #[cfg(test)]
1469597×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1470
                    // Writing the index costs far more than replaying a
1471
                    // few small changes: it is rewritten once it falls
1472
                    // behind, or when replaying took long (large changes).
14731263×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
14741263×
                        || started.elapsed() > INDEX_REPLAY_TIME
14753×
                    {
14763×
                        self.write_state_index(deps, &st);
14771260×
                    }
14781263×
                    return Ok(st);
14792×
                }
14801×
            }
1481351×
        }
1482354×
        let st = self.load_state_history(deps)?;
1483354×
        self.write_state_index(deps, &st);
1484354×
        Ok(st)
14851833×
    }
1486
1487
    /// Two history-only states hold the same changes and render the same
1488
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1489
    /// the checkpoint's graphs as the bases of its files' histories.
1490
    #[cfg(test)]
1491597×
    fn assert_same_state(&self, a: &State, b: &State) {
14921194×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1493597×
        assert_eq!(ids(a), ids(b), "the same changes");
14941194×
        let files = |s: &State| {
14951194×
            let mut s = s.clone();
14961194×
            self.load_all_graphs(&mut s).unwrap();
14971194×
            s.materialize().files
14981194×
        };
1499597×
        assert_eq!(files(a), files(b), "the same files");
1500597×
    }
1501
1502
    /// The state index file: its heads, a hash of its changes block and one
1503
    /// of the rest, then the body [`State::write_index`] gives, whose first
1504
    /// block is the changes. Hashed in two parts so the log can read and
1505
    /// check the changes alone.
1506
    /// The index of `deps` if there is one, else the newest, which the
1507
    /// caller may bring up to date.
15081833×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
15091833×
        let _t = crate::timing::phase("load: state index");
15101833×
        let exact = self.state_index_path(deps);
15111833×
        let bytes = match fs::read(&exact) {
1512216×
            Ok(b) => {
1513
                // Used now: the newest, so the last to be dropped.
1514216×
                let _ = fs::File::options()
1515216×
                    .write(true)
1516216×
                    .open(&exact)
1517216×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1518216×
                b
1519
            }
15201617×
            Err(_) => fs::read(self.state_indexes().first()?).ok()?,
1521
        };
15221482×
        let mut r = crate::flat::Reader::new(&bytes);
15231482×
        let mut heads = Vec::new();
15241482×
        for _ in 0..r.count().ok()? {
152568×
            heads.push(r.object().ok()?);
1526
        }
15271482×
        let (changes_sum, rest_sum) = (r.object().ok()?, r.object().ok()?);
15281482×
        let body = &bytes[4 + 32 * heads.len() + 64..];
15291482×
        let split = 4 + r.count().ok()?;
1530
        // Checked whole, so a part decoded later (the tree's maps, a
1531
        // file's history) can trust its bytes.
15321482×
        let (changes, rest) = (body.get(..split)?, body.get(split..)?);
15331482×
        let mut h = blake3::Hasher::new();
15341482×
        h.update_rayon(rest);
15351482×
        if *blake3::hash(changes).as_bytes() != changes_sum.0
15361482×
            || *h.finalize().as_bytes() != rest_sum.0
1537
        {
15380×
            return None;
15391482×
        }
15401482×
        Some((State::read_index(body).ok()?, heads))
15411833×
    }
1542
1543
    /// The changes of this workspace's state index (the closure of its
1544
    /// heads), read without the rest of the index.
1545157×
    pub(crate) fn read_state_index_changes(
1546157×
        &self,
1547157×
    ) -> Option<std::collections::HashMap<ChangeHash, std::sync::Arc<crate::state::ChangeMeta>>>
1548
    {
1549
        use std::io::Read;
1550157×
        let _t = crate::timing::phase("load: state index changes");
1551157×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1552143×
        let mut word = [0u8; 4];
1553143×
        f.read_exact(&mut word).ok()?;
1554143×
        let n = u32::from_le_bytes(word) as usize;
1555143×
        let mut head = vec![0u8; 32 * n + 64 + 4];
1556143×
        f.read_exact(&mut head).ok()?;
1557143×
        let sum = &head[32 * n..32 * n + 32];
1558143×
        let len = u32::from_le_bytes(head[32 * n + 64..].try_into().unwrap()) as usize;
1559143×
        let mut changes = vec![0u8; 4 + len];
1560143×
        changes[..4].copy_from_slice(&head[32 * n + 64..]);
1561143×
        f.read_exact(&mut changes[4..]).ok()?;
1562143×
        if blake3::hash(&changes).as_bytes() != sum {
15630×
            return None;
1564143×
        }
1565143×
        State::read_index_changes(&changes[4..]).ok()
1566157×
    }
1567
1568
    /// Save `st`, the history-only state of `deps`, as this workspace's
1569
    /// state index; quietly nothing when it cannot be (it is only a cache).
1570357×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1571357×
        let _t = crate::timing::phase("write: state index");
1572357×
        let encoding = crate::timing::phase("write:   of which encoding");
1573357×
        let Some(body) = st.write_index() else {
15740×
            return;
1575
        };
1576357×
        drop(encoding);
1577
        #[cfg(test)]
1578170×
        assert_eq!(
1579170×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1580170×
            Some(body.clone()),
1581
            "a state index reads back as written"
1582
        );
1583357×
        let mut heads = st.maximal(deps);
1584357×
        heads.sort();
1585357×
        let mut w = crate::flat::Writer::default();
1586357×
        w.count(heads.len());
1587357×
        for h in &heads {
158812×
            w.object(h);
158912×
        }
1590357×
        let split = 4 + u32::from_le_bytes(body[..4].try_into().unwrap()) as usize;
1591357×
        w.fixed(blake3::hash(&body[..split]).as_bytes());
1592357×
        let mut sum = blake3::Hasher::new();
1593357×
        sum.update_rayon(&body[split..]);
1594357×
        w.fixed(sum.finalize().as_bytes());
1595357×
        w.fixed(&body);
1596357×
        let path = self.state_index_path(&heads);
1597357×
        let _ = fs::create_dir_all(self.oxy.join("index"));
1598357×
        let _ = write_cache(&path, &w.0);
1599
        // The last two used: the index of a state moved away from stays for
1600
        // a move back. Older ones (and the unnamed one of before) go.
1601357×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
16021×
            let _ = fs::remove_file(old);
16031×
        }
1604357×
        let _ = fs::remove_file(
1605357×
            self.oxy
1606357×
                .join("index")
1607357×
                .join(format!("state-{}", self.workspace.to_hex())),
1608357×
        );
1609357×
    }
1610
16116×
    fn locks_dir(&self) -> PathBuf {
16126×
        self.oxy.join("locks")
16136×
    }
1614
1615
    /// Whether `path` is locked locally for editing (spec §18, advisory).
16163×
    pub fn is_locked(&self, path: &str) -> bool {
16173×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
16183×
    }
1619
1620
    /// Take the advisory local lock on a `lockable` file and make it writable.
16212×
    pub fn lock_path(&self, path: &str) -> Result<()> {
16222×
        let attrs = self.disk_attributes();
16232×
        if !attrs.lookup(path).lockable {
16241×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
16251×
        }
16261×
        fs::create_dir_all(self.locks_dir())?;
16271×
        write_atomic(
16281×
            &self.locks_dir().join(path.replace('/', "%2F")),
16291×
            std::process::id().to_string().as_bytes(),
16300×
        )?;
16311×
        set_readonly(&self.root.join(path), false)?;
16321×
        Ok(())
16332×
    }
1634
1635
    /// Release the local lock and make the file read-only again.
16361×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
16371×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
16381×
        if self.root.join(path).exists() {
16391×
            set_readonly(&self.root.join(path), true)?;
16400×
        }
16411×
        Ok(())
16421×
    }
1643
1644
    /// Whether a repository path is inside the sparse filter (spec §17).
164524237×
    pub fn in_scope(&self, path: &str) -> bool {
164624237×
        self.config.sparse_paths.is_empty()
164782×
            || self
164882×
                .config
164982×
                .sparse_paths
165082×
                .iter()
165199×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
165224237×
    }
1653
16541×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
16551×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
16561×
    }
1657
1658
    /// Walk the working copy; with a manifest, a file whose size and mtime
1659
    /// match it is not read: an opaque file yields its known blob, and a
1660
    /// text file whose recorded graph key equals its base graph's key in
1661
    /// `keys` (path → key) is marked unchanged; other text files are read
1662
    /// but keep their known hash. Files modified within two seconds of the
1663
    /// manifest are never trusted (a racy stat).
1664
    ///
1665
    /// `.oxyattributes` files are always read, since their content is
1666
    /// needed; and when any of them is not known unchanged (added, removed,
1667
    /// edited, or changed in the base), no text file is taken as unchanged,
1668
    /// because attributes decide how a file compares with the base.
1669
    ///
1670
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
1671
    /// (the base state's files) that exists on disk is included even when
1672
    /// an ignore rule matches it, as in Git.
16731170×
    fn walk_working_copy_with(
16741170×
        &self,
16751170×
        cache: Option<&prompt::Manifest>,
16761170×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
16771170×
        keys: Option<&KeyOf>,
16781170×
    ) -> Result<BTreeMap<String, FsEntry>> {
1679
        let mut out: BTreeMap<String, FsEntry>;
16801170×
        let sparse = &self.config.sparse_paths;
16819066×
        let in_scope = |p: &str| {
16829066×
            sparse.is_empty()
16837×
                || sparse
16847×
                    .iter()
16857×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
16869066×
        };
16871170×
        let walk_phase = crate::timing::phase("walk:   of which listing");
1688
        let walk::Listing {
16891170×
            files,
16901170×
            symlinks,
16911170×
            nested,
16921170×
            dirs,
16931170×
        } = match self.listing_cache.take() {
1694139×
            Some(l) => l,
1695
            // Ignore rules apply to untracked paths only, so the base's
1696
            // files are not matched against them (an added file is: a rule
1697
            // written after it was snapshotted leaves it out again).
16989078×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
1699
        };
17001170×
        let keys = keys.filter(|k| {
170111960×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
17021167×
            let attrs_unchanged =
17031167×
                files
17041167×
                    .iter()
170511941×
                    .filter(|(r, _, _)| is_attributes(r))
17061167×
                    .all(|(rel, _, meta)| {
17079×
                        stat_cached(rel, meta, cache)
17089×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
17099×
                    });
17101167×
            let none_removed = tracked
17111167×
                .keys()
17129012×
                .filter(|r| is_attributes(r))
17131167×
                .all(|r| on_disk.contains(r.as_str()));
17141167×
            attrs_unchanged && none_removed
17151167×
        });
17161170×
        *self.walked_dirs.borrow_mut() =
17171170×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
17181170×
        drop(walk_phase);
17191170×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
1720
        // Reading files is most of a walk's cost; do it in parallel.
1721
        {
1722
            use rayon::prelude::*;
17231170×
            let mut read: Vec<(String, FsEntry)> = files
17241170×
                .par_iter()
172511972×
                .map(|(rel, path, meta)| {
1726
                    // A key is worked out only for a file the manifest
1727
                    // knows with the same stat and a key of its own.
172811972×
                    let key = keys
172911972×
                        .filter(|_| !is_attributes(rel))
173011972×
                        .filter(|_| {
173111932×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
173211932×
                        })
173311972×
                        .and_then(|k| k(rel));
173411972×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
173511972×
                })
17361170×
                .collect::<Result<Vec<_>>>()?;
173711970×
            for (rel, e) in read.iter_mut() {
1738
                // A cached blob the store lost (gc, a partial clone): read the file after all.
173911970×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
17400×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
17410×
                    e.blob = None;
174211970×
                }
1743
            }
1744
            // The listing is in path order, so the map is built without
1745
            // searching.
17461169×
            out = read.into_iter().collect();
17471169×
            for (rel, target) in symlinks {
17482×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
17492×
            }
1750
        }
17511169×
        drop(_read_phase);
17521169×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
1753
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
1754
        // already tracked as subrepo nodes, they contribute their pin;
1755
        // unregistered ones are left alone.
17561169×
        let modules = self.modules_on_disk();
17571169×
        let removed = self.removed_subrepos();
17581169×
        for rel in &removed {
17593×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
17601×
                self.clear_removed_subrepo(rel);
17612×
            }
1762
        }
17631169×
        let mut untracked_nested = Vec::new();
17641169×
        for dir in nested {
176523×
            let rel = self.rel_path(&dir);
176623×
            if !self.in_scope(&rel) || removed.contains(&rel) {
17673×
                continue;
176820×
            }
176920×
            let registered = modules.entries.get(&rel);
177020×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
1771
            {
17721×
                untracked_nested.push(rel);
17731×
                continue;
177419×
            }
177519×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
177619×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
1777
        }
17781169×
        untracked_nested.sort();
17791169×
        *self.untracked_nested.borrow_mut() = untracked_nested;
1780
        // Tracked paths the ignore rules hid.
17811169×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
178272×
            if !self.in_scope(rel) {
178310×
                continue;
178462×
            }
178562×
            let path = self.root.join(rel);
178662×
            if *kind == NodeKind::Subrepo {
17874×
                if removed.contains(rel) {
17882×
                    continue;
17892×
                }
17902×
                let present =
17912×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
17922×
                if present {
17930×
                    let pin = subrepos::read_pin(
17940×
                        &path,
17950×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
17960×
                    )?;
17970×
                    out.insert(
17980×
                        rel.clone(),
17990×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
1800
                    );
18012×
                } else if let Some(b) = blob {
18022×
                    // Not cloned (or emptied): the pin stays as recorded, as a
18032×
                    // Git gitlink does when its directory is absent.
18042×
                    out.insert(
18052×
                        rel.clone(),
18062×
                        FsEntry {
18072×
                            blob: Some(*b),
18082×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
18092×
                        },
18102×
                    );
18112×
                }
18122×
                continue;
181358×
            }
181458×
            let Ok(meta) = fs::symlink_metadata(&path) else {
181558×
                continue;
1816
            };
18170×
            let ft = meta.file_type();
18180×
            if ft.is_symlink() {
18190×
                let target = fs::read_link(&path)?;
18200×
                out.insert(
18210×
                    rel.clone(),
18220×
                    FsEntry::new(
18230×
                        NodeKind::Symlink,
1824
                        false,
18250×
                        target.to_string_lossy().as_bytes().to_vec(),
1826
                    ),
1827
                );
18280×
            } else if ft.is_file() {
18290×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
18300×
                out.insert(rel.clone(), e);
18310×
            }
1832
        }
18331169×
        Ok(out)
18341170×
    }
1835
1836
    /// The entry for one regular file, read or served from the stat cache.
18370×
    fn file_entry(
18380×
        &self,
18390×
        rel: &str,
18400×
        path: &Path,
18410×
        meta: &walk::Stat,
18420×
        cache: Option<&prompt::Manifest>,
18430×
    ) -> Result<FsEntry> {
18440×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
18450×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
18460×
            e.content = std::sync::Arc::new(fs::read(path)?);
18470×
            e.blob = None;
18480×
        }
18490×
        Ok(e)
18500×
    }
1851
1852
    /// The non-directory paths of a snapshot with their kinds, for the
1853
    /// walker's `tracked` set.
18542×
    pub(crate) fn tracked_kinds(
18552×
        snapshot: &Snapshot,
18562×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
18572×
        snapshot
18582×
            .files
18592×
            .iter()
186012×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
18618×
            .map(|(p, f)| {
18628×
                let blob = match &f.content {
18634×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
18644×
                    _ => None,
1865
                };
18668×
                (p.clone(), (f.kind, blob))
18678×
            })
18682×
            .collect()
18692×
    }
1870
1871
    /// A path under the root as a `/`-separated relative string.
187252×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
187352×
        path.strip_prefix(&self.root)
187452×
            .unwrap_or(path)
187552×
            .components()
187698×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
187752×
            .collect::<Vec<_>>()
187852×
            .join("/")
187952×
    }
1880
}
1881
1882
impl Repo {
1883
    /// Changes reachable from the bookmark and the working copy, newest first.
188482×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
188582×
        let heads = self.bookmark_heads()?;
188682×
        if self.bare {
18871×
            return self.log_state(&heads);
188881×
        }
188981×
        let (wc_hash, _) = self.working_copy()?;
189081×
        let mut all = heads.clone();
189181×
        all.push(wc_hash);
189281×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
189381×
        let mut entries: Vec<LogEntry> = Vec::new();
1894
        // A shallow clone knows changes beyond its boundary from a
1895
        // checkpoint's metadata only: its log comes from the state.
189681×
        let metas = if self.is_shallow() {
18971×
            self.load_state_history(&all)?
18981×
                .changes()
18999×
                .map(|(h, m)| (*h, m.clone()))
19001×
                .collect()
1901
        } else {
190280×
            self.metas_of(&all)?
1903
        };
1904386×
        for (h, meta) in metas {
1905386×
            entries.push(LogEntry {
1906386×
                hash: h,
1907386×
                change: meta,
1908386×
                is_working_copy: h == wc_hash,
1909386×
                is_head: head_set.contains(&h),
1910386×
            });
1911386×
        }
1912537×
        entries.sort_by(|a, b| {
1913537×
            b.is_working_copy
1914537×
                .cmp(&a.is_working_copy)
1915537×
                .then(b.change.hlc.cmp(&a.change.hlc))
1916537×
                .then(b.hash.cmp(&a.hash))
1917537×
        });
191881×
        Ok(entries)
191982×
    }
1920
1921
    /// A window of `log_state`: entries `offset..offset+limit` and the total
1922
    /// count, for paginated views.
19230×
    pub fn log_window(
19240×
        &self,
19250×
        heads: &[ChangeHash],
19260×
        offset: usize,
19270×
        limit: usize,
19280×
    ) -> Result<(Vec<LogEntry>, usize)> {
19290×
        let all = self.log_state(heads)?;
19300×
        let total = all.len();
19310×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
19320×
    }
1933
1934
    /// The log of the state with these heads, newest first, with no working
1935
    /// copy involved (for hosted repositories and any explicit state).
19367×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1937
        // The log needs change metadata only: neither graphs nor the tree.
19387×
        if self.is_shallow() {
19390×
            return Ok(self.log_of(&self.load_state_history(heads)?));
19407×
        }
19417×
        let metas = self.metas_of(heads)?;
19427×
        let depended: BTreeSet<ChangeHash> = metas
19437×
            .iter()
194416×
            .flat_map(|(_, m)| m.deps.iter().copied())
19457×
            .collect();
19467×
        let mut entries: Vec<LogEntry> = metas
19477×
            .into_iter()
19487×
            .map(|(h, meta)| LogEntry {
194916×
                hash: h,
195016×
                is_head: !depended.contains(&h),
195116×
                change: meta,
1952
                is_working_copy: false,
195316×
            })
19547×
            .collect();
195511×
        entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
19567×
        Ok(entries)
19577×
    }
1958
1959
    /// Every change of the state with these heads and its metadata, read
1960
    /// without its operations ([`Store::get_change_meta`]). A change beyond
1961
    /// a shallow clone's boundary is left out.
1962157×
    pub fn metas_of(
1963157×
        &self,
1964157×
        heads: &[ChangeHash],
1965157×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
1966157×
        let boundary = self.boundary();
1967
        // The state index holds the metadata of its heads' closure: a
1968
        // change found there is not read from the store (a change object
1969
        // can be as large as the tree it adds).
1970157×
        let indexed = self.read_state_index_changes();
1971157×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
1972157×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
1973157×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1974157×
        let mut out = Vec::new();
19751253×
        while let Some(h) = stack.pop() {
19761096×
            if !seen.insert(h) {
1977428×
                continue;
1978668×
            }
1979668×
            if let Some(meta) = indexed.as_ref().and_then(|m| m.get(&h)) {
1980
                #[cfg(test)]
19810×
                assert_eq!(
19820×
                    **meta,
19830×
                    self.store.get_change_meta(&h)?,
1984
                    "the state index holds a change's metadata"
1985
                );
19860×
                stack.extend(meta.deps.iter().copied());
19870×
                out.push((h, (**meta).clone()));
19880×
                continue;
1989668×
            }
1990668×
            let started = std::time::Instant::now();
1991668×
            let meta = match self.store.get_change_meta(&h) {
1992668×
                Ok(m) => m,
19930×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
19940×
                Err(e) => return Err(e.into()),
1995
            };
1996668×
            stored += 1;
1997668×
            from_store += started.elapsed();
1998668×
            stack.extend(meta.deps.iter().copied());
1999668×
            out.push((h, meta));
2000
        }
2001157×
        if stored > 0 && crate::timing::enabled() {
20020×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2003157×
        }
2004157×
        Ok(out)
2005157×
    }
2006
2007
    /// The log of a state already loaded, newest first.
2008
    /// The history of lines `first..=last` (1-based) of `path` in the
2009
    /// state `heads` make (spec §27): every change that inserted or
2010
    /// deleted one of their atoms, or an atom deleted from between them,
2011
    /// newest first. Exact, as atoms keep their identity across edits.
20126×
    pub fn line_history(
20136×
        &self,
20146×
        heads: &[ChangeHash],
20156×
        path: &str,
20166×
        first: usize,
20176×
        last: usize,
20186×
    ) -> Result<Vec<LogEntry>> {
20196×
        if first == 0 || last < first {
20201×
            return fail(format!(
2021
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2022
            ));
20235×
        }
20245×
        let mut state = self.load_state_history(heads)?;
20255×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
20261×
            return fail(format!("{path} is not in that state"));
2027
        };
20284×
        self.load_graphs_of(&mut state, &[node])?;
20294×
        let live = state.live_lines(&node);
20304×
        if last > live.len() {
20311×
            return fail(format!(
2032
                "{path} has {} lines; asked for {first},{last}",
20331×
                live.len()
2034
            ));
20353×
        }
20363×
        let Some(g) = state.file(&node) else {
20370×
            return fail(format!("{path} is not a text file"));
2038
        };
20393×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
20403×
        let touched = g.touching(&atoms);
20413×
        Ok(self
20423×
            .log_of(&state)
20433×
            .into_iter()
204413×
            .filter(|e| touched.contains(&e.hash))
20453×
            .collect())
20466×
    }
2047
20488×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
20498×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
20508×
        let mut entries: Vec<LogEntry> = state
20518×
            .changes()
20528×
            .map(|(h, meta)| LogEntry {
205331×
                hash: *h,
205431×
                change: meta.clone(),
2055
                is_working_copy: false,
205631×
                is_head: head_set.contains(h),
205731×
            })
20588×
            .collect();
205938×
        entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
20608×
        entries
20618×
    }
2062
2063
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2064
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2065
    /// (`resolve_change`).
206661×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
206761×
        let view = self.view()?;
206861×
        if let Some(st) = view.bookmarks.get(spec) {
206936×
            return Ok(self.store.get_state(st)?.heads);
207025×
        }
207125×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
20721×
            return Ok(self.store.get_state(&st)?.heads);
207324×
        }
207424×
        if let Some(heads) = self.tag_heads(spec)? {
20752×
            return Ok(heads);
207622×
        }
207722×
        Ok(vec![self.resolve_change(spec)?])
207861×
    }
2079
2080
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2081
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
208231×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
208331×
        if spec == "@" {
20840×
            return Ok(self.working_copy()?.0);
208531×
        }
208631×
        let view = self.view()?;
208731×
        let named = match view.bookmarks.get(spec) {
20881×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
208930×
            None => match remote_bookmark(&view, spec) {
20901×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
209129×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2092
            },
2093
        };
209431×
        if let Some((kind, heads)) = named {
20953×
            return match heads.len() {
20963×
                1 => Ok(heads[0]),
20970×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2098
            };
209928×
        }
210028×
        if spec.is_empty() || spec == "#" {
21010×
            return fail("empty change specifier");
210228×
        }
210328×
        let entries = self.log()?;
210428×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
210523×
            entries
210623×
                .iter()
210799×
                .filter(|e| e.hash.starts_with_hex(hp))
210823×
                .collect()
2109
        } else {
21105×
            entries
21115×
                .iter()
211218×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
21135×
                .collect()
2114
        };
211528×
        match matches.len() {
211624×
            1 => Ok(matches[0].hash),
21174×
            0 => match self.resolve_in_remotes(spec)? {
21181×
                Some(h) => Ok(h),
21193×
                None => fail(format!("no change matches {spec:?}")),
2120
            },
2121
            _ => {
21220×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
21230×
                if ids.len() == 1 {
21240×
                    fail(format!(
2125
                        "change {spec} is divergent: {} variants",
21260×
                        matches.len()
2127
                    ))
2128
                } else {
21290×
                    fail(format!("{spec:?} is ambiguous"))
2130
                }
2131
            }
2132
        }
213331×
    }
2134
2135
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2136
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2137
    /// `None` when none matches, or more than one.
21384×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
21394×
        let view = self.view()?;
21404×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
21414×
        for bookmarks in view.remotes.values() {
21423×
            for st in bookmarks.values() {
21433×
                let heads = self.store.get_state(st)?.heads;
21447×
                for e in self.log_state(&heads)? {
21457×
                    let hit = match spec.strip_prefix('#') {
21462×
                        Some(hp) => e.hash.starts_with_hex(hp),
21475×
                        None => e.change.change_id.starts_with_hex(spec),
2148
                    };
21497×
                    if hit {
21501×
                        found.insert(e.hash);
21516×
                    }
2152
                }
2153
            }
2154
        }
21554×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
21564×
    }
2157
2158
    /// Where a change is when no local bookmark or the working copy holds
2159
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2160
    /// it is held locally, or nowhere.
21613×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
21626×
        if self.log()?.iter().any(|e| e.hash == *hash) {
21632×
            return Ok(None);
21641×
        }
21651×
        let view = self.view()?;
21661×
        for (remote, bookmarks) in &view.remotes {
21671×
            for (name, st) in bookmarks {
21681×
                let heads = self.store.get_state(st)?.heads;
21691×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
21701×
                    return Ok(Some(format!("{remote}/{name}")));
21710×
                }
2172
            }
2173
        }
21740×
        Ok(None)
21753×
    }
2176
2177
    /// Human-readable description of what a change does, with line content.
21783×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
21793×
        let change = self.store.get_change(hash)?;
21803×
        let (base, base_snapshot) = self.change_base(&change)?;
21813×
        Ok(render_change(&change, &base, &base_snapshot))
21823×
    }
2183
2184
    /// The base state of `change` (its dependencies) and its rendering, as
2185
    /// much as showing the change needs: the whole tree, and the graphs and
2186
    /// contents of the files the change edits. Other text files are left
2187
    /// unrendered ([`Snapshot::unrendered`]).
21886×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
21896×
        let base = self.load_state_history(&change.deps)?;
21906×
        self.render_base_for(change, base)
21916×
    }
2192
2193
    /// The base for showing `change` alone: the graphs of the files it
2194
    /// edits built, and the base's tree with no file rendered, which is
2195
    /// all [`render_change`](snapshot::render_change) and
2196
    /// [`diff_files_of`](snapshot::diff_files_of) read.
21972×
    pub(crate) fn tree_base_for(
21982×
        &self,
21992×
        change: &Change,
22002×
        mut base: State,
22012×
    ) -> Result<(State, Snapshot)> {
22022×
        let _t = crate::timing::phase("diff: the base's tree");
22032×
        let edited: std::collections::HashSet<NodeId> =
22048×
            change.edits.iter().map(|e| e.node()).collect();
22052×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
22062×
        self.load_graphs_of(&mut base, &nodes)?;
22072×
        let snapshot = Snapshot {
22082×
            tree: base.tree().view(),
22092×
            files: BTreeMap::new(),
22102×
            unrendered: BTreeSet::new(),
22112×
        };
22122×
        Ok((base, snapshot))
22132×
    }
2214
2215
    /// [`Repo::change_base`] with the base already loaded (the working
2216
    /// copy's comes from the state index).
2217221×
    pub(crate) fn render_base_for(
2218221×
        &self,
2219221×
        change: &Change,
2220221×
        mut base: State,
2221221×
    ) -> Result<(State, Snapshot)> {
2222221×
        let _t = crate::timing::phase("diff: render the base");
2223221×
        let edited: std::collections::HashSet<NodeId> =
2224417×
            change.edits.iter().map(|e| e.node()).collect();
2225221×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2226221×
        self.load_graphs_of(&mut base, &nodes)?;
2227221×
        let snapshot = {
2228221×
            let _t = crate::timing::phase("diff:   of which materialize");
2229221×
            base.materialize_nodes(&edited)
2230
        };
2231221×
        Ok((base, snapshot))
2232221×
    }
2233
}
2234
22350×
fn remove_any(path: &Path) -> std::io::Result<()> {
22360×
    let m = fs::symlink_metadata(path)?;
22370×
    if m.is_dir() {
22380×
        fs::remove_dir_all(path)
2239
    } else {
22400×
        fs::remove_file(path)
2241
    }
22420×
}
2243
22445×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
22455×
    let mut perms = fs::metadata(path)?.permissions();
22465×
    perms.set_readonly(readonly);
22475×
    fs::set_permissions(path, perms)
22485×
}
2249
2250
#[cfg(unix)]
22515893×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2252
    use std::os::unix::fs::PermissionsExt;
22535893×
    let mut perms = fs::metadata(path)?.permissions();
22545893×
    let mode = perms.mode();
22555893×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
22565893×
    if want != mode {
22574×
        perms.set_mode(want);
22584×
        fs::set_permissions(path, perms)?;
22595889×
    }
22605893×
    Ok(())
22615893×
}
2262
#[cfg(not(unix))]
2263
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2264
    Ok(())
2265
}
2266
2267
#[cfg(unix)]
226816246×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2269
    use std::os::unix::fs::PermissionsExt;
227016246×
    m.permissions().mode() & 0o111 != 0
227116246×
}
2272
#[cfg(not(unix))]
2273
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2274
    false
2275
}
2276
227712741×
fn op_ref(k: OpKey) -> OpRef {
227812741×
    OpRef {
227912741×
        change: k.0,
228012741×
        index: k.1,
228112741×
    }
228212741×
}
2283
22845885×
fn split_path(path: &str) -> (&str, &str) {
22855885×
    match path.rfind('/') {
22865046×
        Some(i) => (&path[..i], &path[i + 1..]),
2287839×
        None => ("", path),
2288
    }
22895885×
}
2290
2291
/// Whether `rel` is an attributes file (spec §7.6).
229267121×
fn is_attributes(rel: &str) -> bool {
229367121×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
229467121×
}
2295
2296
/// The manifest entry for `rel` when its size and mtime match it outside
2297
/// the racy window.
229823913×
fn stat_cached<'m>(
229923913×
    rel: &str,
230023913×
    meta: &walk::Stat,
230123913×
    cache: Option<&'m prompt::Manifest>,
230223913×
) -> Option<&'m prompt::ManifestEntry> {
230323913×
    let m = cache?;
230419053×
    let e = m.entries.get(rel)?;
230517756×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
230617756×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
230723913×
}
2308
2309
/// Read one working-copy file, or serve it from the stat cache (spec
2310
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2311
/// an opaque file is not read at all (its stored blob stands in), and a
2312
/// text file the manifest recorded equal to a base graph whose key is
2313
/// `key`, the key the base has now, is not read either: equal keys mean
2314
/// equal renderings, so it still equals the base. Touches no repository
2315
/// state, so the walk runs it in parallel; the caller checks that a cached
2316
/// blob is still in the store.
231711972×
fn read_file_entry(
231811972×
    rel: &str,
231911972×
    path: &Path,
232011972×
    meta: &walk::Stat,
232111972×
    cache: Option<&prompt::Manifest>,
232211972×
    key: Option<[u8; 32]>,
232311972×
) -> Result<FsEntry> {
232411972×
    let exec = meta.exec;
232511972×
    let stat = Some((meta.size, meta.mtime_ns));
232611972×
    let mut e = match stat_cached(rel, meta, cache) {
23274247×
        Some(e) if e.blob.is_some() => FsEntry {
23281×
            blob: e.blob,
23291×
            content_hash: Some(e.hash),
23301×
            ..FsEntry::new(NodeKind::File, exec, vec![])
23311×
        },
23324246×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
23334241×
            content_hash: Some(e.hash),
23344241×
            unchanged: true,
23354241×
            graph_key: e.graph,
23364241×
            ..FsEntry::new(NodeKind::File, exec, vec![])
23374241×
        },
23385×
        Some(e) => FsEntry {
23395×
            content_hash: Some(e.hash),
23405×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2341
        },
23427725×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2343
    };
2344
    // The stat the manifest records: taken before the read, so a file that
2345
    // changes meanwhile is read again next time.
234611971×
    e.stat = stat;
234711971×
    Ok(e)
234811972×
}
2349
2350
/// Two maps side by side in key order: each key of either, with its value
2351
/// in each. Linear, with no lookups, for maps of a whole tree.
23522266×
pub(crate) fn join<'a, A, B>(
23532266×
    a: &'a BTreeMap<String, A>,
23542266×
    b: &'a BTreeMap<String, B>,
23552266×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
23562266×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
235734848×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
23582266×
        (None, None) => None,
23592867×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
23605690×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
236124025×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2362310×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2363277×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2364
            std::cmp::Ordering::Equal => {
236523438×
                let (k, va) = a.next()?;
236623438×
                let (_, vb) = b.next()?;
236723438×
                Some((k, Some(va), Some(vb)))
2368
            }
2369
        },
237034848×
    })
23712266×
}
2372
2373
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2374
/// lookups.
23751170×
pub(crate) fn missing_from<'a, A, B>(
23761170×
    a: &'a BTreeMap<String, A>,
23771170×
    b: &BTreeMap<String, B>,
23781170×
) -> Vec<(&'a String, &'a A)> {
23791170×
    let mut keys = b.keys().peekable();
23801170×
    a.iter()
23819022×
        .filter(|(k, _)| {
238217427×
            while keys.next_if(|kb| *kb < *k).is_some() {}
23839022×
            keys.peek() != Some(k)
23849022×
        })
23851170×
        .collect()
23861170×
}