OXYGENHUB

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

1803 of 2042 lines run, 414 of 676 functions · run #282 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.
752386×
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
762386×
    let Some(url) = &config.storage_url else {
772381×
        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×
    )?)
1002386×
}
101
102162×
fn fail<T>(s: impl Into<String>) -> Result<T> {
103162×
    Err(RepoError::Msg(s.into()))
104162×
}
105
106
mod bookmarks;
107
mod checkout;
108
mod checkpoint;
109
mod config;
110
mod doctor;
111
mod fsck;
112
mod gc;
113
mod git;
114
mod history;
115
mod hooks;
116
mod hosted;
117
mod identity;
118
mod inspect;
119
mod ops;
120
mod policy;
121
mod prompt;
122
mod receipts;
123
mod revset;
124
mod snapshot;
125
pub mod strata;
126
mod subrepos;
127
mod sync;
128
mod tags;
129
#[cfg(test)]
130
mod tests;
131
mod touched;
132
mod walk;
133
mod workspace;
134
135
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
136
pub use checkout::CheckoutReport;
137
pub use config::{parse_size, read_config_file, Config};
138
pub use doctor::{Check, DoctorReport, Health};
139
pub use fsck::{FsckReport, Problem, Severity};
140
pub use gc::GcReport;
141
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
142
pub use hooks::{json_array, json_str, HookOutcome};
143
pub use hosted::FileEdit;
144
pub use identity::{Rotation, SignatureStatus};
145
pub use inspect::{BisectStep, BlameLine, Description};
146
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
147
pub use policy::PolicyUpdate;
148
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
149
pub use receipts::ReceiptInfo;
150
pub use revset::{Revset, REVSET_BUDGET};
151
pub use snapshot::{
152
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
153
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
154
    Selection, SnapshotResult,
155
};
156
pub use subrepos::{SubrepoInfo, SubrepoSync};
157
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT};
158
pub use tags::TagInfo;
159
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
160
161
/// The file name under which per-bookmark or per-tag data is kept: `/`
162
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
163
/// than a directory that would clash with it.
1643946×
pub(crate) fn name_file(name: &str) -> String {
1653946×
    name.replace('%', "%25").replace('/', "%2F")
1663946×
}
167
168
/// The name a [`name_file`] file name stands for.
16943×
pub(crate) fn file_name_to_name(file: &str) -> String {
17043×
    file.replace("%2F", "/").replace("%25", "%")
17143×
}
172
1736821×
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
1746821×
    Ok(crate::durable::write_atomic(path, data)?)
1756821×
}
176
177
/// Replace a cache file: whole or not at all, but without waiting for the
178
/// disk. A cache checks its own bytes when read, so one a crash leaves
179
/// short or stale is rebuilt rather than trusted.
180
/// How many changes a state index may fall behind its working copy before
181
/// it is written again; until then each load replays them.
182
const INDEX_REPLAY_LIMIT: usize = 16;
183
/// The changes whose encodings are kept for building graphs: a batch of
184
/// files often takes inline text from a few changes in turn.
185
const CHANGE_CACHE_COUNT: usize = 4;
186
const CHANGE_CACHE_BYTES: usize = 512 << 20;
187
/// How many state indexes a workspace keeps.
188
const STATE_INDEXES_KEPT: usize = 2;
189
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
190
1912787×
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
1922787×
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
1932787×
    fs::write(&tmp, data)?;
1942787×
    fs::rename(&tmp, path)?;
1952787×
    Ok(())
1962787×
}
197
198
pub struct LogEntry {
199
    pub hash: ChangeHash,
200
    /// Metadata from the state; the full change may be absent in a shallow repository.
201
    pub change: crate::state::ChangeMeta,
202
    pub is_working_copy: bool,
203
    pub is_head: bool,
204
}
205
206
/// A text file's base graph key, by path, as a walk asks for it.
207
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
208
209
/// A file as found on disk or in an imported tree.
210
#[derive(Clone)]
211
pub(crate) struct FsEntry {
212
    pub kind: NodeKind,
213
    pub exec: bool,
214
    /// File content, or a symlink's target. Empty when `blob` is set.
215
    /// Shared, so a new file's insert holds it without a copy.
216
    pub content: std::sync::Arc<Vec<u8>>,
217
    /// The stored blob of an opaque file whose size and mtime are unchanged
218
    /// since the last manifest (spec §12.3 stat cache); the content was not
219
    /// read.
220
    pub blob: Option<ObjectRef>,
221
    /// BLAKE3 of the content, carried over from the manifest when the stat
222
    /// is unchanged, so the manifest can be rewritten without rehashing.
223
    pub content_hash: Option<[u8; 32]>,
224
    /// A text file known equal to the base's rendering without reading it:
225
    /// its stat matches the manifest and the manifest recorded it equal to
226
    /// a base file graph with the same key (spec §12.3). `content` is empty.
227
    pub unchanged: bool,
228
    /// The base graph key this file equals, for the next manifest.
229
    pub graph_key: Option<[u8; 32]>,
230
    /// Size and mtime already known to be current (a checkout leaving the
231
    /// file as it was), so the manifest need not stat it again.
232
    pub stat: Option<(u64, u128)>,
233
}
234
235
impl FsEntry {
23622587×
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
23722587×
        FsEntry {
23822587×
            kind,
23922587×
            exec,
24022587×
            content: std::sync::Arc::new(content),
24122587×
            blob: None,
24222587×
            content_hash: None,
24322587×
            unchanged: false,
24422587×
            graph_key: None,
24522587×
            stat: None,
24622587×
        }
24722587×
    }
248
}
249
250
pub struct Repo {
251
    /// Oxygen-pinned subrepos skipped by the running Git export.
252
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
253
    /// The manifest as last read, with the file identity it was read from,
254
    /// so one command parses it once (see `read_manifest`).
255
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
256
    /// A listing of the working copy left by a failed clean check, for the
257
    /// snapshot that follows it to reuse; taken by the next walk and
258
    /// dropped whenever the manifest is written.
259
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
260
    /// The nested repositories the last walk left out, being neither
261
    /// registered nor tracked subrepos (oxygen#43).
262
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
263
    /// New untracked files the last walk left out for their size, with
264
    /// their sizes (oxygen#98).
265
    pub(crate) skipped_large: std::cell::RefCell<Vec<(String, u64)>>,
266
    root: PathBuf,
267
    oxy: PathBuf,
268
    store: Store,
269
    workspace: WorkspaceId,
270
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
271
    bare: bool,
272
    keys_dir: PathBuf,
273
    user_config: PathBuf,
274
    pub config: Config,
275
    /// What the working copy's file system can represent (spec §7.7).
276
    platform: crate::portable::Platform,
277
    /// The encodings of the changes last read for their inline inserts,
278
    /// oldest first.
279
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
280
    /// `--at-op`: read the repository as it was after this operation;
281
    /// recording an operation is refused.
282
    at_op: Option<ObjectRef>,
283
    /// The directories (with their times) and nested repositories of the
284
    /// last walk, for the manifest written from it.
285
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
286
    /// The directories a manifest check listed, for its restamp only.
287
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
288
}
289
290
/// A walk's directories with their times, and its nested repositories.
291
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
292
293
/// Marker file of a bare repository, inside `.oxy/`.
294
const BARE_MARKER: &str = "bare";
295
/// Marker of a hosted repository that has no id yet: the first push binds
296
/// it to the pusher's id (spec §16.1).
297
const UNBOUND_MARKER: &str = "unbound";
298
299
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
300
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
3017392×
pub fn default_home() -> PathBuf {
3027392×
    if let Ok(h) = std::env::var("OXY_HOME") {
3037389×
        return PathBuf::from(h);
3043×
    }
3053×
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
3060×
        return PathBuf::from(x).join("oxy");
3073×
    }
308
    // Windows has no HOME as a rule: the roaming profile's application
309
    // data, as Windows programs keep theirs.
310
    #[cfg(windows)]
311
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
312
        return PathBuf::from(d).join("oxy");
313
    }
3143×
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
3153×
    PathBuf::from(home).join(".config").join("oxy")
3167392×
}
317
3182386×
pub fn default_keys_dir() -> PathBuf {
3192386×
    default_home().join("keys")
3202386×
}
321
3224772×
pub fn default_user_config() -> PathBuf {
3234772×
    default_home().join("config.toml")
3244772×
}
325
326
/// Where `create_identity` records the author.
327
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
328
pub enum IdentityScope {
329
    /// The user file: every repository of this user signs with it.
330
    User,
331
    /// This repository only.
332
    Repo,
333
}
334
335
impl Repo {
336
    // ------------------------------------------------------------ lifecycle
337
338217×
    pub fn init(root: &Path) -> Result<Repo> {
339217×
        let mut id = [0u8; 16];
340217×
        rand::rngs::OsRng.fill_bytes(&mut id);
341217×
        Self::init_with_id(root, id)
342217×
    }
343
344
    /// Initialize a repository with a given repository ID (clones share the
345
    /// ID of their origin, spec §14.4).
346457×
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
347457×
        Self::init_on(root, id, None)
348457×
    }
349
350
    /// A new repository with a fresh id, bare or not, on `storage` or in
351
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
35212×
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
35312×
        let mut id = [0u8; 16];
35412×
        rand::rngs::OsRng.fill_bytes(&mut id);
35512×
        if bare {
3560×
            Self::init_bare_on(root, id, storage)
357
        } else {
35812×
            Self::init_on(root, id, storage)
359
        }
36012×
    }
361
362
    /// Initialize a repository whose objects and operation head are kept
363
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
364472×
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
365472×
        fs::create_dir_all(root)?;
366472×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
367472×
        let oxy = root.join(OXY_DIR);
368472×
        if oxy.exists() {
3691×
            return fail(format!("{} is already an oxy repository", root.display()));
370471×
        }
371471×
        fs::create_dir_all(oxy.join("ops"))?;
372471×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
373471×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
374471×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
375471×
        if let Some(url) = storage {
3763×
            config.set("storage.url", url)?;
377468×
        }
378471×
        config.save(&oxy.join("config"))?;
379471×
        let workspace = WorkspaceId::random();
380471×
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
381471×
        let store = open_objects(&oxy, &config)?;
382470×
        let repo = Repo {
383470×
            last_change: Default::default(),
384470×
            at_op: None,
385470×
            walked_dirs: Default::default(),
386470×
            listed_dirs: Default::default(),
387470×
            git_export_skipped: Default::default(),
388470×
            manifest_cache: Default::default(),
389470×
            listing_cache: Default::default(),
390470×
            untracked_nested: Default::default(),
391470×
            skipped_large: Default::default(),
392470×
            root,
393470×
            oxy,
394470×
            store,
395470×
            workspace,
396470×
            bare: false,
397470×
            keys_dir: default_keys_dir(),
398470×
            platform: crate::portable::Platform::current(),
399470×
            user_config: default_user_config(),
400470×
            config,
401470×
        };
402470×
        repo.register_workspace(&workspace, &repo.root)?;
403
404470×
        let wc = repo.new_working_copy(vec![], "");
405470×
        let wc_hash = repo.store.put_change(&wc)?;
406470×
        let mut view = View::default();
407470×
        view.bookmarks.insert(
408470×
            repo.config.bookmark.clone(),
409470×
            repo.store.put_state(&StateObject::new(vec![]))?,
410
        );
411470×
        view.workspaces.insert(workspace, wc_hash);
412470×
        repo.record_op(&[], "oxy init", view)?;
413468×
        Ok(repo)
414472×
    }
415
416
    /// Create a bare repository: an object store, operation log and
417
    /// references with no workspace and no working copy, for hosting
418
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
4195×
    pub fn init_bare(root: &Path) -> Result<Repo> {
4205×
        let mut id = [0u8; 16];
4215×
        rand::rngs::OsRng.fill_bytes(&mut id);
4225×
        Self::init_bare_with_id(root, id)
4235×
    }
424
42539×
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
42639×
        Self::init_bare_on(root, id, None)
42739×
    }
428
429
    /// [`Repo::init_on`] for a bare repository.
43039×
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
43139×
        fs::create_dir_all(root)?;
43239×
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
43339×
        let oxy = root.join(OXY_DIR);
43439×
        if oxy.exists() {
4350×
            return fail(format!("{} is already an oxy repository", root.display()));
43639×
        }
43739×
        fs::create_dir_all(oxy.join("ops"))?;
43839×
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
43939×
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
44039×
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
44139×
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
44239×
        if let Some(url) = storage {
4430×
            config.set("storage.url", url)?;
44439×
        }
44539×
        config.save(&oxy.join("config"))?;
44639×
        let store = open_objects(&oxy, &config)?;
44739×
        let repo = Repo {
44839×
            last_change: Default::default(),
44939×
            at_op: None,
45039×
            walked_dirs: Default::default(),
45139×
            listed_dirs: Default::default(),
45239×
            git_export_skipped: Default::default(),
45339×
            manifest_cache: Default::default(),
45439×
            listing_cache: Default::default(),
45539×
            untracked_nested: Default::default(),
45639×
            skipped_large: Default::default(),
45739×
            root,
45839×
            oxy,
45939×
            store,
46039×
            workspace: WorkspaceId::ZERO,
46139×
            bare: true,
46239×
            keys_dir: default_keys_dir(),
46339×
            platform: crate::portable::Platform::current(),
46439×
            user_config: default_user_config(),
46539×
            config,
46639×
        };
46739×
        let mut view = View::default();
46839×
        view.bookmarks.insert(
46939×
            repo.config.bookmark.clone(),
47039×
            repo.store.put_state(&StateObject::new(vec![]))?,
471
        );
47239×
        repo.record_op(&[], "oxy init --bare", view)?;
47339×
        Ok(repo)
47439×
    }
475
476
    /// A bare repository with no id yet. Its `id()` is all zero until the
477
    /// first push binds it (`bind_id`), so an existing repository can be
478
    /// pushed to a freshly created hosted one and keep its identity.
47913×
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
48013×
        let repo = Self::init_bare_with_id(root, [0; 16])?;
48113×
        fs::remove_file(repo.oxy.join("id"))?;
48213×
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
48313×
        Ok(repo)
48413×
    }
485
4863405×
    pub fn is_unbound(&self) -> bool {
4873405×
        self.oxy.join(UNBOUND_MARKER).is_file()
4883405×
    }
489
490
    /// Give an unbound repository its id.
49112×
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
49212×
        if !self.is_unbound() {
4930×
            return fail("this repository already has an id");
49412×
        }
49512×
        if id == [0; 16] {
4960×
            return fail("a repository id cannot be all zero");
49712×
        }
49812×
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
49912×
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
50012×
        Ok(())
50112×
    }
502
503
    /// Whether this repository has no working copy (`init_bare`).
50476×
    pub fn is_bare(&self) -> bool {
50576×
        self.bare
50676×
    }
507
508
    /// Open the repository containing `start` (searching upwards).
5091876×
    pub fn open(start: &Path) -> Result<Repo> {
5101876×
        let start = start.canonicalize()?;
5111876×
        let mut dir: Option<&Path> = Some(&start);
5121876×
        while let Some(d) = dir {
5131876×
            let oxy = d.join(OXY_DIR);
5141876×
            if oxy.is_file() {
515
                // A secondary workspace (spec §12.2): the file points at the repository.
5169×
                let text = fs::read_to_string(&oxy)?;
5179×
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
5180×
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
519
                };
5209×
                let format = fs::read_to_string(shared.join("format"))?;
5219×
                if format != FORMAT_LINE {
5220×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5239×
                }
5249×
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
5259×
                let store = open_objects(&shared, &config)?;
5269×
                let mut repo = Repo {
5279×
                    last_change: Default::default(),
5289×
                    at_op: None,
5299×
                    walked_dirs: Default::default(),
5309×
                    listed_dirs: Default::default(),
5319×
                    git_export_skipped: Default::default(),
5329×
                    manifest_cache: Default::default(),
5339×
                    listing_cache: Default::default(),
5349×
                    untracked_nested: Default::default(),
5359×
                    skipped_large: Default::default(),
5369×
                    root: d.to_path_buf(),
5379×
                    oxy: shared,
5389×
                    store,
5399×
                    workspace,
5409×
                    bare: false,
5419×
                    keys_dir: default_keys_dir(),
5429×
                    platform: crate::portable::Platform::current(),
5439×
                    user_config: default_user_config(),
5449×
                    config,
5459×
                };
5469×
                repo.apply_workspace_bookmark();
5479×
                return Ok(repo);
5481867×
            }
5491867×
            if oxy.is_dir() {
5501867×
                let format = fs::read_to_string(oxy.join("format"))?;
5511867×
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
5521867×
                let bare = oxy.join(BARE_MARKER).is_file();
5531867×
                let workspace = if bare {
554144×
                    WorkspaceId::ZERO
555
                } else {
5561723×
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
5571723×
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
558
                };
5591867×
                let store = open_objects(&oxy, &config)?;
5601867×
                let mut repo = Repo {
5611867×
                    last_change: Default::default(),
5621867×
                    at_op: None,
5631867×
                    walked_dirs: Default::default(),
5641867×
                    listed_dirs: Default::default(),
5651867×
                    git_export_skipped: Default::default(),
5661867×
                    manifest_cache: Default::default(),
5671867×
                    listing_cache: Default::default(),
5681867×
                    untracked_nested: Default::default(),
5691867×
                    skipped_large: Default::default(),
5701867×
                    root: d.to_path_buf(),
5711867×
                    oxy,
5721867×
                    store,
5731867×
                    workspace,
5741867×
                    bare,
5751867×
                    keys_dir: default_keys_dir(),
5761867×
                    platform: crate::portable::Platform::current(),
5771867×
                    user_config: default_user_config(),
5781867×
                    config,
5791867×
                };
5801867×
                if !bare {
5811723×
                    repo.apply_workspace_bookmark();
5821723×
                }
5831867×
                if format == FORMAT1_LINE {
5841×
                    repo.migrate_format1()?;
5851866×
                } else if format != FORMAT_LINE {
5860×
                    return fail(format!("unsupported repository format: {}", format.trim()));
5871866×
                }
5881867×
                return Ok(repo);
5890×
            }
5900×
            dir = d.parent();
591
        }
5920×
        fail(format!(
593
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
5940×
            start.display()
595
        ))
5961876×
    }
597
598
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
599
    /// into format 2, where each bookmark names a `state` object.
6001×
    fn migrate_format1(&self) -> Result<()> {
6011×
        let (head, version) = self.read_head()?;
602
        // Collect the chain root-first.
6031×
        let mut chain: Vec<Format1Op> = Vec::new();
6041×
        let mut cur = Some(head);
6053×
        while let Some(r) = cur {
6062×
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
6072×
            cur = op.parents.first().copied();
6082×
            chain.push(op);
609
        }
6101×
        chain.reverse();
6111×
        let mut new_parent: Option<ObjectRef> = None;
6122×
        for old in chain {
6132×
            let mut view = View::default();
6142×
            for (name, heads) in &old.view.bookmarks {
6152×
                view.bookmarks.insert(
6162×
                    name.clone(),
6172×
                    self.store.put_state(&StateObject::new(heads.clone()))?,
618
                );
619
            }
6202×
            view.workspaces = old.view.workspaces.clone();
6212×
            let op = Op {
6222×
                parents: new_parent.into_iter().collect(),
6232×
                hlc: old.hlc,
6242×
                command: old.command,
6252×
                view,
6262×
                workspace: None,
6272×
                undoes: None,
6282×
            };
6292×
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
630
        }
6311×
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
6320×
            return fail("the operation log changed while it was rewritten; run the command again");
6331×
        }
6341×
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
6351×
        Ok(())
6361×
    }
637
638
    /// Pack automatically once many loose objects have accumulated.
639635×
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
640635×
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
6410×
            self.store.pack_loose()?;
6420×
            self.store.merge_packs()?;
643635×
        }
644635×
        Ok(())
645635×
    }
646
647
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
6483126×
    pub fn id(&self) -> Result<[u8; 16]> {
6493126×
        if self.is_unbound() {
65018×
            return Ok([0; 16]);
6513108×
        }
6523108×
        let path = self.oxy.join("id");
6533108×
        match fs::read_to_string(&path) {
6543108×
            Ok(h) => hex::decode(h.trim())
6553108×
                .ok()
6563108×
                .and_then(|v| v.try_into().ok())
6573108×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
6580×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6590×
                let mut id = [0u8; 16];
6600×
                rand::rngs::OsRng.fill_bytes(&mut id);
6610×
                write_atomic(&path, hex::encode(id).as_bytes())?;
6620×
                Ok(id)
663
            }
6640×
            Err(e) => Err(e.into()),
665
        }
6663126×
    }
667
66862×
    pub fn root(&self) -> &Path {
66962×
        &self.root
67062×
    }
671488×
    pub fn store(&self) -> &Store {
672488×
        &self.store
673488×
    }
67411×
    pub fn workspace(&self) -> WorkspaceId {
67511×
        self.workspace
67611×
    }
677
678
    /// Use a different user directory for keys and the user config file
679
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
680
    /// Act as if the working copy were on another platform's file system
681
    /// (tests of Windows and macOS behaviour on any host).
6822×
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
6832×
        self.platform = platform;
6842×
        self
6852×
    }
686
6870×
    pub fn platform(&self) -> crate::portable::Platform {
6880×
        self.platform
6890×
    }
690
691159×
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
692159×
        let dir = dir.into();
693159×
        self.keys_dir = dir.join("keys");
694159×
        self.user_config = dir.join("config.toml");
695159×
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
696159×
            self.config = c;
697159×
        }
698159×
        self.apply_workspace_bookmark();
699159×
        self
700159×
    }
701
702
    /// The workspace's current bookmark (spec §10.1) overrides the
703
    /// configured default when `oxy bookmark switch` has recorded one.
7041891×
    fn apply_workspace_bookmark(&mut self) {
7051891×
        if let Ok(b) = fs::read_to_string(
7061891×
            self.oxy
7071891×
                .join("workspaces")
7081891×
                .join(self.workspace.to_hex())
7091891×
                .join("bookmark"),
7101891×
        ) {
71135×
            let b = b.trim();
71235×
            if !b.is_empty() {
71335×
                self.config.bookmark = b.to_string();
71435×
            }
7151856×
        }
7161891×
    }
717
7181×
    pub fn user_config_path(&self) -> &Path {
7191×
        &self.user_config
7201×
    }
721
722
    /// Set a key in the user file and refresh the effective configuration.
72312×
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
72412×
        Config::set_user(&self.user_config, key, value)?;
72511×
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
72611×
        Ok(())
72712×
    }
728
729356×
    pub fn save_config(&self) -> Result<()> {
730356×
        self.config.save(&self.oxy.join("config"))
731356×
    }
732
7334184×
    fn author(&self) -> KeyId {
7344184×
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
7354184×
    }
736
}
737
738
impl Repo {
7391600×
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
7401600×
        let mut c = Change {
7411600×
            version: crate::objects::CHANGE_VERSION,
7421600×
            change_id: ChangeId::random(),
7431600×
            deps,
7441600×
            author: self.author(),
7451600×
            hlc: Hlc::now(),
7461600×
            message: message.into(),
7471600×
            tree_ops: vec![],
7481600×
            edits: vec![],
7491600×
            kind: ChangeKind::WorkingCopy,
7501600×
        };
7511600×
        c.normalize();
7521600×
        c
7531600×
    }
754
755
    // ------------------------------------------------------------ operation log
756
75713547×
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
75813547×
        if let Some(r) = self.at_op {
7595×
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
76013542×
        }
76113542×
        let r = self.head_ref()?;
76213540×
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
76313540×
        Ok((r, op))
76413547×
    }
765
7669394×
    pub fn view(&self) -> Result<View> {
7679394×
        Ok(self.head_op()?.1.view)
7689394×
    }
769
7703293×
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
7713293×
        self.record_op_undoing(parents, command, view, None)
7723293×
    }
773
774
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
7753296×
    fn record_op_undoing(
7763296×
        &self,
7773296×
        parents: &[ObjectRef],
7783296×
        command: &str,
7793296×
        view: View,
7803296×
        undoes: Option<ObjectRef>,
7813296×
    ) -> Result<ObjectRef> {
7823296×
        if self.at_op.is_some() {
7831×
            return fail(
784
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
785
            );
7863295×
        }
7873295×
        let op = Op {
7883295×
            parents: parents.to_vec(),
7893295×
            hlc: Hlc::now(),
7903295×
            command: command.into(),
7913295×
            view,
7923295×
            workspace: Some(self.workspace),
7933295×
            undoes,
7943295×
        };
7953295×
        let r = self.store.put(ObjectType::Op, &op.encode())?;
796
        // The head is the commit point: everything it names must be on disk first.
7973293×
        let flushing = crate::timing::phase("op: flush the store");
7983293×
        self.store.flush()?;
7993291×
        drop(flushing);
800
        // Compare and swap (spec §12.1): when another process recorded an
801
        // operation since this one read the head, the two are merged
802
        // instead of one overwriting the other. On this disk the head moves
803
        // under a short lock; on any other store by its record's version,
804
        // and a record that moved meanwhile is read again and merged again.
8053291×
        let _lock = if self.store.is_local() {
8063283×
            Some(self.lock_ops()?)
807
        } else {
8088×
            None
809
        };
8103291×
        let Some(parent) = parents.first() else {
811
            // The first operation (init): there is no head yet.
812509×
            if !self.swap_head(&r, None)? {
8132×
                return fail(format!(
814
                    "{} already holds a repository's operation log",
8152×
                    self.store.backend().describe()
816
                ));
817507×
            }
818507×
            return Ok(r);
819
        };
8202782×
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
8212782×
        for _ in 0..HEAD_TRIES {
8222782×
            let (current, version) = self.read_head()?;
8232782×
            let to = if current == *parent {
8242768×
                r
825
            } else {
82614×
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
82713×
                let merged = Op {
82814×
                    parents: vec![current, r],
82914×
                    hlc: Hlc::now(),
83014×
                    command: format!("{command} (merged with a concurrent operation)"),
83114×
                    view: self.merge_views(&base, &op.view, &theirs)?,
83213×
                    workspace: Some(self.workspace),
83313×
                    undoes: None,
834
                };
83513×
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
83613×
                self.store.flush()?;
83713×
                m
838
            };
8392781×
            if self.swap_head(&to, version.as_ref())? {
8402775×
                return Ok(to);
8410×
            }
842
        }
8430×
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
8443296×
    }
845
846
    /// The operation head's lock, held only while the head pointer moves.
8473293×
    fn lock_ops(&self) -> Result<FileLock> {
8483293×
        fs::create_dir_all(self.oxy.join("ops"))?;
8493293×
        FileLock::acquire(
8503293×
            self.oxy.join("ops").join("lock"),
8513293×
            "another oxy process holds the operation log",
852
        )
8533293×
    }
854
85513544×
    fn head_ref(&self) -> Result<ObjectRef> {
85613544×
        Ok(self.read_head()?.0)
85713544×
    }
858
859
    /// The operation head, and on a store its record's version for
860
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
861
    /// any other store (a bucket, or memory in tests) it is the store's
862
    /// [`HEAD_RECORD`] reference record (oxygen#68).
86316414×
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
86416414×
        if self.store.is_local() {
86516395×
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
86616395×
            let r = ObjectRef::from_hex(hex.trim())
86716395×
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
86816392×
            return Ok((r, None));
86919×
        }
87019×
        let backend = self.store.backend();
87119×
        match backend.read_ref(HEAD_RECORD) {
87219×
            Ok(Some((bytes, version))) => {
87319×
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
8740×
                    || {
8750×
                        RepoError::Msg(format!(
8760×
                            "the operation head in {} is corrupt",
8770×
                            backend.describe()
8780×
                        ))
8790×
                    },
8800×
                )?;
88119×
                Ok((r, Some(version)))
882
            }
8830×
            Ok(None) => fail(format!(
884
                "{} holds no operation log (no {HEAD_RECORD} record)",
8850×
                backend.describe()
886
            )),
8870×
            Err(e) => fail(format!("read the operation head: {e}")),
888
        }
88916414×
    }
890
891
    /// Move the operation head to `to` from the `expected` version
892
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
893
    /// disk the caller holds the operations lock and the head always
894
    /// moves; on a store it moves only if the record is unchanged, and
895
    /// `false` says another process moved it first.
8963303×
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
8973303×
        if self.store.is_local() {
8983293×
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
8993287×
            return Ok(true);
90010×
        }
90110×
        match self
90210×
            .store
90310×
            .backend()
90410×
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
905
        {
9067×
            Ok(_) => Ok(true),
9073×
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
9080×
            Err(e) => fail(format!("move the operation head: {e}")),
909
        }
9103303×
    }
911
912
    /// Three-way merge of two views that both started from `base` (spec
913
    /// §12.1). A reference only one side changed takes that side's value.
914
    /// When both changed it differently: a bookmark keeps both sides'
915
    /// heads (it may then have several), a change beats a deletion, a
916
    /// workspace changed by both is an error (only one of them matches the
917
    /// files on disk), and otherwise this process's value wins for remote
918
    /// references and the policy, the first value for a tag (tags never
919
    /// move).
92014×
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
92150×
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
92250×
            b: &BTreeMap<K, V>,
92350×
            o: &BTreeMap<K, V>,
92450×
            t: &BTreeMap<K, V>,
92550×
            mut both: impl FnMut(&V, &V) -> Result<V>,
92650×
        ) -> Result<BTreeMap<K, V>> {
92750×
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
92850×
            let mut out = BTreeMap::new();
92951×
            for k in keys {
93051×
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
93151×
                let v = if ov == tv || tv == bv {
93225×
                    ov.cloned()
93326×
                } else if ov == bv {
93415×
                    tv.cloned()
935
                } else {
93611×
                    match (ov, tv) {
93711×
                        (Some(x), Some(y)) => Some(both(x, y)?),
9380×
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
9390×
                        (None, None) => None,
940
                    }
941
                };
94250×
                if let Some(v) = v {
94350×
                    out.insert(k.clone(), v);
94450×
                }
945
            }
94649×
            Ok(out)
94750×
        }
94814×
        let bookmarks = pick(
94914×
            &base.bookmarks,
95014×
            &ours.bookmarks,
95114×
            &theirs.bookmarks,
95210×
            |x, y| {
95310×
                let mut heads = self.store.get_state(x)?.heads;
95410×
                heads.extend(self.store.get_state(y)?.heads);
95510×
                let heads = self.load_state(&heads)?.maximal(&heads);
95610×
                Ok(self.store.put_state(&StateObject::new(heads))?)
95710×
            },
9580×
        )?;
959
        // Two operations that both replaced one workspace's working copy
960
        // cannot both be right: the files on disk match only one of them.
961
        // The working-copy lock keeps this from happening; should it happen
962
        // anyway, this operation is not recorded.
96314×
        let workspaces = pick(
96414×
            &base.workspaces,
96514×
            &ours.workspaces,
96614×
            &theirs.workspaces,
9671×
            |_, _| {
9681×
                fail(
969
                    "another oxy process changed this working copy at the same time; \
970
                     this command was not recorded: check `oxy status` and run it again",
971
                )
9721×
            },
9731×
        )?;
97413×
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
97513×
        let empty = BTreeMap::new();
97613×
        let names: BTreeSet<&String> = base
97713×
            .remotes
97813×
            .keys()
97913×
            .chain(ours.remotes.keys())
98013×
            .chain(theirs.remotes.keys())
98113×
            .collect();
98213×
        let mut remotes = BTreeMap::new();
98313×
        for n in names {
9849×
            let m = pick(
9859×
                base.remotes.get(n).unwrap_or(&empty),
9869×
                ours.remotes.get(n).unwrap_or(&empty),
9879×
                theirs.remotes.get(n).unwrap_or(&empty),
9880×
                |x, _| Ok(*x),
9890×
            )?;
9909×
            if !m.is_empty() {
9919×
                remotes.insert(n.clone(), m);
9929×
            }
993
        }
99413×
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
99513×
            ours.policy
9960×
        } else if ours.policy == base.policy {
9970×
            theirs.policy
998
        } else {
9990×
            ours.policy.or(theirs.policy)
1000
        };
100113×
        self.store.flush()?;
100213×
        Ok(View {
100313×
            bookmarks,
100413×
            workspaces,
100513×
            remotes,
100613×
            policy,
100713×
            tags,
100813×
        })
100914×
    }
1010
101146×
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
101246×
        let mut out = Vec::new();
101346×
        let (mut r, mut op) = self.head_op()?;
1014
        loop {
1015253×
            let next = op.parents.first().copied();
1016253×
            out.push((r, op));
1017253×
            match next {
1018207×
                Some(p) => {
1019207×
                    r = p;
1020207×
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1021
                }
102246×
                None => break,
1023
            }
1024
        }
102546×
        Ok(out)
102646×
    }
1027
1028
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1029
    ///
1030
    /// The command undone is the newest one this workspace ran: operations
1031
    /// that only recorded a working-copy snapshot are skipped (the files are
1032
    /// still on disk and the next snapshot recreates them), as are pushes
1033
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1034
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1035
    /// operations are never undone, and a command an earlier undo already
1036
    /// reverted is passed over, so undoing again goes further back.
1037
    ///
1038
    /// When nothing newer came from another workspace, the operation head
1039
    /// moves back to before the command. Otherwise the command is reverted
1040
    /// in place: every reference it changed goes back to its value before
1041
    /// it, recorded as a new operation that names it, and anything another
1042
    /// workspace changed since is kept. A reference both the command and a
1043
    /// later operation of another workspace changed is not guessed at: the
1044
    /// undo is refused, naming it.
1045
    ///
1046
    /// When the working copy is clean and was clean after the command's
1047
    /// predecessor, its files follow too, since nothing on disk can be
1048
    /// lost; otherwise they stay as they are (an undone commit's edits come
1049
    /// back as uncommitted work).
105016×
    pub fn undo(&self) -> Result<Undone> {
105116×
        let _wc = self.lock_working_copy()?;
105216×
        let clean_now =
105316×
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
105416×
        let (head_ref, head) = self.head_op()?;
105516×
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
105640×
        let load = |r: &ObjectRef| -> Result<Op> {
105740×
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
105840×
        };
105916×
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
106016×
        let mut pending_checkout: Option<Op> = None;
106116×
        let mut others = 0usize;
106216×
        let (mut r, mut op) = (head_ref, head.clone());
106315×
        let (target_ref, target, parent) = loop {
106441×
            let parent = match op.parents.first() {
106540×
                Some(p) => Some((*p, load(p)?)),
10661×
                None => None,
1067
            };
106841×
            if skip.contains(&r) {
10691×
                pending_checkout = None;
107040×
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
107110×
                // A push cannot be taken back: undoing it would only make
107210×
                // this repository forget what the remote holds.
107330×
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
107410×
                others += 1;
107520×
            } else if let Some(u) = op.undoes {
10761×
                skip.insert(u);
10771×
                pending_checkout = None;
107819×
            } else if op.command.ends_with(" (checkout)") {
10793×
                pending_checkout = Some(op.clone());
10803×
            } else {
108116×
                match parent {
108215×
                    Some((_, p)) => break (r, op, p),
10831×
                    None => return fail("nothing to undo in this workspace"),
1084
                }
1085
            }
108625×
            match parent {
108725×
                Some((pr, p)) => (r, op) = (pr, p),
10880×
                None => return fail("nothing to undo in this workspace"),
1089
            }
1090
        };
109115×
        let before = parent.view;
109215×
        let after = pending_checkout
109315×
            .map(|o| o.view)
109415×
            .unwrap_or_else(|| target.view.clone());
109515×
        let changes = self.view_changes(&before, &after)?;
109615×
        let pushed = self.pushed_by(&before, &after, &head.view)?;
109715×
        let restored_wc = before.workspaces.get(&self.workspace).copied();
109815×
        if others == 0 {
1099
            // Only this workspace's operations since: move the head back.
110010×
            let _lock = if self.store.is_local() {
110110×
                Some(self.lock_ops()?)
1102
            } else {
11030×
                None
1104
            };
110510×
            let parent_ref = *target.parents.first().expect("the target has a parent");
110610×
            let (now, version) = self.read_head()?;
110710×
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
11080×
                return fail("another oxy command ran while undoing; run undo again");
110910×
            }
1110
        } else {
11115×
            let view = self.revert_view(&head.view, &before, &after)?;
11123×
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1113
        }
111413×
        self.drop_manifest();
111513×
        if let Some(then) = restored_wc {
111613×
            if clean_now && Some(then) != wc_now {
1117
                // Past `core.snapshot-retention` the working copy may be
1118
                // gone: the files then stay as they are.
111910×
                let Ok(wc) = self.store.get_change(&then) else {
11200×
                    return Ok(Undone {
11210×
                        command: target.command,
11220×
                        changes,
11230×
                        others_kept: others,
11240×
                        pushed,
11250×
                    });
1126
                };
112710×
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
11288×
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1129
                    // The files differ from the restored working copy by
1130
                    // exactly what the undone command did: nothing else is
1131
                    // on disk, as the working copy was clean.
11328×
                    self.checkout(&base, true, "oxy undo (checkout)")?;
11332×
                }
11343×
            }
11350×
        }
113613×
        Ok(Undone {
113713×
            command: target.command,
113813×
            changes,
113913×
            others_kept: others,
114013×
            pushed,
114113×
        })
114216×
    }
1143
1144
    /// Whether operation `op` was a push: it changed only what this
1145
    /// repository knows of remotes.
114631×
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
114731×
        let Some(p) = parent else {
11481×
            return false;
1149
        };
115030×
        op.command.starts_with("oxy push")
11511×
            && op.view.bookmarks == p.view.bookmarks
11521×
            && op.view.tags == p.view.tags
11531×
            && op.view.workspaces == p.view.workspaces
11541×
            && op.view.policy == p.view.policy
115531×
    }
1156
1157
    /// Whether operation `op` (whose predecessor is `parent`) was this
1158
    /// workspace's. Operations record their workspace (oxygen#99); for older
1159
    /// ones it is read from the view: one that changed only other
1160
    /// workspaces' working copies was theirs, anything else counts as ours.
116130×
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
116230×
        if let Some(w) = op.workspace {
116330×
            return w == self.workspace;
11640×
        }
11650×
        let Some(p) = parent else {
11660×
            return true;
1167
        };
11680×
        let ids: BTreeSet<&WorkspaceId> = op
11690×
            .view
11700×
            .workspaces
11710×
            .keys()
11720×
            .chain(p.view.workspaces.keys())
11730×
            .collect();
11740×
        let moved: Vec<&WorkspaceId> = ids
11750×
            .into_iter()
11760×
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
11770×
            .collect();
11780×
        moved.is_empty() || moved.contains(&&self.workspace)
117930×
    }
1180
1181
    /// `current` with what changed from `before` to `after` put back, this
1182
    /// workspace's working copy included; refused when a later operation
1183
    /// changed one of the same references again.
11845×
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
118510×
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
118610×
            cur: &mut BTreeMap<K, V>,
118710×
            before: &BTreeMap<K, V>,
118810×
            after: &BTreeMap<K, V>,
118910×
            name: impl Fn(&K) -> String,
119010×
            clashes: &mut Vec<String>,
119110×
        ) {
119210×
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
119310×
            for k in keys {
11945×
                let (b, a) = (before.get(k), after.get(k));
11955×
                if a == b {
11964×
                    continue;
11971×
                }
11981×
                if cur.get(k) != a {
11991×
                    clashes.push(name(k));
12001×
                    continue;
12010×
                }
12020×
                match b {
12030×
                    Some(v) => cur.insert(k.clone(), v.clone()),
12040×
                    None => cur.remove(k),
1205
                };
1206
            }
120710×
        }
12085×
        let mut out = current.clone();
12095×
        let mut clashes = Vec::new();
1210
        // A bookmark another workspace moved since is put back head by
1211
        // head: the heads the command added go, the heads it replaced
1212
        // return, and the other workspace's heads stay. Only when a later
1213
        // change was built on one the command added is that not possible.
12145×
        let names: BTreeSet<&String> = before
12155×
            .bookmarks
12165×
            .keys()
12175×
            .chain(after.bookmarks.keys())
12185×
            .collect();
12198×
        for name in names {
12208×
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
12218×
            let cur = current.bookmarks.get(name);
12228×
            if a == b {
12234×
                continue;
12244×
            }
12254×
            if cur == a {
12262×
                match b {
12272×
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
12280×
                    None => out.bookmarks.remove(name),
1229
                };
12302×
                continue;
12312×
            }
12322×
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
12330×
                clashes.push(format!("bookmark {name}"));
12340×
                continue;
1235
            };
12362×
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
12372×
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
12382×
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
12392×
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
12402×
            if !added.iter().all(|h| now.contains(h)) {
12411×
                clashes.push(format!(
1242
                    "bookmark {name} (a later change builds on this one)"
1243
                ));
12441×
                continue;
12451×
            }
12461×
            let mut heads: Vec<ChangeHash> = now
12471×
                .iter()
12483×
                .filter(|h| !added.contains(h))
12491×
                .chain(was.difference(&became))
12501×
                .copied()
12511×
                .collect();
12521×
            heads.sort();
12531×
            heads.dedup();
12541×
            let heads = self.load_state(&heads)?.maximal(&heads);
12551×
            out.bookmarks.insert(
12561×
                name.clone(),
12571×
                self.store.put_state(&StateObject::new(heads))?,
1258
            );
1259
        }
1260
12615×
        back(
12625×
            &mut out.tags,
12635×
            &before.tags,
12645×
            &after.tags,
12650×
            |k| format!("tag {k}"),
12665×
            &mut clashes,
1267
        );
12685×
        let mine = self.workspace;
126915×
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
127015×
            v.workspaces
127115×
                .iter()
127229×
                .filter(|(k, _)| **k != mine)
127315×
                .map(|(k, v)| (*k, *v))
127415×
                .collect()
127515×
        };
12765×
        let mut theirs = others(&out);
12775×
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
12781×
            Some(p) => format!("the workspace at {}", p.display()),
12790×
            None => format!("workspace {}", id.to_hex()),
12801×
        };
12815×
        back(
12825×
            &mut theirs,
12835×
            &others(before),
12845×
            &others(after),
12855×
            workspace_name,
12865×
            &mut clashes,
1287
        );
12885×
        let empty = BTreeMap::new();
12895×
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
12905×
        for n in names {
12910×
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
12920×
            back(
12930×
                &mut cur,
12940×
                before.remotes.get(n).unwrap_or(&empty),
12950×
                after.remotes.get(n).unwrap_or(&empty),
12960×
                |k| format!("{n}/{k}"),
12970×
                &mut clashes,
1298
            );
12990×
            if cur.is_empty() {
13000×
                out.remotes.remove(n);
13010×
            } else {
13020×
                out.remotes.insert(n.clone(), cur);
13030×
            }
1304
        }
13055×
        if before.policy != after.policy {
13060×
            if out.policy == after.policy {
13070×
                out.policy = before.policy;
13080×
            } else {
13090×
                clashes.push("the policy".into());
13100×
            }
13115×
        }
13125×
        if !clashes.is_empty() {
13132×
            return fail(format!(
1314
                "undo would also take back what another workspace has done since to {}; \
1315
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
13162×
                clashes.join(", ")
1317
            ));
13183×
        }
13193×
        out.workspaces = theirs;
13203×
        match before.workspaces.get(&mine) {
13213×
            Some(wc) => out.workspaces.insert(mine, *wc),
13220×
            None => out.workspaces.remove(&mine),
1323
        };
13243×
        Ok(out)
13255×
    }
1326
1327
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1328
    /// in `now` already holds: undoing them locally leaves them there.
132915×
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
133015×
        let mut out = Vec::new();
133118×
        for (name, st) in &after.bookmarks {
133218×
            if before.bookmarks.get(name) == Some(st) {
13334×
                continue;
133414×
            }
133514×
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
133614×
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
13370×
                None => BTreeSet::new(),
1338
            };
133914×
            let added: Vec<ChangeHash> = self
134014×
                .store
134114×
                .get_state(st)?
1342
                .heads
134314×
                .into_iter()
134420×
                .filter(|h| !had.contains(h))
134514×
                .collect();
134614×
            if added.is_empty() {
13471×
                continue;
134813×
            }
134913×
            for (remote, bookmarks) in &now.remotes {
13501×
                if let Some(rs) = bookmarks.get(name) {
13511×
                    let theirs = self.store.get_state(rs)?.heads;
13521×
                    if added.iter().any(|h| theirs.contains(h)) {
13531×
                        out.push((name.clone(), remote.clone()));
13541×
                    }
13550×
                }
1356
            }
1357
        }
135815×
        Ok(out)
135915×
    }
1360
1361
    /// The last operation that was not a snapshot.
13622×
    pub fn last_command(&self) -> Result<Op> {
13632×
        let (_, mut op) = self.head_op()?;
13644×
        while op.is_snapshot() {
13652×
            let Some(parent) = op.parents.first() else {
13660×
                break;
1367
            };
13682×
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1369
        }
13702×
        Ok(op)
13712×
    }
1372
1373
    // ------------------------------------------------------------ states
1374
1375
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1376199×
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1377199×
        if let Some(st) = self.load_state_checkpointed(heads)? {
13784×
            return Ok(st);
1379194×
        }
1380194×
        self.load_state_full(heads)
1381199×
    }
1382
1383
    /// The state of `heads` for its history (changes, tree, metadata) with
1384
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1385
    /// and friends. Build the graphs a command needs with
1386
    /// [`Repo::load_graphs_of`].
13871675×
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
13881675×
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
138931×
            return Ok(st);
13901644×
        }
13911644×
        self.load_state_replayed(heads, State::new_history_only())
13921675×
    }
1393
1394
    /// Build these file graphs in a history-only state.
13951760×
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
13961760×
        state
13971760×
            .load_graphs(
13981760×
                nodes,
139954×
                |refs| {
140054×
                    self.read_blobs(refs).map_err(|e| {
14013×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14023×
                    })
140354×
                },
14042004×
                |h| self.change_bytes(h),
1405
            )
14061760×
            .map_err(|e| self.index_damage(e))
14071760×
    }
1408
1409
    /// An error building graphs, and when it is a state index found
1410
    /// damaged (a file's history that does not match its hash), the
1411
    /// workspace's state indexes removed: they are rebuilt from history by
1412
    /// the next command.
14134×
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
14144×
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
14153×
            return e.into();
1416
        };
14172×
        for path in self.state_indexes() {
14182×
            let _ = fs::remove_file(path);
14192×
        }
14201×
        RepoError::Msg(format!(
14211×
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
14221×
        ))
14234×
    }
1424
1425
    /// The graphs of `nodes` of a history-only state, built beside it (see
1426
    /// [`State::build_graphs_detached`]).
142777×
    pub fn build_graphs_detached(
142877×
        &self,
142977×
        state: &State,
143077×
        nodes: &[crate::ids::NodeId],
143177×
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
143277×
        Ok(state
143377×
            .build_graphs_detached(
143477×
                nodes,
14350×
                |refs| {
14360×
                    self.read_blobs(refs).map_err(|e| {
14370×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14380×
                    })
14390×
                },
144083×
                |h| self.change_bytes(h),
1441
            )
144277×
            .map_err(|e| self.index_damage(e))?
144377×
            .into_iter()
144477×
            .collect())
144577×
    }
1446
1447
    /// The contents of texts [`State::single_text`] gave: blobs read in
1448
    /// one go, inline ones from their changes.
1449355×
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1450
        use crate::objects::TextRef;
1451355×
        let refs: Vec<ObjectRef> = texts
1452355×
            .iter()
14535546×
            .filter_map(|t| match t {
14541×
                TextRef::Blob(r, _, _) => Some(*r),
14555545×
                TextRef::Inline { .. } => None,
14565546×
            })
1457355×
            .collect();
1458355×
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1459355×
        let mut out = Vec::with_capacity(texts.len());
14605546×
        for t in texts {
14615546×
            let lines = match t {
14621×
                TextRef::Blob(_, count, form) => {
14631×
                    let content = blobs
14641×
                        .next()
14651×
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
14661×
                    crate::objects::text_lines(&content, *count, *form)?
1467
                }
14685545×
                TextRef::Inline { change, start, end } => {
14695545×
                    let bytes = self.change_bytes(change)?;
14705545×
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
14710×
                        RepoError::Msg("an inline insert lies outside its change".into())
14720×
                    })?;
14735545×
                    crate::objects::inline_lines(range)?
1474
                }
1475
            };
14765546×
            out.push(lines.bytes().to_vec());
1477
        }
1478355×
        Ok(out)
1479355×
    }
1480
1481
    /// Build every graph a history-only state still lacks, making it full.
14821790×
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
14831790×
        state
14841790×
            .load_all_graphs(
148516×
                |refs| {
148616×
                    self.read_blobs(refs).map_err(|e| {
14870×
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
14880×
                    })
148916×
                },
14903751×
                |h| self.change_bytes(h),
1491
            )
14921790×
            .map_err(|e| self.index_damage(e))
14931790×
    }
1494
1495
    /// A change's encoding, for building graphs of its inline inserts. The
1496
    /// last few read are kept: a checkout building graphs a batch at a
1497
    /// time reads the same large changes for every batch, often in turn.
149811383×
    fn change_bytes(
149911383×
        &self,
150011383×
        h: &ChangeHash,
150111383×
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
150211383×
        let mut cache = self.last_change.borrow_mut();
150319586×
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
15048919×
            let hit = cache.remove(i);
15058919×
            let b = hit.1.clone();
15068919×
            cache.push(hit);
15078919×
            return Ok(b);
15082464×
        }
15092464×
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
15100×
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
15110×
        })?);
15122464×
        cache.push((*h, b.clone()));
1513
        // The last few, within a memory budget; the newest always stays.
15143968×
        while cache.len() > CHANGE_CACHE_COUNT
15152464×
            || (cache.len() > 1
15167380×
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
15171504×
        {
15181504×
            cache.remove(0);
15191504×
        }
15202464×
        Ok(b)
152111383×
    }
1522
1523
    /// Load the dependency closure of `heads` change by change.
1524248×
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1525248×
        self.load_state_replayed(heads, State::new())
1526248×
    }
1527
15283235×
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
15293235×
        let history = state.is_history_only();
15303235×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
15313235×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1532
        {
15333235×
            let _t = crate::timing::phase("load: read and add changes");
15343235×
            let (mut read, mut add, mut fetch) = (
15353235×
                std::time::Duration::ZERO,
15363235×
                std::time::Duration::ZERO,
15373235×
                std::time::Duration::ZERO,
15383235×
            );
153913139×
            while let Some(h) = stack.pop() {
1540
                // A change the state holds brings its history with it.
15419907×
                if !seen.insert(h) || state.contains(&h) {
15422354×
                    continue;
15437553×
                }
15447553×
                let t0 = std::time::Instant::now();
1545
                // A history-only state reads text only for the graphs it
1546
                // builds; either way the hash is the one asked for.
15477553×
                let (c, texts) = if history {
15486224×
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
15496223×
                    fetch += t0.elapsed();
15506223×
                    Change::decode_skeleton(&bytes, h)
15516223×
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1552
                } else {
15531329×
                    (self.store.get_change(&h)?, Vec::new())
1554
                };
15557550×
                read += t0.elapsed();
15567550×
                stack.extend(c.deps.iter().copied());
15577550×
                let t1 = std::time::Instant::now();
15587550×
                state.add_known(h, c, texts);
15597550×
                add += t1.elapsed();
1560
            }
15613232×
            crate::timing::record("load:   of which reading", read);
15623232×
            crate::timing::record("load:     of which fetching", fetch);
15633232×
            crate::timing::record("load:   of which applying", add);
1564
        }
15653232×
        let _t = crate::timing::phase("load: validate");
15663232×
        state.validate()?;
15673232×
        Ok(state)
15683235×
    }
1569
15702304×
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
15712304×
        if self.bare {
15722×
            return fail("this is a bare repository: it has no working copy");
15732302×
        }
15742302×
        let view = self.view()?;
15752302×
        let h = *view
15762302×
            .workspaces
15772302×
            .get(&self.workspace)
15782302×
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
15792301×
        Ok((h, self.store.get_change(&h)?))
15802304×
    }
1581
1582
    /// Heads of a bookmark's state (spec §10.1).
15831767×
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
15841767×
        match view.bookmarks.get(bookmark) {
15851767×
            Some(st) => Ok(self.store.get_state(st)?.heads),
15860×
            None => Ok(vec![]),
1587
        }
15881767×
    }
1589
1590508×
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1591508×
        self.heads_of(&self.view()?, &self.config.bookmark)
1592508×
    }
1593
1594
    // ------------------------------------------------------------ blobs
1595
1596394×
    fn blob_for(content: &[u8]) -> Blob {
1597394×
        Blob::of(content)
1598394×
    }
1599
1600245×
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1601245×
        Self::blob_for(content).hash()
1602245×
    }
1603
1604147×
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1605190×
        for c in crate::chunk::chunks(content) {
1606190×
            self.store.put_chunk(c)?;
1607
        }
1608147×
        Ok(self
1609147×
            .store
1610147×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1611147×
    }
1612
1613
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1614
    /// all their chunks, are read in parallel; a blob the store lacks goes
1615
    /// through [`Repo::read_blob`], which may fetch it lazily.
1616429×
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1617429×
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1618429×
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
161980×
            blobs.push(match got {
162075×
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
16210×
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
16225×
                Err(crate::store::StoreError::NotFound(_)) => None,
16230×
                Err(e) => return Err(e.into()),
1624
            });
1625
        }
1626429×
        let chunk_refs: Vec<ObjectRef> = blobs
1627429×
            .iter()
1628429×
            .flatten()
1629429×
            .flat_map(|b| b.chunks.iter().copied())
1630429×
            .collect();
1631429×
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1632429×
        let mut out = Vec::with_capacity(refs.len());
1633429×
        for (r, blob) in refs.iter().zip(blobs) {
163480×
            match blob {
16355×
                None => out.push(self.read_blob(r)?),
163675×
                Some(b) => {
163775×
                    let mut content = Vec::with_capacity(b.length as usize);
1638114×
                    for c in &b.chunks {
1639114×
                        match chunks.next() {
1640114×
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
16410×
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
16420×
                            Some(Err(e)) => return Err(e.into()),
16430×
                            None => return fail("chunk list ended early"),
1644
                        }
1645
                    }
164675×
                    out.push(content);
1647
                }
1648
            }
1649
        }
1650424×
        Ok(out)
1651429×
    }
1652
1653
    /// Read a blob's content, fetching it from the remote that withheld it
1654
    /// when it is lazily absent (spec §13.5).
1655112×
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1656112×
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
16574×
            self.fetch_lazy_blob(r)?;
1658108×
        }
1659112×
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1660107×
        let mut out = Vec::with_capacity(blob.length as usize);
1661134×
        for c in &blob.chunks {
1662134×
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1663
        }
1664107×
        Ok(out)
1665112×
    }
1666
1667
    // ------------------------------------------------------------ working copy
1668
1669
    /// Attributes from the `.oxyattributes` files in the working directory.
16702×
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1671
        // Nested repositories and ignored paths are left out, as in a walk.
16728×
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
16732×
        let files: Vec<(String, Vec<u8>)> = listing
16742×
            .files
16752×
            .into_iter()
16762×
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
16772×
            .collect();
16782×
        crate::attributes::Attributes::from_files(
16792×
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1680
        )
16812×
    }
1682
1683
    /// Folders holding a repository of their own that the last look at the
1684
    /// working copy left out, not being subrepos (oxygen#43).
168529×
    pub fn untracked_nested(&self) -> Vec<String> {
168629×
        self.untracked_nested.borrow().clone()
168729×
    }
1688
1689
    /// New untracked files the last snapshot left out for being larger than
1690
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
169133×
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
169233×
        self.skipped_large.borrow().clone()
169333×
    }
1694
1695
    /// Attributes from a materialized state's `.oxyattributes` files.
16963×
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
16976×
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
16986×
            match &f.content {
16996×
                FileContent::Text { bytes, .. }
17006×
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1701
                {
17020×
                    Some((p.as_str(), bytes.as_slice()))
1703
                }
17046×
                _ => None,
1705
            }
17066×
        }))
17073×
    }
1708
1709
    /// Store a blob, raw when the path is `nocompress`.
1710129×
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1711129×
        if !nocompress {
1712127×
            return self.store_blob(content);
17132×
        }
17142×
        for c in crate::chunk::chunks(content) {
17152×
            self.store.put_chunk_nocompress(c)?;
1716
        }
17172×
        Ok(self
17182×
            .store
17192×
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1720129×
    }
1721
1722
    /// This workspace's state index (oxygen#41): its working copy's base,
1723
    /// saved so a snapshot reads it rather than replaying history.
1724
    /// The state index of the state with these heads: this workspace keeps
1725
    /// the last few it used, named by their heads, so moving between two
1726
    /// states finds both.
17272385×
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
17282385×
        let mut heads = heads.to_vec();
17292385×
        heads.sort();
17302385×
        let mut h = blake3::Hasher::new();
17312391×
        for c in &heads {
17322391×
            h.update(&c.0);
17332391×
        }
17342385×
        self.oxy.join("index").join(format!(
17352385×
            "{}{}",
17362385×
            self.state_index_prefix(),
17372385×
            &h.finalize().to_hex()[..16]
17382385×
        ))
17392385×
    }
1740
17414688×
    fn state_index_prefix(&self) -> String {
17424688×
        format!("state-{}-", self.workspace.to_hex())
17434688×
    }
1744
1745
    /// This workspace's state indexes, newest first.
17462303×
    fn state_indexes(&self) -> Vec<PathBuf> {
17472303×
        let prefix = self.state_index_prefix();
17482303×
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
17492303×
            .into_iter()
17502303×
            .flatten()
17512303×
            .flatten()
17522303×
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
17532303×
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
17542303×
            .collect();
17552303×
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
17562303×
        found.into_iter().map(|(_, p)| p).collect()
17572303×
    }
1758
1759
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1760
    /// from this workspace's state index when it holds that history: every
1761
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1762
    /// is loaded from history and indexed for next time.
17631991×
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
17641991×
        if let Some((st, heads)) = self.read_state_index(deps) {
17651604×
            let mut have = st.maximal(deps);
17661604×
            have.sort();
17671604×
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1768
                // Re-encoding reads every history: one found damaged is
1769
                // left to the build that reads it, which reports it.
1770
                #[cfg(test)]
1771151×
                if let Some(mine) = st.write_index() {
1772146×
                    assert_eq!(
1773146×
                        Some(mine),
1774146×
                        self.load_state_history(deps)?.write_index(),
1775
                        "a state index holds the state history gives"
1776
                    );
17775×
                }
1778261×
                return Ok(st);
17791343×
            }
1780
            // An index a few changes behind (a commit, a pull since): add
1781
            // what it lacks, as long as all it holds is history of `deps`.
1782
            // Anything amiss (a change beyond a shallow boundary) takes the
1783
            // long way instead.
17841343×
            let (indexed, started) = (st.len(), std::time::Instant::now());
17851343×
            if let Ok(st) = self.load_state_replayed(deps, st) {
17861342×
                let mut all = deps.to_vec();
17871342×
                all.extend(heads.iter().copied());
17881342×
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
17891342×
                within.sort();
17901342×
                want.sort();
17911342×
                if within == want {
1792
                    #[cfg(test)]
1793679×
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1794
                    // Writing the index costs far more than replaying a
1795
                    // few small changes: it is rewritten once it falls
1796
                    // behind, or when replaying took long (large changes).
17971340×
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
17981340×
                        || started.elapsed() > INDEX_REPLAY_TIME
17993×
                    {
18003×
                        self.write_state_index(deps, &st);
18011337×
                    }
18021340×
                    return Ok(st);
18032×
                }
18041×
            }
1805387×
        }
1806390×
        let st = self.load_state_history(deps)?;
1807390×
        self.write_state_index(deps, &st);
1808390×
        Ok(st)
18091991×
    }
1810
1811
    /// Two history-only states hold the same changes and render the same
1812
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1813
    /// the checkpoint's graphs as the bases of its files' histories.
1814
    #[cfg(test)]
1815679×
    fn assert_same_state(&self, a: &State, b: &State) {
18161358×
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1817679×
        assert_eq!(ids(a), ids(b), "the same changes");
18181358×
        let files = |s: &State| {
18191358×
            let mut s = s.clone();
18201358×
            self.load_all_graphs(&mut s).unwrap();
18211358×
            s.materialize().files
18221358×
        };
1823679×
        assert_eq!(files(a), files(b), "the same files");
1824679×
    }
1825
1826
    /// The state index file: its heads, a hash of its changes block and one
1827
    /// of the rest, then the body [`State::write_index`] gives, whose first
1828
    /// block is the changes. Hashed in two parts so the log can read and
1829
    /// check the changes alone.
1830
    /// The index of `deps` if there is one, else the newest, which the
1831
    /// caller may bring up to date.
18321991×
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1833
        use std::io::Read;
18341991×
        let _t = crate::timing::phase("load: state index");
18351991×
        let exact = self.state_index_path(deps);
18361991×
        let reading = crate::timing::phase("load:   of which reading the file");
18371991×
        let mut f = match fs::File::open(&exact) {
1838261×
            Ok(f) => {
1839
                // Used now: the newest, so the last to be dropped.
1840261×
                let _ = fs::File::options()
1841261×
                    .write(true)
1842261×
                    .open(&exact)
1843261×
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1844261×
                f
1845
            }
18461730×
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1847
        };
18481604×
        let total = f.metadata().ok()?.len();
18491604×
        let mut word = [0u8; 4];
18501604×
        f.read_exact(&mut word).ok()?;
18511604×
        let n = u32::from_le_bytes(word) as usize;
18521604×
        let mut head = vec![0u8; 32 * n + 64 + 8];
18531604×
        f.read_exact(&mut head).ok()?;
18541604×
        let heads: Vec<ChangeHash> = head[..32 * n]
18551604×
            .chunks_exact(32)
18561604×
            .map(|c| ObjectRef(c.try_into().unwrap()))
18571604×
            .collect();
18581604×
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
18591604×
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
18601604×
        let at = (4 + head.len()) as u64;
18611604×
        if at.checked_add(front_len).is_none_or(|end| end > total) {
18620×
            return None;
18631604×
        }
1864
        // The front only: the files' histories after it are read, each
1865
        // checked by its own hash, when a command builds that file.
18661604×
        let mut front = vec![0u8; front_len as usize];
18671604×
        f.read_exact(&mut front).ok()?;
18681604×
        drop(reading);
18691604×
        let checking = crate::timing::phase("load:   of which checking the file");
18701604×
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
18711604×
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
18723208×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
18731604×
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
18740×
            return None;
18751604×
        }
18761604×
        drop(checking);
18771604×
        let histories = crate::state::Histories::File(
18781604×
            std::sync::Arc::new(f),
18791604×
            at + front_len,
18801604×
            total - at - front_len,
18811604×
        );
18821604×
        Some((State::read_index_front(&front, histories).ok()?, heads))
18831991×
    }
1884
1885
    /// The changes of this workspace's state index (the closure of its
1886
    /// heads), read without the rest of the index.
1887
    #[allow(clippy::type_complexity)]
1888177×
    pub(crate) fn read_state_index_changes(
1889177×
        &self,
1890177×
    ) -> Option<(
1891177×
        Vec<ChangeHash>,
1892177×
        crate::fasthash::FastMap<ChangeHash, std::sync::Arc<crate::state::ChangeMeta>>,
1893177×
    )> {
1894
        use std::io::Read;
1895177×
        let _t = crate::timing::phase("load: state index changes");
1896177×
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1897160×
        let mut word = [0u8; 4];
1898160×
        f.read_exact(&mut word).ok()?;
1899160×
        let n = u32::from_le_bytes(word) as usize;
1900
        // Heads, the two sums, the front's length, then the changes block.
1901160×
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1902160×
        f.read_exact(&mut head).ok()?;
1903160×
        let heads: Vec<ChangeHash> = head[..32 * n]
1904160×
            .chunks_exact(32)
1905160×
            .map(|c| ObjectRef(c.try_into().unwrap()))
1906160×
            .collect();
1907160×
        let sum = &head[32 * n..32 * n + 32];
1908160×
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1909160×
        let mut changes = vec![0u8; 4 + len];
1910160×
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1911160×
        f.read_exact(&mut changes[4..]).ok()?;
1912160×
        let checking = crate::timing::phase("load:   of which checking");
1913160×
        let mut h = blake3::Hasher::new();
1914160×
        h.update_rayon(&changes);
1915160×
        if h.finalize().as_bytes() != sum {
19160×
            return None;
1917160×
        }
1918160×
        drop(checking);
1919160×
        let _decoding = crate::timing::phase("load:   of which decoding");
1920160×
        Some((heads, State::read_index_changes(&changes[4..]).ok()?))
1921177×
    }
1922
1923
    /// Save `st`, the history-only state of `deps`, as this workspace's
1924
    /// state index; quietly nothing when it cannot be (it is only a cache).
1925394×
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1926394×
        let _t = crate::timing::phase("write: state index");
1927394×
        let encoding = crate::timing::phase("write:   of which encoding");
1928394×
        let Some(body) = st.write_index() else {
19290×
            return;
1930
        };
1931394×
        drop(encoding);
1932
        #[cfg(test)]
1933206×
        assert_eq!(
1934206×
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1935206×
            Some(body.clone()),
1936
            "a state index reads back as written"
1937
        );
1938394×
        let mut heads = st.maximal(deps);
1939394×
        heads.sort();
1940394×
        let mut w = crate::flat::Writer::default();
1941394×
        w.count(heads.len());
1942394×
        for h in &heads {
194317×
            w.object(h);
194417×
        }
1945
        // The body is the front's length, the front, then the files'
1946
        // histories, which carry their own hashes: the sums cover the
1947
        // front's changes block and the rest of the front.
1948394×
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
1949394×
        let front = &body[8..8 + front_len];
1950394×
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
1951788×
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1952394×
        w.fixed(&sum(&front[..split]));
1953394×
        w.fixed(&sum(&front[split..]));
1954394×
        w.fixed(&body);
1955394×
        let path = self.state_index_path(&heads);
1956394×
        let _ = fs::create_dir_all(self.oxy.join("index"));
1957394×
        let _ = write_cache(&path, &w.0);
1958
        // The last two used: the index of a state moved away from stays for
1959
        // a move back. Older ones (and the unnamed one of before) go.
1960394×
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
19611×
            let _ = fs::remove_file(old);
19621×
        }
1963394×
        let _ = fs::remove_file(
1964394×
            self.oxy
1965394×
                .join("index")
1966394×
                .join(format!("state-{}", self.workspace.to_hex())),
1967394×
        );
1968394×
    }
1969
19706×
    fn locks_dir(&self) -> PathBuf {
19716×
        self.oxy.join("locks")
19726×
    }
1973
1974
    /// Whether `path` is locked locally for editing (spec §18, advisory).
19753×
    pub fn is_locked(&self, path: &str) -> bool {
19763×
        self.locks_dir().join(path.replace('/', "%2F")).exists()
19773×
    }
1978
1979
    /// Take the advisory local lock on a `lockable` file and make it writable.
19802×
    pub fn lock_path(&self, path: &str) -> Result<()> {
19812×
        let attrs = self.disk_attributes();
19822×
        if !attrs.lookup(path).lockable {
19831×
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
19841×
        }
19851×
        fs::create_dir_all(self.locks_dir())?;
19861×
        write_atomic(
19871×
            &self.locks_dir().join(path.replace('/', "%2F")),
19881×
            std::process::id().to_string().as_bytes(),
19890×
        )?;
19901×
        set_readonly(&self.root.join(path), false)?;
19911×
        Ok(())
19922×
    }
1993
1994
    /// Release the local lock and make the file read-only again.
19951×
    pub fn unlock_path(&self, path: &str) -> Result<()> {
19961×
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
19971×
        if self.root.join(path).exists() {
19981×
            set_readonly(&self.root.join(path), true)?;
19990×
        }
20001×
        Ok(())
20011×
    }
2002
2003
    /// Whether a repository path is inside the sparse filter (spec §17).
200424376×
    pub fn in_scope(&self, path: &str) -> bool {
200524376×
        self.config.sparse_paths.is_empty()
200682×
            || self
200782×
                .config
200882×
                .sparse_paths
200982×
                .iter()
201099×
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
201124376×
    }
2012
20131×
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
20141×
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
20151×
    }
2016
2017
    /// Walk the working copy; with a manifest, a file whose size and mtime
2018
    /// match it is not read: an opaque file yields its known blob, and a
2019
    /// text file whose recorded graph key equals its base graph's key in
2020
    /// `keys` (path → key) is marked unchanged; other text files are read
2021
    /// but keep their known hash. Files modified within two seconds of the
2022
    /// manifest are never trusted (a racy stat).
2023
    ///
2024
    /// `.oxyattributes` files are always read, since their content is
2025
    /// needed; and when any of them is not known unchanged (added, removed,
2026
    /// edited, or changed in the base), no text file is taken as unchanged,
2027
    /// because attributes decide how a file compares with the base.
2028
    ///
2029
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2030
    /// (the base state's files) that exists on disk is included even when
2031
    /// an ignore rule matches it, as in Git.
20321271×
    fn walk_working_copy_with(
20331271×
        &self,
20341271×
        cache: Option<&prompt::Manifest>,
20351271×
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
20361271×
        keys: Option<&KeyOf>,
20371271×
    ) -> Result<BTreeMap<String, FsEntry>> {
2038
        let mut out: BTreeMap<String, FsEntry>;
20391271×
        let sparse = &self.config.sparse_paths;
20409138×
        let in_scope = |p: &str| {
20419138×
            sparse.is_empty()
20427×
                || sparse
20437×
                    .iter()
20447×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
20459138×
        };
20461271×
        let walk_phase = crate::timing::phase("walk:   of which listing");
2047
        let walk::Listing {
20481271×
            files,
20491271×
            symlinks,
20501271×
            nested,
20511271×
            dirs,
20521271×
        } = match self.listing_cache.take() {
2053163×
            Some(l) => l,
2054
            // Ignore rules apply to untracked paths only, so the base's
2055
            // files are not matched against them (an added file is: a rule
2056
            // written after it was snapshotted leaves it out again).
20579150×
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2058
        };
2059
        // A new file larger than the limit is left out and named, not taken
2060
        // in unseen (oxygen#98): a build's output or a downloaded image
2061
        // would otherwise be stored by the next status, kept by the
2062
        // operation log. Files tracked, or already in the working copy, stay.
20631271×
        let limit = self.config.max_new_file;
20641271×
        let mut skipped = Vec::new();
20651271×
        let files: Vec<_> = files
20661271×
            .into_iter()
206712096×
            .filter(|(rel, _, meta)| {
206812096×
                let new = !tracked.contains_key(rel)
20693099×
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
207012096×
                if limit > 0 && new && meta.size > limit {
20713×
                    skipped.push((rel.clone(), meta.size));
20723×
                    return false;
207312093×
                }
207412093×
                true
207512096×
            })
20761271×
            .collect();
20771271×
        *self.skipped_large.borrow_mut() = skipped;
20781271×
        let keys = keys.filter(|k| {
207912081×
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
20801268×
            let attrs_unchanged =
20811268×
                files
20821268×
                    .iter()
208312062×
                    .filter(|(r, _, _)| is_attributes(r))
20841268×
                    .all(|(rel, _, meta)| {
20859×
                        stat_cached(rel, meta, cache)
20869×
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
20879×
                    });
20881268×
            let none_removed = tracked
20891268×
                .keys()
20909091×
                .filter(|r| is_attributes(r))
20911268×
                .all(|r| on_disk.contains(r.as_str()));
20921268×
            attrs_unchanged && none_removed
20931268×
        });
20941271×
        *self.walked_dirs.borrow_mut() =
20951271×
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
20961271×
        drop(walk_phase);
20971271×
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2098
        // Reading files is most of a walk's cost; do it in parallel.
2099
        {
2100
            use rayon::prelude::*;
21011271×
            let mut read: Vec<(String, FsEntry)> = files
21021271×
                .par_iter()
210312093×
                .map(|(rel, path, meta)| {
2104
                    // A key is worked out only for a file the manifest
2105
                    // knows with the same stat and a key of its own.
210612093×
                    let key = keys
210712093×
                        .filter(|_| !is_attributes(rel))
210812093×
                        .filter(|_| {
210912053×
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
211012053×
                        })
211112093×
                        .and_then(|k| k(rel));
211212093×
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
211312093×
                })
21141271×
                .collect::<Result<Vec<_>>>()?;
211512091×
            for (rel, e) in read.iter_mut() {
2116
                // A cached blob the store lost (gc, a partial clone): read the file after all.
211712091×
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
21180×
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
21190×
                    e.blob = None;
212012091×
                }
2121
            }
2122
            // The listing is in path order, so the map is built without
2123
            // searching.
21241270×
            out = read.into_iter().collect();
21251270×
            for (rel, target) in symlinks {
21262×
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
21272×
            }
2128
        }
21291270×
        drop(_read_phase);
21301270×
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2131
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2132
        // already tracked as subrepo nodes, they contribute their pin;
2133
        // unregistered ones are left alone.
21341270×
        let modules = self.modules_on_disk();
21351270×
        let removed = self.removed_subrepos();
21361270×
        for rel in &removed {
21373×
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
21381×
                self.clear_removed_subrepo(rel);
21392×
            }
2140
        }
21411270×
        let mut untracked_nested = Vec::new();
21421270×
        for dir in nested {
214330×
            let rel = self.rel_path(&dir);
214430×
            if !self.in_scope(&rel) || removed.contains(&rel) {
21453×
                continue;
214627×
            }
214727×
            let registered = modules.entries.get(&rel);
214827×
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2149
            {
21501×
                untracked_nested.push(rel);
21511×
                continue;
215226×
            }
215326×
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
215426×
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2155
        }
21561270×
        untracked_nested.sort();
21571270×
        *self.untracked_nested.borrow_mut() = untracked_nested;
2158
        // Tracked paths the ignore rules hid.
21591270×
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
216085×
            if !self.in_scope(rel) {
216110×
                continue;
216275×
            }
216375×
            let path = self.root.join(rel);
216475×
            if *kind == NodeKind::Subrepo {
21654×
                if removed.contains(rel) {
21662×
                    continue;
21672×
                }
21682×
                let present =
21692×
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
21702×
                if present {
21710×
                    let pin = subrepos::read_pin(
21720×
                        &path,
21730×
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
21740×
                    )?;
21750×
                    out.insert(
21760×
                        rel.clone(),
21770×
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2178
                    );
21792×
                } else if let Some(b) = blob {
21802×
                    // Not cloned (or emptied): the pin stays as recorded, as a
21812×
                    // Git gitlink does when its directory is absent.
21822×
                    out.insert(
21832×
                        rel.clone(),
21842×
                        FsEntry {
21852×
                            blob: Some(*b),
21862×
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
21872×
                        },
21882×
                    );
21892×
                }
21902×
                continue;
219171×
            }
219271×
            let Ok(meta) = fs::symlink_metadata(&path) else {
219371×
                continue;
2194
            };
21950×
            let ft = meta.file_type();
21960×
            if ft.is_symlink() {
21970×
                let target = fs::read_link(&path)?;
21980×
                out.insert(
21990×
                    rel.clone(),
22000×
                    FsEntry::new(
22010×
                        NodeKind::Symlink,
2202
                        false,
22030×
                        target.to_string_lossy().as_bytes().to_vec(),
2204
                    ),
2205
                );
22060×
            } else if ft.is_file() {
22070×
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
22080×
                out.insert(rel.clone(), e);
22090×
            }
2210
        }
22111270×
        Ok(out)
22121271×
    }
2213
2214
    /// The entry for one regular file, read or served from the stat cache.
22150×
    fn file_entry(
22160×
        &self,
22170×
        rel: &str,
22180×
        path: &Path,
22190×
        meta: &walk::Stat,
22200×
        cache: Option<&prompt::Manifest>,
22210×
    ) -> Result<FsEntry> {
22220×
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
22230×
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
22240×
            e.content = std::sync::Arc::new(fs::read(path)?);
22250×
            e.blob = None;
22260×
        }
22270×
        Ok(e)
22280×
    }
2229
2230
    /// The non-directory paths of a snapshot with their kinds, for the
2231
    /// walker's `tracked` set.
22322×
    pub(crate) fn tracked_kinds(
22332×
        snapshot: &Snapshot,
22342×
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
22352×
        snapshot
22362×
            .files
22372×
            .iter()
223812×
            .filter(|(_, f)| f.kind != NodeKind::Dir)
22398×
            .map(|(p, f)| {
22408×
                let blob = match &f.content {
22414×
                    FileContent::Opaque { blobs } => blobs.first().copied(),
22424×
                    _ => None,
2243
                };
22448×
                (p.clone(), (f.kind, blob))
22458×
            })
22462×
            .collect()
22472×
    }
2248
2249
    /// A path under the root as a `/`-separated relative string.
225068×
    pub(crate) fn rel_path(&self, path: &Path) -> String {
225168×
        path.strip_prefix(&self.root)
225268×
            .unwrap_or(path)
225368×
            .components()
2254130×
            .map(|c| c.as_os_str().to_string_lossy().to_string())
225568×
            .collect::<Vec<_>>()
225668×
            .join("/")
225768×
    }
2258
}
2259
2260
impl Repo {
2261
    /// Changes reachable from the bookmark and the working copy, newest first.
226295×
    pub fn log(&self) -> Result<Vec<LogEntry>> {
226395×
        let heads = self.bookmark_heads()?;
226495×
        if self.bare {
22651×
            return self.log_state(&heads);
226694×
        }
226794×
        let (wc_hash, wc) = self.working_copy()?;
226894×
        let mut all = heads.clone();
226994×
        all.push(wc_hash);
227094×
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
227194×
        let mut entries: Vec<LogEntry> = Vec::new();
2272
        // A shallow clone knows changes beyond its boundary from a
2273
        // checkpoint's metadata only: its log comes from the state.
227494×
        let metas = if self.is_shallow() {
22751×
            self.load_state_history(&all)?
22761×
                .changes()
22779×
                .map(|(h, m)| (*h, m.clone()))
22781×
                .collect()
2279
        } else {
2280
            // The working copy's change is in hand, and is never in the
2281
            // state index: its metadata is not looked up again.
228293×
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
228393×
            below.extend(wc.deps.iter().copied());
228493×
            let _t = crate::timing::phase("log: metadata");
228593×
            let mut metas = self.metas_of(&below)?;
2286325×
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
228793×
                metas.push((wc_hash, crate::state::ChangeMeta::of(&wc)));
228893×
            }
228993×
            metas
2290
        };
2291427×
        for (h, meta) in metas {
2292427×
            entries.push(LogEntry {
2293427×
                hash: h,
2294427×
                change: meta,
2295427×
                is_working_copy: h == wc_hash,
2296427×
                is_head: head_set.contains(&h),
2297427×
            });
2298427×
        }
229994×
        let _sorting = crate::timing::phase("log: sort");
2300
        // The hash makes the order total, so an unstable sort gives the same.
2301825×
        entries.sort_unstable_by(|a, b| {
2302825×
            b.is_working_copy
2303825×
                .cmp(&a.is_working_copy)
2304825×
                .then(b.change.hlc.cmp(&a.change.hlc))
2305825×
                .then(b.hash.cmp(&a.hash))
2306825×
        });
230794×
        Ok(entries)
230895×
    }
2309
2310
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2311
    /// count, for paginated views.
23120×
    pub fn log_window(
23130×
        &self,
23140×
        heads: &[ChangeHash],
23150×
        offset: usize,
23160×
        limit: usize,
23170×
    ) -> Result<(Vec<LogEntry>, usize)> {
23180×
        let all = self.log_state(heads)?;
23190×
        let total = all.len();
23200×
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
23210×
    }
2322
2323
    /// The log of the state with these heads, newest first, with no working
2324
    /// copy involved (for hosted repositories and any explicit state).
232510×
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2326
        // The log needs change metadata only: neither graphs nor the tree.
232710×
        if self.is_shallow() {
23280×
            return Ok(self.log_of(&self.load_state_history(heads)?));
232910×
        }
233010×
        let metas = self.metas_of(heads)?;
233110×
        let depended: BTreeSet<ChangeHash> = metas
233210×
            .iter()
233330×
            .flat_map(|(_, m)| m.deps.iter().copied())
233410×
            .collect();
233510×
        let mut entries: Vec<LogEntry> = metas
233610×
            .into_iter()
233710×
            .map(|(h, meta)| LogEntry {
233830×
                hash: h,
233930×
                is_head: !depended.contains(&h),
234030×
                change: meta,
2341
                is_working_copy: false,
234230×
            })
234310×
            .collect();
234437×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
234510×
        Ok(entries)
234610×
    }
2347
2348
    /// Every change of the state with these heads and its metadata, read
2349
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2350
    /// a shallow clone's boundary is left out.
2351177×
    pub fn metas_of(
2352177×
        &self,
2353177×
        heads: &[ChangeHash],
2354177×
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2355177×
        let boundary = self.boundary();
2356
        // The state index holds the metadata of its heads' closure: a
2357
        // change found there is not read from the store (a change object
2358
        // can be as large as the tree it adds).
2359177×
        let read = self.read_state_index_changes();
2360
        // Every one of `heads` in the index, and every head of the index
2361
        // among them: their closure is the index's changes, all of them
2362
        // (it is closed), and no walk is needed to find it.
2363177×
        if let Some((index_heads, all)) = &read {
2364160×
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
2365160×
            if heads.iter().all(|h| all.contains_key(h))
23660×
                && index_heads.iter().all(|h| asked.contains(h))
2367
            {
23680×
                let (_, all) = read.expect("matched above");
2369
                #[cfg(test)]
2370
                {
2371
                    // The walk the shortcut saves finds the same changes.
23720×
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
23730×
                    let mut stack = heads.to_vec();
23740×
                    while let Some(h) = stack.pop() {
23750×
                        if seen.insert(h) {
23760×
                            stack.extend(self.store.get_change_meta(&h)?.deps);
23770×
                        }
2378
                    }
23790×
                    assert_eq!(seen, all.keys().copied().collect::<HashSet<_>>());
2380
                }
23810×
                return Ok(all
23820×
                    .into_iter()
23830×
                    .map(|(h, m)| (h, std::sync::Arc::unwrap_or_clone(m)))
23840×
                    .collect());
2385160×
            }
238617×
        }
2387177×
        let mut indexed = read.map(|(_, all)| all);
2388177×
        let _walk = crate::timing::phase("metadata: walk");
2389177×
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2390177×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2391177×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2392177×
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
23931277×
        while let Some(h) = stack.pop() {
23941100×
            if !seen.insert(h) {
2395461×
                continue;
2396639×
            }
2397
            // Taken out of the index's map, each once: not copied.
2398639×
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2399
                #[cfg(test)]
24000×
                assert_eq!(
24010×
                    *meta,
24020×
                    self.store.get_change_meta(&h)?,
2403
                    "the state index holds a change's metadata"
2404
                );
24050×
                let meta = std::sync::Arc::unwrap_or_clone(meta);
24060×
                stack.extend(meta.deps.iter().copied());
24070×
                out.push((h, meta));
24080×
                continue;
2409639×
            }
2410639×
            let started = std::time::Instant::now();
2411639×
            let meta = match self.store.get_change_meta(&h) {
2412639×
                Ok(m) => m,
24130×
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
24140×
                Err(e) => return Err(e.into()),
2415
            };
2416639×
            stored += 1;
2417639×
            from_store += started.elapsed();
2418639×
            stack.extend(meta.deps.iter().copied());
2419639×
            out.push((h, meta));
2420
        }
2421177×
        if stored > 0 && crate::timing::enabled() {
24220×
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2423177×
        }
2424177×
        Ok(out)
2425177×
    }
2426
2427
    /// The log of a state already loaded, newest first.
2428
    /// The history of lines `first..=last` (1-based) of `path` in the
2429
    /// state `heads` make (spec §27): every change that inserted or
2430
    /// deleted one of their atoms, or an atom deleted from between them,
2431
    /// newest first. Exact, as atoms keep their identity across edits.
24326×
    pub fn line_history(
24336×
        &self,
24346×
        heads: &[ChangeHash],
24356×
        path: &str,
24366×
        first: usize,
24376×
        last: usize,
24386×
    ) -> Result<Vec<LogEntry>> {
24396×
        if first == 0 || last < first {
24401×
            return fail(format!(
2441
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2442
            ));
24435×
        }
24445×
        let mut state = self.load_state_history(heads)?;
24455×
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
24461×
            return fail(format!("{path} is not in that state"));
2447
        };
24484×
        self.load_graphs_of(&mut state, &[node])?;
24494×
        let live = state.live_lines(&node);
24504×
        if last > live.len() {
24511×
            return fail(format!(
2452
                "{path} has {} lines; asked for {first},{last}",
24531×
                live.len()
2454
            ));
24553×
        }
24563×
        let Some(g) = state.file(&node) else {
24570×
            return fail(format!("{path} is not a text file"));
2458
        };
24593×
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
24603×
        let touched = g.touching(&atoms);
24613×
        Ok(self
24623×
            .log_of(&state)
24633×
            .into_iter()
246413×
            .filter(|e| touched.contains(&e.hash))
24653×
            .collect())
24666×
    }
2467
24688×
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
24698×
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
24708×
        let mut entries: Vec<LogEntry> = state
24718×
            .changes()
24728×
            .map(|(h, meta)| LogEntry {
247331×
                hash: *h,
247431×
                change: meta.clone(),
2475
                is_working_copy: false,
247631×
                is_head: head_set.contains(h),
247731×
            })
24788×
            .collect();
247944×
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
24808×
        entries
24818×
    }
2482
2483
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2484
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2485
    /// (`resolve_change`).
248667×
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
248767×
        let view = self.view()?;
248867×
        if let Some(st) = view.bookmarks.get(spec) {
248939×
            return Ok(self.store.get_state(st)?.heads);
249028×
        }
249128×
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
24922×
            return Ok(self.store.get_state(&st)?.heads);
249326×
        }
249426×
        if let Some(heads) = self.tag_heads(spec)? {
24952×
            return Ok(heads);
249624×
        }
249724×
        Ok(vec![self.resolve_change(spec)?])
249867×
    }
2499
2500
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2501
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
250236×
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
250336×
        if spec == "@" {
25040×
            return Ok(self.working_copy()?.0);
250536×
        }
250636×
        let view = self.view()?;
250736×
        let named = match view.bookmarks.get(spec) {
25081×
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
250935×
            None => match remote_bookmark(&view, spec) {
25101×
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
251134×
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2512
            },
2513
        };
251436×
        if let Some((kind, heads)) = named {
25153×
            return match heads.len() {
25163×
                1 => Ok(heads[0]),
25170×
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2518
            };
251933×
        }
252033×
        if spec.is_empty() || spec == "#" {
25210×
            return fail("empty change specifier");
252233×
        }
252333×
        let entries = self.log()?;
2524
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2525
        // cannot be a ChangeId, which has 32 (oxygen#103).
252633×
        let full_hash =
2527128×
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
252833×
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
252927×
            entries
253027×
                .iter()
2531109×
                .filter(|e| e.hash.starts_with_hex(hp))
253227×
                .collect()
2533
        } else {
25346×
            entries
25356×
                .iter()
253621×
                .filter(|e| e.change.change_id.starts_with_hex(spec))
25376×
                .collect()
2538
        };
253933×
        match matches.len() {
254028×
            1 => Ok(matches[0].hash),
25415×
            0 => match self.resolve_in_remotes(spec)? {
25421×
                Some(h) => Ok(h),
25434×
                None => fail(format!("no change matches {spec:?}")),
2544
            },
2545
            _ => {
25460×
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
25470×
                if ids.len() == 1 {
25480×
                    fail(format!(
2549
                        "change {spec} is divergent: {} variants",
25500×
                        matches.len()
2551
                    ))
2552
                } else {
25530×
                    fail(format!("{spec:?} is ambiguous"))
2554
                }
2555
            }
2556
        }
255736×
    }
2558
2559
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2560
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2561
    /// `None` when none matches, or more than one.
25625×
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
25635×
        let view = self.view()?;
25645×
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
25655×
        for bookmarks in view.remotes.values() {
25663×
            for st in bookmarks.values() {
25673×
                let heads = self.store.get_state(st)?.heads;
25687×
                for e in self.log_state(&heads)? {
25697×
                    let hit = match spec.strip_prefix('#') {
25702×
                        Some(hp) => e.hash.starts_with_hex(hp),
25715×
                        None => e.change.change_id.starts_with_hex(spec),
2572
                    };
25737×
                    if hit {
25741×
                        found.insert(e.hash);
25756×
                    }
2576
                }
2577
            }
2578
        }
25795×
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
25805×
    }
2581
2582
    /// Where a change is when no local bookmark or the working copy holds
2583
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2584
    /// it is held locally, or nowhere.
25853×
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
25866×
        if self.log()?.iter().any(|e| e.hash == *hash) {
25872×
            return Ok(None);
25881×
        }
25891×
        let view = self.view()?;
25901×
        for (remote, bookmarks) in &view.remotes {
25911×
            for (name, st) in bookmarks {
25921×
                let heads = self.store.get_state(st)?.heads;
25931×
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
25941×
                    return Ok(Some(format!("{remote}/{name}")));
25950×
                }
2596
            }
2597
        }
25980×
        Ok(None)
25993×
    }
2600
2601
    /// Human-readable description of what a change does, with line content.
26023×
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
26033×
        let change = self.store.get_change(hash)?;
26043×
        let (base, base_snapshot) = self.change_base(&change)?;
26053×
        Ok(render_change(&change, &base, &base_snapshot))
26063×
    }
2607
2608
    /// The base state of `change` (its dependencies) and its rendering, as
2609
    /// much as showing the change needs: the whole tree, and the graphs and
2610
    /// contents of the files the change edits. Other text files are left
2611
    /// unrendered ([`Snapshot::unrendered`]).
26126×
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
26136×
        let base = self.load_state_history(&change.deps)?;
26146×
        self.render_base_for(change, base)
26156×
    }
2616
2617
    /// The base for showing `change` alone: the graphs of the files it
2618
    /// edits built, and the base's tree with no file rendered, which is
2619
    /// all [`render_change`](snapshot::render_change) and
2620
    /// [`diff_files_of`](snapshot::diff_files_of) read.
26212×
    pub(crate) fn tree_base_for(
26222×
        &self,
26232×
        change: &Change,
26242×
        mut base: State,
26252×
    ) -> Result<(State, Snapshot)> {
26262×
        let _t = crate::timing::phase("diff: the base's tree");
26272×
        let edited: std::collections::HashSet<NodeId> =
26288×
            change.edits.iter().map(|e| e.node()).collect();
26292×
        let nodes: Vec<NodeId> = edited.into_iter().collect();
26302×
        self.load_graphs_of(&mut base, &nodes)?;
26312×
        let snapshot = Snapshot {
26322×
            tree: base.tree().view(),
26332×
            files: BTreeMap::new(),
26342×
            unrendered: BTreeSet::new(),
26352×
        };
26362×
        Ok((base, snapshot))
26372×
    }
2638
2639
    /// [`Repo::change_base`] with the base already loaded (the working
2640
    /// copy's comes from the state index).
2641216×
    pub(crate) fn render_base_for(
2642216×
        &self,
2643216×
        change: &Change,
2644216×
        mut base: State,
2645216×
    ) -> Result<(State, Snapshot)> {
2646216×
        let _t = crate::timing::phase("diff: render the base");
2647216×
        let edited: std::collections::HashSet<NodeId> =
2648413×
            change.edits.iter().map(|e| e.node()).collect();
2649216×
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2650216×
        self.load_graphs_of(&mut base, &nodes)?;
2651216×
        let snapshot = {
2652216×
            let _t = crate::timing::phase("diff:   of which materialize");
2653216×
            base.materialize_nodes(&edited)
2654
        };
2655216×
        Ok((base, snapshot))
2656216×
    }
2657
}
2658
26590×
fn remove_any(path: &Path) -> std::io::Result<()> {
26600×
    let m = fs::symlink_metadata(path)?;
26610×
    if m.is_dir() {
26620×
        fs::remove_dir_all(path)
2663
    } else {
26640×
        fs::remove_file(path)
2665
    }
26660×
}
2667
26685×
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
26695×
    let mut perms = fs::metadata(path)?.permissions();
26705×
    perms.set_readonly(readonly);
26715×
    fs::set_permissions(path, perms)
26725×
}
2673
2674
#[cfg(unix)]
26755865×
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2676
    use std::os::unix::fs::PermissionsExt;
26775865×
    let mut perms = fs::metadata(path)?.permissions();
26785865×
    let mode = perms.mode();
26795865×
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
26805865×
    if want != mode {
26814×
        perms.set_mode(want);
26824×
        fs::set_permissions(path, perms)?;
26835861×
    }
26845865×
    Ok(())
26855865×
}
2686
#[cfg(not(unix))]
2687
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2688
    Ok(())
2689
}
2690
2691
#[cfg(unix)]
269216357×
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2693
    use std::os::unix::fs::PermissionsExt;
269416357×
    m.permissions().mode() & 0o111 != 0
269516357×
}
2696
#[cfg(not(unix))]
2697
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2698
    false
2699
}
2700
270112864×
fn op_ref(k: OpKey) -> OpRef {
270212864×
    OpRef {
270312864×
        change: k.0,
270412864×
        index: k.1,
270512864×
    }
270612864×
}
2707
27086011×
fn split_path(path: &str) -> (&str, &str) {
27096011×
    match path.rfind('/') {
27105057×
        Some(i) => (&path[..i], &path[i + 1..]),
2711954×
        None => ("", path),
2712
    }
27136011×
}
2714
2715
/// Whether `rel` is an attributes file (spec §7.6).
271667421×
fn is_attributes(rel: &str) -> bool {
271767421×
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
271867421×
}
2719
2720
/// The manifest entry for `rel` when its size and mtime match it outside
2721
/// the racy window.
272224155×
fn stat_cached<'m>(
272324155×
    rel: &str,
272424155×
    meta: &walk::Stat,
272524155×
    cache: Option<&'m prompt::Manifest>,
272624155×
) -> Option<&'m prompt::ManifestEntry> {
272724155×
    let m = cache?;
272819211×
    let e = m.entries.get(rel)?;
272917888×
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
273017888×
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
273124155×
}
2732
2733
/// Read one working-copy file, or serve it from the stat cache (spec
2734
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2735
/// an opaque file is not read at all (its stored blob stands in), and a
2736
/// text file the manifest recorded equal to a base graph whose key is
2737
/// `key`, the key the base has now, is not read either: equal keys mean
2738
/// equal renderings, so it still equals the base. Touches no repository
2739
/// state, so the walk runs it in parallel; the caller checks that a cached
2740
/// blob is still in the store.
274112093×
fn read_file_entry(
274212093×
    rel: &str,
274312093×
    path: &Path,
274412093×
    meta: &walk::Stat,
274512093×
    cache: Option<&prompt::Manifest>,
274612093×
    key: Option<[u8; 32]>,
274712093×
) -> Result<FsEntry> {
274812093×
    let exec = meta.exec;
274912093×
    let stat = Some((meta.size, meta.mtime_ns));
275012093×
    let mut e = match stat_cached(rel, meta, cache) {
27514247×
        Some(e) if e.blob.is_some() => FsEntry {
27521×
            blob: e.blob,
27531×
            content_hash: Some(e.hash),
27541×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27551×
        },
27564246×
        Some(e) if key.is_some() && e.graph == key => FsEntry {
27574241×
            content_hash: Some(e.hash),
27584241×
            unchanged: true,
27594241×
            graph_key: e.graph,
27604241×
            ..FsEntry::new(NodeKind::File, exec, vec![])
27614241×
        },
27625×
        Some(e) => FsEntry {
27635×
            content_hash: Some(e.hash),
27645×
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2765
        },
27667846×
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2767
    };
2768
    // The stat the manifest records: taken before the read, so a file that
2769
    // changes meanwhile is read again next time.
277012092×
    e.stat = stat;
277112092×
    Ok(e)
277212093×
}
2773
2774
/// Two maps side by side in key order: each key of either, with its value
2775
/// in each. Linear, with no lookups, for maps of a whole tree.
27762506×
pub(crate) fn join<'a, A, B>(
27772506×
    a: &'a BTreeMap<String, A>,
27782506×
    b: &'a BTreeMap<String, B>,
27792506×
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
27802506×
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
278135490×
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
27822506×
        (None, None) => None,
27832922×
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
27845791×
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
278524271×
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2786328×
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2787301×
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2788
            std::cmp::Ordering::Equal => {
278923642×
                let (k, va) = a.next()?;
279023642×
                let (_, vb) = b.next()?;
279123642×
                Some((k, Some(va), Some(vb)))
2792
            }
2793
        },
279435490×
    })
27952506×
}
2796
2797
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2798
/// lookups.
27991271×
pub(crate) fn missing_from<'a, A, B>(
28001271×
    a: &'a BTreeMap<String, A>,
28011271×
    b: &BTreeMap<String, B>,
28021271×
) -> Vec<(&'a String, &'a A)> {
28031271×
    let mut keys = b.keys().peekable();
28041271×
    a.iter()
28059101×
        .filter(|(k, _)| {
280617520×
            while keys.next_if(|kb| *kb < *k).is_some() {}
28079101×
            keys.peek() != Some(k)
28089101×
        })
28091271×
        .collect()
28101271×
}