OXYGENHUB
◆ v0.11.0 oxygen / crates / oxy-core / src / repo / mod.rs
117.0 KiB · Rust · last changed Cylinder C1, first part: artifacts as trees of the repository's chunks, oxy artifact pack/list/show/unpack/verify, kept by gc (refs #108) 7 days ago source blame history raw
98286406 Andy McCall ↶ 1
//! A repository on disk: the `.oxy` directory, one workspace, the operation
2
//! log, and the working-copy change (spec §12, §13.1).
3
//!
83e0677b Andy McCall ↶ 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
98286406 Andy McCall ↶ 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};
7ba155f2 Andy McCall ↶ 13
use crate::identity::{
14
    verify as verify_signature, Delegate, Domain, Identity, Scope, SecretKey, Signature,
15
};
98286406 Andy McCall ↶ 16
use crate::ids::{ChangeId, NodeId, WorkspaceId};
75167672 Andy McCall 17
use crate::objects::{
18
    Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp,
19
};
98286406 Andy McCall ↶ 20
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
75167672 Andy McCall 21
use crate::protocol::{
22
    open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef,
23
    SignedAttest, SignedPolicy,
24
};
98286406 Andy McCall ↶ 25
use crate::state::{FileContent, Snapshot, State};
26
use crate::store::{Store, StoreError};
75167672 Andy McCall 27
#[allow(unused_imports)]
28
use crate::subrepo::Pin;
98286406 Andy McCall ↶ 29
use crate::tree::OpKey;
30
use rand::RngCore;
cc7a0056 Andy McCall ↶ 31
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
98286406 Andy McCall ↶ 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;
d02e545d Andy McCall ↶ 40
/// Loose objects tolerated before a commit packs them (spec §13.4).
41
pub const AUTOPACK_THRESHOLD: usize = 4096;
98286406 Andy McCall ↶ 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),
e266b7d4 Andy McCall ↶ 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),
98286406 Andy McCall ↶ 59
}
60
61
pub type Result<T> = std::result::Result<T, RepoError>;
62
dd21fd82 Andy McCall ↶ 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
d069701a Andy McCall ↶ 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.
75
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
76
    let Some(url) = &config.storage_url else {
77
        return Ok(Store::open(oxy.join("objects"))?);
78
    };
79
    let options = crate::protocol::RemoteOptions {
80
        cache_dir: Some(oxy.join("cache")),
81
        ..Default::default()
82
    };
83
    let remote = crate::protocol::open_store(url, &options)
84
        .ok_or_else(|| {
85
            RepoError::Msg(format!(
86
                "storage.url {url}: this oxy cannot open that kind of store (dir://, or s3://, gs:// and az:// in builds with cloud stores)"
87
            ))
88
        })?
89
        .map_err(|e| RepoError::Msg(format!("open the repository's store {url}: {e}")))?;
90
    let cached = crate::strata::CachingStore::open(
91
        std::sync::Arc::from(remote),
92
        oxy.join("cache"),
93
        config.storage_cache,
94
    )
95
    .map_err(|e| RepoError::Msg(format!("open the cache for {url}: {e}")))?;
96
    Ok(Store::open_on(
97
        std::sync::Arc::new(cached),
98
        oxy.join("objects"),
99
    )?)
100
}
101
98286406 Andy McCall ↶ 102
fn fail<T>(s: impl Into<String>) -> Result<T> {
103
    Err(RepoError::Msg(s.into()))
104
}
105
7b9809e6 Andy McCall ↶ 106
mod bookmarks;
98286406 Andy McCall ↶ 107
mod checkout;
252e8cb2 Andy McCall ↶ 108
mod checkpoint;
98286406 Andy McCall ↶ 109
mod config;
3e5772cc Andy McCall ↶ 110
mod doctor;
387335ff Andy McCall ↶ 111
mod fsck;
ba160f60 Andy McCall ↶ 112
mod gc;
79ab8528 Andy McCall ↶ 113
mod git;
614541c3 Andy McCall ↶ 114
mod history;
6d3eefbc Andy McCall ↶ 115
mod hooks;
84b9e9ac Andy McCall ↶ 116
mod hosted;
75167672 Andy McCall 117
mod identity;
957fee30 Andy McCall ↶ 118
mod inspect;
c895bc52 Andy McCall ↶ 119
mod keyless;
98a1620a Andy McCall ↶ 120
mod ops;
83e0677b Andy McCall ↶ 121
mod policy;
135212de Andy McCall ↶ 122
mod prompt;
fc1a466a Andy McCall ↶ 123
mod receipts;
47ce8b8e Andy McCall ↶ 124
mod revset;
98286406 Andy McCall ↶ 125
mod snapshot;
9f9e72b9 Andy McCall ↶ 126
pub mod strata;
75167672 Andy McCall 127
mod subrepos;
98286406 Andy McCall ↶ 128
mod sync;
132b884b Andy McCall ↶ 129
mod tags;
98286406 Andy McCall ↶ 130
#[cfg(test)]
131
mod tests;
170bb436 Andy McCall ↶ 132
mod touched;
4b9d0677 Andy McCall ↶ 133
mod transparency;
76740263 Andy McCall ↶ 134
mod walk;
75167672 Andy McCall 135
mod workspace;
98286406 Andy McCall ↶ 136
14edbaaf Andy McCall ↶ 137
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
98286406 Andy McCall ↶ 138
pub use checkout::CheckoutReport;
b3c5a59a Andy McCall ↶ 139
pub use config::{parse_size, read_config_file, Config};
3e5772cc Andy McCall ↶ 140
pub use doctor::{Check, DoctorReport, Health};
387335ff Andy McCall ↶ 141
pub use fsck::{FsckReport, Problem, Severity};
ba160f60 Andy McCall ↶ 142
pub use gc::GcReport;
62794ecc Andy McCall ↶ 143
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
75167672 Andy McCall 144
pub use hooks::{json_array, json_str, HookOutcome};
84b9e9ac Andy McCall ↶ 145
pub use hosted::FileEdit;
64dc5197 Andy McCall ↶ 146
pub use identity::{create_user_identity, Rotation, SignatureStatus};
6a81dbab Andy McCall ↶ 147
pub use inspect::{BisectStep, BlameLine, Description};
c895bc52 Andy McCall ↶ 148
pub use keyless::home_key;
530a0fc6 Andy McCall ↶ 149
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
28fc23d7 Andy McCall ↶ 150
pub use policy::PolicyUpdate;
75167672 Andy McCall 151
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
fc1a466a Andy McCall ↶ 152
pub use receipts::ReceiptInfo;
47ce8b8e Andy McCall ↶ 153
pub use revset::{Revset, REVSET_BUDGET};
75167672 Andy McCall 154
pub use snapshot::{
155
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
9bd98cfb Andy McCall ↶ 156
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, KeptBoth,
157
    PathStatus, Selection, SnapshotResult,
75167672 Andy McCall 158
};
159
pub use subrepos::{SubrepoInfo, SubrepoSync};
cb8b8082 Andy McCall ↶ 160
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT};
132b884b Andy McCall ↶ 161
pub use tags::TagInfo;
e59512f2 Andy McCall ↶ 162
pub use transparency::LogAudit;
6caacfff Andy McCall ↶ 163
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
98286406 Andy McCall ↶ 164
54cd08a1 Andy McCall ↶ 165
/// The file name under which per-bookmark or per-tag data is kept: `/`
166
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
167
/// than a directory that would clash with it.
168
pub(crate) fn name_file(name: &str) -> String {
169
    name.replace('%', "%25").replace('/', "%2F")
170
}
171
172
/// The name a [`name_file`] file name stands for.
173
pub(crate) fn file_name_to_name(file: &str) -> String {
174
    file.replace("%2F", "/").replace("%25", "%")
175
}
176
98286406 Andy McCall ↶ 177
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
4dcb8c09 Andy McCall ↶ 178
    Ok(crate::durable::write_atomic(path, data)?)
98286406 Andy McCall ↶ 179
}
180
f9466021 Andy McCall ↶ 181
/// Replace a cache file: whole or not at all, but without waiting for the
182
/// disk. A cache checks its own bytes when read, so one a crash leaves
183
/// short or stale is rebuilt rather than trusted.
184
/// How many changes a state index may fall behind its working copy before
185
/// it is written again; until then each load replays them.
186
const INDEX_REPLAY_LIMIT: usize = 16;
acadb5ed Andy McCall ↶ 187
/// The changes whose encodings are kept for building graphs: a batch of
188
/// files often takes inline text from a few changes in turn.
189
const CHANGE_CACHE_COUNT: usize = 4;
190
const CHANGE_CACHE_BYTES: usize = 512 << 20;
638fb214 Andy McCall ↶ 191
/// How many state indexes a workspace keeps.
192
const STATE_INDEXES_KEPT: usize = 2;
f9466021 Andy McCall ↶ 193
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
194
195
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
196
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
197
    fs::write(&tmp, data)?;
198
    fs::rename(&tmp, path)?;
199
    Ok(())
200
}
201
98286406 Andy McCall ↶ 202
pub struct LogEntry {
203
    pub hash: ChangeHash,
2863456a Andy McCall ↶ 204
    /// Metadata from the state; the full change may be absent in a shallow repository.
205
    pub change: crate::state::ChangeMeta,
98286406 Andy McCall ↶ 206
    pub is_working_copy: bool,
207
    pub is_head: bool,
208
}
209
992467d3 Andy McCall ↶ 210
/// A text file's base graph key, by path, as a walk asks for it.
1966f5db Andy McCall ↶ 211
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
992467d3 Andy McCall ↶ 212
c3069537 Andy McCall ↶ 213
/// A file as found on disk or in an imported tree.
23ff1288 Andy McCall ↶ 214
#[derive(Clone)]
c3069537 Andy McCall ↶ 215
pub(crate) struct FsEntry {
216
    pub kind: NodeKind,
217
    pub exec: bool,
b7f102fc Andy McCall ↶ 218
    /// File content, or a symlink's target. Empty when `blob` is set.
40a40bb7 Andy McCall ↶ 219
    /// Shared, so a new file's insert holds it without a copy.
220
    pub content: std::sync::Arc<Vec<u8>>,
b7f102fc Andy McCall ↶ 221
    /// The stored blob of an opaque file whose size and mtime are unchanged
222
    /// since the last manifest (spec §12.3 stat cache); the content was not
223
    /// read.
224
    pub blob: Option<ObjectRef>,
225
    /// BLAKE3 of the content, carried over from the manifest when the stat
226
    /// is unchanged, so the manifest can be rewritten without rehashing.
1966f5db Andy McCall ↶ 227
    pub content_hash: Option<[u8; 32]>,
cc7a0056 Andy McCall ↶ 228
    /// A text file known equal to the base's rendering without reading it:
229
    /// its stat matches the manifest and the manifest recorded it equal to
230
    /// a base file graph with the same key (spec §12.3). `content` is empty.
231
    pub unchanged: bool,
232
    /// The base graph key this file equals, for the next manifest.
1966f5db Andy McCall ↶ 233
    pub graph_key: Option<[u8; 32]>,
0554aaa7 Andy McCall ↶ 234
    /// Size and mtime already known to be current (a checkout leaving the
235
    /// file as it was), so the manifest need not stat it again.
236
    pub stat: Option<(u64, u128)>,
98286406 Andy McCall ↶ 237
}
238
b7f102fc Andy McCall ↶ 239
impl FsEntry {
240
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
75167672 Andy McCall 241
        FsEntry {
242
            kind,
243
            exec,
40a40bb7 Andy McCall ↶ 244
            content: std::sync::Arc::new(content),
75167672 Andy McCall 245
            blob: None,
246
            content_hash: None,
cc7a0056 Andy McCall ↶ 247
            unchanged: false,
248
            graph_key: None,
0554aaa7 Andy McCall ↶ 249
            stat: None,
75167672 Andy McCall 250
        }
b7f102fc Andy McCall ↶ 251
    }
252
}
253
98286406 Andy McCall ↶ 254
pub struct Repo {
f53cbe7a Andy McCall ↶ 255
    /// The key a host accepts certified updates with (spec §14.7): when
256
    /// set, accepting a reference update signed by a short-lived key also
257
    /// records the host's acceptance and its time.
258
    pub(crate) acceptor: Option<std::sync::Arc<(Identity, crate::identity::SecretKey)>>,
c895bc52 Andy McCall ↶ 259
    /// With `author.signer = keyless`, the fresh key the hub last
260
    /// certified and when its certificate ends (spec §14.7): kept in memory
261
    /// only, for one command.
262
    pub(crate) keyless_key: std::cell::RefCell<Option<(KeyId, crate::identity::SecretKey, u64)>>,
4dee277c Andy McCall ↶ 263
    /// Oxygen-pinned subrepos skipped by the running Git export.
264
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
d0990c2b Andy McCall ↶ 265
    /// The manifest as last read, with the file identity it was read from,
266
    /// so one command parses it once (see `read_manifest`).
267
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
76740263 Andy McCall ↶ 268
    /// A listing of the working copy left by a failed clean check, for the
269
    /// snapshot that follows it to reuse; taken by the next walk and
270
    /// dropped whenever the manifest is written.
271
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
d4dbab97 Andy McCall ↶ 272
    /// The nested repositories the last walk left out, being neither
273
    /// registered nor tracked subrepos (oxygen#43).
274
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
b689779e Andy McCall ↶ 275
    /// New untracked files the last walk left out for their size, with
276
    /// their sizes (oxygen#98).
277
    pub(crate) skipped_large: std::cell::RefCell<Vec<(String, u64)>>,
98286406 Andy McCall ↶ 278
    root: PathBuf,
279
    oxy: PathBuf,
280
    store: Store,
281
    workspace: WorkspaceId,
e02bf0cd Andy McCall ↶ 282
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
283
    bare: bool,
98286406 Andy McCall ↶ 284
    keys_dir: PathBuf,
285
    user_config: PathBuf,
286
    pub config: Config,
c863c7a7 Andy McCall ↶ 287
    /// What the working copy's file system can represent (spec §7.7).
288
    platform: crate::portable::Platform,
acadb5ed Andy McCall ↶ 289
    /// The encodings of the changes last read for their inline inserts,
290
    /// oldest first.
291
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
98a1620a Andy McCall ↶ 292
    /// `--at-op`: read the repository as it was after this operation;
293
    /// recording an operation is refused.
294
    at_op: Option<ObjectRef>,
767ac6cd Andy McCall 295
    /// The operation head this handle reads (oxygenhub#249): read once, on
296
    /// first use, and moved only by this handle's own operations or by
297
    /// [`Repo::refresh`], so one command or request never mixes two heads.
298
    head_seen: std::cell::Cell<Option<ObjectRef>>,
1ec3f008 Andy McCall ↶ 299
    /// The directories (with their times) and nested repositories of the
300
    /// last walk, for the manifest written from it.
301
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
0389c3e8 Andy McCall ↶ 302
    /// The directories a manifest check listed, for its restamp only.
303
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
98286406 Andy McCall ↶ 304
}
305
1ec3f008 Andy McCall ↶ 306
/// A walk's directories with their times, and its nested repositories.
307
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
308
e02bf0cd Andy McCall ↶ 309
/// Marker file of a bare repository, inside `.oxy/`.
310
const BARE_MARKER: &str = "bare";
75167672 Andy McCall 311
/// Marker of a hosted repository that has no id yet: the first push binds
312
/// it to the pusher's id (spec §16.1).
313
const UNBOUND_MARKER: &str = "unbound";
e02bf0cd Andy McCall ↶ 314
98286406 Andy McCall ↶ 315
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
316
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
317
pub fn default_home() -> PathBuf {
318
    if let Ok(h) = std::env::var("OXY_HOME") {
319
        return PathBuf::from(h);
320
    }
321
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
322
        return PathBuf::from(x).join("oxy");
323
    }
abaa8d51 Andy McCall ↶ 324
    // Windows has no HOME as a rule: the roaming profile's application
325
    // data, as Windows programs keep theirs.
326
    #[cfg(windows)]
327
    if let Some(d) = std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")) {
328
        return PathBuf::from(d).join("oxy");
329
    }
98286406 Andy McCall ↶ 330
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
331
    PathBuf::from(home).join(".config").join("oxy")
332
}
333
334
pub fn default_keys_dir() -> PathBuf {
335
    default_home().join("keys")
336
}
337
338
pub fn default_user_config() -> PathBuf {
339
    default_home().join("config.toml")
340
}
341
342
/// Where `create_identity` records the author.
343
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
344
pub enum IdentityScope {
345
    /// The user file: every repository of this user signs with it.
346
    User,
347
    /// This repository only.
348
    Repo,
349
}
350
351
impl Repo {
352
    // ------------------------------------------------------------ lifecycle
353
354
    pub fn init(root: &Path) -> Result<Repo> {
355
        let mut id = [0u8; 16];
356
        rand::rngs::OsRng.fill_bytes(&mut id);
357
        Self::init_with_id(root, id)
358
    }
359
360
    /// Initialize a repository with a given repository ID (clones share the
361
    /// ID of their origin, spec §14.4).
362
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
d069701a Andy McCall ↶ 363
        Self::init_on(root, id, None)
364
    }
365
366
    /// A new repository with a fresh id, bare or not, on `storage` or in
367
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
368
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
369
        let mut id = [0u8; 16];
370
        rand::rngs::OsRng.fill_bytes(&mut id);
371
        if bare {
372
            Self::init_bare_on(root, id, storage)
373
        } else {
374
            Self::init_on(root, id, storage)
375
        }
376
    }
377
378
    /// Initialize a repository whose objects and operation head are kept
379
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
380
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
98286406 Andy McCall ↶ 381
        fs::create_dir_all(root)?;
544d0541 Andy McCall ↶ 382
        let root = crate::portable::canonical(root).unwrap_or_else(|_| root.to_path_buf());
98286406 Andy McCall ↶ 383
        let oxy = root.join(OXY_DIR);
384
        if oxy.exists() {
385
            return fail(format!("{} is already an oxy repository", root.display()));
386
        }
387
        fs::create_dir_all(oxy.join("ops"))?;
388
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
389
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
d069701a Andy McCall ↶ 390
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
391
        if let Some(url) = storage {
392
            config.set("storage.url", url)?;
393
        }
98286406 Andy McCall ↶ 394
        config.save(&oxy.join("config"))?;
395
        let workspace = WorkspaceId::random();
396
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
d069701a Andy McCall ↶ 397
        let store = open_objects(&oxy, &config)?;
75167672 Andy McCall 398
        let repo = Repo {
f53cbe7a Andy McCall ↶ 399
            acceptor: None,
c895bc52 Andy McCall ↶ 400
            keyless_key: Default::default(),
519c7c06 Andy McCall ↶ 401
            last_change: Default::default(),
98a1620a Andy McCall ↶ 402
            at_op: None,
767ac6cd Andy McCall 403
            head_seen: Default::default(),
1ec3f008 Andy McCall ↶ 404
            walked_dirs: Default::default(),
0389c3e8 Andy McCall ↶ 405
            listed_dirs: Default::default(),
75167672 Andy McCall 406
            git_export_skipped: Default::default(),
d0990c2b Andy McCall ↶ 407
            manifest_cache: Default::default(),
76740263 Andy McCall ↶ 408
            listing_cache: Default::default(),
d4dbab97 Andy McCall ↶ 409
            untracked_nested: Default::default(),
b689779e Andy McCall ↶ 410
            skipped_large: Default::default(),
75167672 Andy McCall 411
            root,
412
            oxy,
413
            store,
414
            workspace,
415
            bare: false,
416
            keys_dir: default_keys_dir(),
c863c7a7 Andy McCall ↶ 417
            platform: crate::portable::Platform::current(),
75167672 Andy McCall 418
            user_config: default_user_config(),
419
            config,
420
        };
4e88e774 Andy McCall ↶ 421
        repo.register_workspace(&workspace, &repo.root)?;
98286406 Andy McCall ↶ 422
423
        let wc = repo.new_working_copy(vec![], "");
424
        let wc_hash = repo.store.put_change(&wc)?;
425
        let mut view = View::default();
75167672 Andy McCall 426
        view.bookmarks.insert(
427
            repo.config.bookmark.clone(),
428
            repo.store.put_state(&StateObject::new(vec![]))?,
429
        );
98286406 Andy McCall ↶ 430
        view.workspaces.insert(workspace, wc_hash);
431
        repo.record_op(&[], "oxy init", view)?;
432
        Ok(repo)
433
    }
434
e02bf0cd Andy McCall ↶ 435
    /// Create a bare repository: an object store, operation log and
436
    /// references with no workspace and no working copy, for hosting
437
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
438
    pub fn init_bare(root: &Path) -> Result<Repo> {
439
        let mut id = [0u8; 16];
440
        rand::rngs::OsRng.fill_bytes(&mut id);
441
        Self::init_bare_with_id(root, id)
442
    }
443
444
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
d069701a Andy McCall ↶ 445
        Self::init_bare_on(root, id, None)
446
    }
447
448
    /// [`Repo::init_on`] for a bare repository.
449
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
e02bf0cd Andy McCall ↶ 450
        fs::create_dir_all(root)?;
544d0541 Andy McCall ↶ 451
        let root = crate::portable::canonical(root).unwrap_or_else(|_| root.to_path_buf());
e02bf0cd Andy McCall ↶ 452
        let oxy = root.join(OXY_DIR);
453
        if oxy.exists() {
454
            return fail(format!("{} is already an oxy repository", root.display()));
455
        }
456
        fs::create_dir_all(oxy.join("ops"))?;
457
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
458
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
459
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
d069701a Andy McCall ↶ 460
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
461
        if let Some(url) = storage {
462
            config.set("storage.url", url)?;
463
        }
e02bf0cd Andy McCall ↶ 464
        config.save(&oxy.join("config"))?;
d069701a Andy McCall ↶ 465
        let store = open_objects(&oxy, &config)?;
75167672 Andy McCall 466
        let repo = Repo {
f53cbe7a Andy McCall ↶ 467
            acceptor: None,
c895bc52 Andy McCall ↶ 468
            keyless_key: Default::default(),
519c7c06 Andy McCall ↶ 469
            last_change: Default::default(),
98a1620a Andy McCall ↶ 470
            at_op: None,
767ac6cd Andy McCall 471
            head_seen: Default::default(),
1ec3f008 Andy McCall ↶ 472
            walked_dirs: Default::default(),
0389c3e8 Andy McCall ↶ 473
            listed_dirs: Default::default(),
75167672 Andy McCall 474
            git_export_skipped: Default::default(),
d0990c2b Andy McCall ↶ 475
            manifest_cache: Default::default(),
76740263 Andy McCall ↶ 476
            listing_cache: Default::default(),
d4dbab97 Andy McCall ↶ 477
            untracked_nested: Default::default(),
b689779e Andy McCall ↶ 478
            skipped_large: Default::default(),
75167672 Andy McCall 479
            root,
480
            oxy,
481
            store,
482
            workspace: WorkspaceId::ZERO,
483
            bare: true,
484
            keys_dir: default_keys_dir(),
c863c7a7 Andy McCall ↶ 485
            platform: crate::portable::Platform::current(),
75167672 Andy McCall 486
            user_config: default_user_config(),
487
            config,
488
        };
e02bf0cd Andy McCall ↶ 489
        let mut view = View::default();
75167672 Andy McCall 490
        view.bookmarks.insert(
491
            repo.config.bookmark.clone(),
492
            repo.store.put_state(&StateObject::new(vec![]))?,
493
        );
e02bf0cd Andy McCall ↶ 494
        repo.record_op(&[], "oxy init --bare", view)?;
495
        Ok(repo)
496
    }
497
75167672 Andy McCall 498
    /// A bare repository with no id yet. Its `id()` is all zero until the
499
    /// first push binds it (`bind_id`), so an existing repository can be
500
    /// pushed to a freshly created hosted one and keep its identity.
501
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
502
        let repo = Self::init_bare_with_id(root, [0; 16])?;
503
        fs::remove_file(repo.oxy.join("id"))?;
504
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
505
        Ok(repo)
506
    }
507
508
    pub fn is_unbound(&self) -> bool {
509
        self.oxy.join(UNBOUND_MARKER).is_file()
510
    }
511
512
    /// Give an unbound repository its id.
513
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
514
        if !self.is_unbound() {
515
            return fail("this repository already has an id");
516
        }
517
        if id == [0; 16] {
518
            return fail("a repository id cannot be all zero");
519
        }
520
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
521
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
522
        Ok(())
523
    }
524
e02bf0cd Andy McCall ↶ 525
    /// Whether this repository has no working copy (`init_bare`).
526
    pub fn is_bare(&self) -> bool {
527
        self.bare
528
    }
529
98286406 Andy McCall ↶ 530
    /// Open the repository containing `start` (searching upwards).
531
    pub fn open(start: &Path) -> Result<Repo> {
544d0541 Andy McCall ↶ 532
        let start = crate::portable::canonical(start)?;
98286406 Andy McCall ↶ 533
        let mut dir: Option<&Path> = Some(&start);
534
        while let Some(d) = dir {
535
            let oxy = d.join(OXY_DIR);
4e88e774 Andy McCall ↶ 536
            if oxy.is_file() {
537
                // A secondary workspace (spec §12.2): the file points at the repository.
538
                let text = fs::read_to_string(&oxy)?;
539
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
540
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
541
                };
542
                let format = fs::read_to_string(shared.join("format"))?;
543
                if format != FORMAT_LINE {
544
                    return fail(format!("unsupported repository format: {}", format.trim()));
545
                }
546
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
d069701a Andy McCall ↶ 547
                let store = open_objects(&shared, &config)?;
75167672 Andy McCall 548
                let mut repo = Repo {
f53cbe7a Andy McCall ↶ 549
                    acceptor: None,
c895bc52 Andy McCall ↶ 550
                    keyless_key: Default::default(),
519c7c06 Andy McCall ↶ 551
                    last_change: Default::default(),
98a1620a Andy McCall ↶ 552
                    at_op: None,
767ac6cd Andy McCall 553
                    head_seen: Default::default(),
1ec3f008 Andy McCall ↶ 554
                    walked_dirs: Default::default(),
0389c3e8 Andy McCall ↶ 555
                    listed_dirs: Default::default(),
75167672 Andy McCall 556
                    git_export_skipped: Default::default(),
d0990c2b Andy McCall ↶ 557
                    manifest_cache: Default::default(),
76740263 Andy McCall ↶ 558
                    listing_cache: Default::default(),
d4dbab97 Andy McCall ↶ 559
                    untracked_nested: Default::default(),
b689779e Andy McCall ↶ 560
                    skipped_large: Default::default(),
75167672 Andy McCall 561
                    root: d.to_path_buf(),
562
                    oxy: shared,
563
                    store,
564
                    workspace,
565
                    bare: false,
566
                    keys_dir: default_keys_dir(),
c863c7a7 Andy McCall ↶ 567
                    platform: crate::portable::Platform::current(),
75167672 Andy McCall 568
                    user_config: default_user_config(),
569
                    config,
570
                };
7b9809e6 Andy McCall ↶ 571
                repo.apply_workspace_bookmark();
572
                return Ok(repo);
4e88e774 Andy McCall ↶ 573
            }
98286406 Andy McCall ↶ 574
            if oxy.is_dir() {
575
                let format = fs::read_to_string(oxy.join("format"))?;
576
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
e02bf0cd Andy McCall ↶ 577
                let bare = oxy.join(BARE_MARKER).is_file();
578
                let workspace = if bare {
579
                    WorkspaceId::ZERO
580
                } else {
75167672 Andy McCall 581
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
582
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
e02bf0cd Andy McCall ↶ 583
                };
d069701a Andy McCall ↶ 584
                let store = open_objects(&oxy, &config)?;
75167672 Andy McCall 585
                let mut repo = Repo {
f53cbe7a Andy McCall ↶ 586
                    acceptor: None,
c895bc52 Andy McCall ↶ 587
                    keyless_key: Default::default(),
519c7c06 Andy McCall ↶ 588
                    last_change: Default::default(),
98a1620a Andy McCall ↶ 589
                    at_op: None,
767ac6cd Andy McCall 590
                    head_seen: Default::default(),
1ec3f008 Andy McCall ↶ 591
                    walked_dirs: Default::default(),
0389c3e8 Andy McCall ↶ 592
                    listed_dirs: Default::default(),
75167672 Andy McCall 593
                    git_export_skipped: Default::default(),
d0990c2b Andy McCall ↶ 594
                    manifest_cache: Default::default(),
76740263 Andy McCall ↶ 595
                    listing_cache: Default::default(),
d4dbab97 Andy McCall ↶ 596
                    untracked_nested: Default::default(),
b689779e Andy McCall ↶ 597
                    skipped_large: Default::default(),
75167672 Andy McCall 598
                    root: d.to_path_buf(),
599
                    oxy,
600
                    store,
601
                    workspace,
602
                    bare,
603
                    keys_dir: default_keys_dir(),
c863c7a7 Andy McCall ↶ 604
                    platform: crate::portable::Platform::current(),
75167672 Andy McCall 605
                    user_config: default_user_config(),
606
                    config,
607
                };
e02bf0cd Andy McCall ↶ 608
                if !bare {
609
                    repo.apply_workspace_bookmark();
610
                }
98286406 Andy McCall ↶ 611
                if format == FORMAT1_LINE {
612
                    repo.migrate_format1()?;
613
                } else if format != FORMAT_LINE {
614
                    return fail(format!("unsupported repository format: {}", format.trim()));
615
                }
616
                return Ok(repo);
617
            }
618
            dir = d.parent();
619
        }
75167672 Andy McCall 620
        fail(format!(
3e5772cc Andy McCall ↶ 621
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
75167672 Andy McCall 622
            start.display()
623
        ))
98286406 Andy McCall ↶ 624
    }
625
626
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
627
    /// into format 2, where each bookmark names a `state` object.
628
    fn migrate_format1(&self) -> Result<()> {
dd21fd82 Andy McCall ↶ 629
        let (head, version) = self.read_head()?;
98286406 Andy McCall ↶ 630
        // Collect the chain root-first.
631
        let mut chain: Vec<Format1Op> = Vec::new();
632
        let mut cur = Some(head);
633
        while let Some(r) = cur {
634
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
635
            cur = op.parents.first().copied();
636
            chain.push(op);
637
        }
638
        chain.reverse();
639
        let mut new_parent: Option<ObjectRef> = None;
640
        for old in chain {
641
            let mut view = View::default();
642
            for (name, heads) in &old.view.bookmarks {
75167672 Andy McCall 643
                view.bookmarks.insert(
644
                    name.clone(),
645
                    self.store.put_state(&StateObject::new(heads.clone()))?,
646
                );
98286406 Andy McCall ↶ 647
            }
648
            view.workspaces = old.view.workspaces.clone();
75167672 Andy McCall 649
            let op = Op {
650
                parents: new_parent.into_iter().collect(),
651
                hlc: old.hlc,
652
                command: old.command,
653
                view,
530a0fc6 Andy McCall ↶ 654
                workspace: None,
655
                undoes: None,
75167672 Andy McCall 656
            };
98286406 Andy McCall ↶ 657
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
658
        }
dd21fd82 Andy McCall ↶ 659
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
660
            return fail("the operation log changed while it was rewritten; run the command again");
661
        }
98286406 Andy McCall ↶ 662
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
663
        Ok(())
d02e545d Andy McCall ↶ 664
    }
665
767ac6cd Andy McCall 666
    /// Pack automatically once many loose objects have accumulated, and
667
    /// delete what packing retired over [`crate::store::RETIRED_FOR`] ago
668
    /// (a store nobody runs `oxy gc` on would keep both copies forever).
d02e545d Andy McCall ↶ 669
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
767ac6cd Andy McCall 670
        self.store
671
            .expire_retired(crate::store::RETIRED_FOR, &mut |_| {})?;
d02e545d Andy McCall ↶ 672
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
673
            self.store.pack_loose()?;
135212de Andy McCall ↶ 674
            self.store.merge_packs()?;
d02e545d Andy McCall ↶ 675
        }
676
        Ok(())
677
    }
678
98286406 Andy McCall ↶ 679
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
680
    pub fn id(&self) -> Result<[u8; 16]> {
75167672 Andy McCall 681
        if self.is_unbound() {
682
            return Ok([0; 16]);
683
        }
98286406 Andy McCall ↶ 684
        let path = self.oxy.join("id");
685
        match fs::read_to_string(&path) {
75167672 Andy McCall 686
            Ok(h) => hex::decode(h.trim())
687
                .ok()
688
                .and_then(|v| v.try_into().ok())
689
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
98286406 Andy McCall ↶ 690
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
691
                let mut id = [0u8; 16];
692
                rand::rngs::OsRng.fill_bytes(&mut id);
693
                write_atomic(&path, hex::encode(id).as_bytes())?;
694
                Ok(id)
695
            }
696
            Err(e) => Err(e.into()),
697
        }
698
    }
699
700
    pub fn root(&self) -> &Path {
701
        &self.root
702
    }
642da263 Andy McCall ↶ 703
    /// The repository's `.oxy` directory (shared by its workspaces), for
704
    /// what other crates keep beside the store (Cylinder's artifacts).
705
    pub fn oxy_dir(&self) -> &Path {
706
        &self.oxy
707
    }
98286406 Andy McCall ↶ 708
    pub fn store(&self) -> &Store {
709
        &self.store
710
    }
711
    pub fn workspace(&self) -> WorkspaceId {
712
        self.workspace
713
    }
714
715
    /// Use a different user directory for keys and the user config file
716
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
c863c7a7 Andy McCall ↶ 717
    /// Act as if the working copy were on another platform's file system
718
    /// (tests of Windows and macOS behaviour on any host).
f53cbe7a Andy McCall ↶ 719
    /// Accept certified updates as `identity` (a host's key), recording when
720
    /// (spec §14.7).
721
    pub fn with_acceptor(mut self, identity: Identity, sk: crate::identity::SecretKey) -> Repo {
722
        self.acceptor = Some(std::sync::Arc::new((identity, sk)));
723
        self
724
    }
725
c863c7a7 Andy McCall ↶ 726
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
727
        self.platform = platform;
728
        self
729
    }
730
731
    pub fn platform(&self) -> crate::portable::Platform {
732
        self.platform
733
    }
734
98286406 Andy McCall ↶ 735
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
736
        let dir = dir.into();
737
        self.keys_dir = dir.join("keys");
738
        self.user_config = dir.join("config.toml");
739
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
740
            self.config = c;
741
        }
7b9809e6 Andy McCall ↶ 742
        self.apply_workspace_bookmark();
98286406 Andy McCall ↶ 743
        self
744
    }
745
7b9809e6 Andy McCall ↶ 746
    /// The workspace's current bookmark (spec §10.1) overrides the
747
    /// configured default when `oxy bookmark switch` has recorded one.
748
    fn apply_workspace_bookmark(&mut self) {
75167672 Andy McCall 749
        if let Ok(b) = fs::read_to_string(
750
            self.oxy
751
                .join("workspaces")
752
                .join(self.workspace.to_hex())
753
                .join("bookmark"),
754
        ) {
7b9809e6 Andy McCall ↶ 755
            let b = b.trim();
756
            if !b.is_empty() {
757
                self.config.bookmark = b.to_string();
758
            }
759
        }
760
    }
761
98286406 Andy McCall ↶ 762
    pub fn user_config_path(&self) -> &Path {
763
        &self.user_config
764
    }
765
766
    /// Set a key in the user file and refresh the effective configuration.
767
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
768
        Config::set_user(&self.user_config, key, value)?;
769
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
770
        Ok(())
771
    }
772
773
    pub fn save_config(&self) -> Result<()> {
774
        self.config.save(&self.oxy.join("config"))
775
    }
776
777
    fn author(&self) -> KeyId {
778
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
779
    }
780
}
781
782
impl Repo {
783
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
784
        let mut c = Change {
6f8aeb99 Andy McCall ↶ 785
            version: crate::objects::CHANGE_VERSION,
98286406 Andy McCall ↶ 786
            change_id: ChangeId::random(),
787
            deps,
788
            author: self.author(),
789
            hlc: Hlc::now(),
790
            message: message.into(),
791
            tree_ops: vec![],
792
            edits: vec![],
793
            kind: ChangeKind::WorkingCopy,
794
        };
795
        c.normalize();
796
        c
797
    }
798
799
    // ------------------------------------------------------------ operation log
800
801
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
98a1620a Andy McCall ↶ 802
        if let Some(r) = self.at_op {
803
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
804
        }
dd21fd82 Andy McCall ↶ 805
        let r = self.head_ref()?;
98286406 Andy McCall ↶ 806
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
807
        Ok((r, op))
808
    }
809
810
    pub fn view(&self) -> Result<View> {
811
        Ok(self.head_op()?.1.view)
812
    }
813
814
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
530a0fc6 Andy McCall ↶ 815
        self.record_op_undoing(parents, command, view, None)
816
    }
817
818
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
819
    fn record_op_undoing(
820
        &self,
821
        parents: &[ObjectRef],
822
        command: &str,
823
        view: View,
824
        undoes: Option<ObjectRef>,
825
    ) -> Result<ObjectRef> {
98a1620a Andy McCall ↶ 826
        if self.at_op.is_some() {
827
            return fail(
828
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
829
            );
830
        }
75167672 Andy McCall 831
        let op = Op {
832
            parents: parents.to_vec(),
833
            hlc: Hlc::now(),
834
            command: command.into(),
835
            view,
530a0fc6 Andy McCall ↶ 836
            workspace: Some(self.workspace),
837
            undoes,
75167672 Andy McCall 838
        };
98286406 Andy McCall ↶ 839
        let r = self.store.put(ObjectType::Op, &op.encode())?;
4dcb8c09 Andy McCall ↶ 840
        // The head is the commit point: everything it names must be on disk first.
236f35c0 Andy McCall ↶ 841
        let flushing = crate::timing::phase("op: flush the store");
4dcb8c09 Andy McCall ↶ 842
        self.store.flush()?;
236f35c0 Andy McCall ↶ 843
        drop(flushing);
dd21fd82 Andy McCall ↶ 844
        // Compare and swap (spec §12.1): when another process recorded an
845
        // operation since this one read the head, the two are merged
846
        // instead of one overwriting the other. On this disk the head moves
847
        // under a short lock; on any other store by its record's version,
848
        // and a record that moved meanwhile is read again and merged again.
849
        let _lock = if self.store.is_local() {
850
            Some(self.lock_ops()?)
851
        } else {
852
            None
853
        };
854
        let Some(parent) = parents.first() else {
19555025 Andy McCall ↶ 855
            // The first operation (init): there is no head yet.
dd21fd82 Andy McCall ↶ 856
            if !self.swap_head(&r, None)? {
857
                return fail(format!(
858
                    "{} already holds a repository's operation log",
859
                    self.store.backend().describe()
860
                ));
861
            }
19555025 Andy McCall ↶ 862
            return Ok(r);
863
        };
dd21fd82 Andy McCall ↶ 864
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
865
        for _ in 0..HEAD_TRIES {
866
            let (current, version) = self.read_head()?;
867
            let to = if current == *parent {
868
                r
869
            } else {
870
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
871
                let merged = Op {
872
                    parents: vec![current, r],
873
                    hlc: Hlc::now(),
874
                    command: format!("{command} (merged with a concurrent operation)"),
875
                    view: self.merge_views(&base, &op.view, &theirs)?,
530a0fc6 Andy McCall ↶ 876
                    workspace: Some(self.workspace),
877
                    undoes: None,
dd21fd82 Andy McCall ↶ 878
                };
879
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
880
                self.store.flush()?;
881
                m
882
            };
883
            if self.swap_head(&to, version.as_ref())? {
884
                return Ok(to);
885
            }
886
        }
887
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
19555025 Andy McCall ↶ 888
    }
889
890
    /// The operation head's lock, held only while the head pointer moves.
891
    fn lock_ops(&self) -> Result<FileLock> {
892
        fs::create_dir_all(self.oxy.join("ops"))?;
893
        FileLock::acquire(
894
            self.oxy.join("ops").join("lock"),
895
            "another oxy process holds the operation log",
896
        )
897
    }
898
767ac6cd Andy McCall 899
    /// The operation head this handle reads: the one it first read, or
900
    /// the last one it moved the head to (see [`Repo::refresh`]).
19555025 Andy McCall ↶ 901
    fn head_ref(&self) -> Result<ObjectRef> {
767ac6cd Andy McCall 902
        if let Some(r) = self.head_seen.get() {
903
            return Ok(r);
904
        }
905
        let r = self.read_head()?.0;
906
        self.head_seen.set(Some(r));
907
        Ok(r)
908
    }
909
910
    /// Read the operation head again: what another process or handle
911
    /// recorded since this handle first read it becomes visible. A handle
912
    /// keeps the head it first read for the rest of its life otherwise,
913
    /// so whatever it reads comes from one view (oxygenhub#249); a loop
914
    /// that waits for others' operations, or a step that must see what
915
    /// another handle just recorded, refreshes. Packs written since are
916
    /// picked up too.
917
    pub fn refresh(&self) -> Result<()> {
918
        self.forget_head();
919
        self.store.refresh()?;
920
        Ok(())
921
    }
922
923
    /// Read the operation head again on next use, as [`Repo::refresh`]
924
    /// does, leaving the packs as they are.
925
    pub(crate) fn forget_head(&self) {
926
        self.head_seen.set(None);
dd21fd82 Andy McCall ↶ 927
    }
928
929
    /// The operation head, and on a store its record's version for
930
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
931
    /// any other store (a bucket, or memory in tests) it is the store's
932
    /// [`HEAD_RECORD`] reference record (oxygen#68).
933
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
934
        if self.store.is_local() {
935
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
936
            let r = ObjectRef::from_hex(hex.trim())
937
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
938
            return Ok((r, None));
939
        }
940
        let backend = self.store.backend();
941
        match backend.read_ref(HEAD_RECORD) {
942
            Ok(Some((bytes, version))) => {
943
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
944
                    || {
945
                        RepoError::Msg(format!(
946
                            "the operation head in {} is corrupt",
947
                            backend.describe()
948
                        ))
949
                    },
950
                )?;
951
                Ok((r, Some(version)))
952
            }
953
            Ok(None) => fail(format!(
954
                "{} holds no operation log (no {HEAD_RECORD} record)",
955
                backend.describe()
956
            )),
957
            Err(e) => fail(format!("read the operation head: {e}")),
958
        }
19555025 Andy McCall ↶ 959
    }
960
dd21fd82 Andy McCall ↶ 961
    /// Move the operation head to `to` from the `expected` version
962
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
963
    /// disk the caller holds the operations lock and the head always
964
    /// moves; on a store it moves only if the record is unchanged, and
965
    /// `false` says another process moved it first.
966
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
967
        if self.store.is_local() {
968
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
767ac6cd Andy McCall 969
            self.head_seen.set(Some(*to));
dd21fd82 Andy McCall ↶ 970
            return Ok(true);
971
        }
972
        match self
973
            .store
974
            .backend()
975
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
976
        {
767ac6cd Andy McCall 977
            Ok(_) => {
978
                self.head_seen.set(Some(*to));
979
                Ok(true)
980
            }
dd21fd82 Andy McCall ↶ 981
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
982
            Err(e) => fail(format!("move the operation head: {e}")),
983
        }
984
    }
985
19555025 Andy McCall ↶ 986
    /// Three-way merge of two views that both started from `base` (spec
987
    /// §12.1). A reference only one side changed takes that side's value.
988
    /// When both changed it differently: a bookmark keeps both sides'
6caacfff Andy McCall ↶ 989
    /// heads (it may then have several), a change beats a deletion, a
990
    /// workspace changed by both is an error (only one of them matches the
991
    /// files on disk), and otherwise this process's value wins for remote
19555025 Andy McCall ↶ 992
    /// references and the policy, the first value for a tag (tags never
993
    /// move).
994
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
995
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
996
            b: &BTreeMap<K, V>,
997
            o: &BTreeMap<K, V>,
998
            t: &BTreeMap<K, V>,
999
            mut both: impl FnMut(&V, &V) -> Result<V>,
1000
        ) -> Result<BTreeMap<K, V>> {
1001
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
1002
            let mut out = BTreeMap::new();
1003
            for k in keys {
1004
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
1005
                let v = if ov == tv || tv == bv {
1006
                    ov.cloned()
1007
                } else if ov == bv {
1008
                    tv.cloned()
1009
                } else {
1010
                    match (ov, tv) {
1011
                        (Some(x), Some(y)) => Some(both(x, y)?),
1012
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
1013
                        (None, None) => None,
1014
                    }
1015
                };
1016
                if let Some(v) = v {
1017
                    out.insert(k.clone(), v);
1018
                }
1019
            }
1020
            Ok(out)
1021
        }
1022
        let bookmarks = pick(
1023
            &base.bookmarks,
1024
            &ours.bookmarks,
1025
            &theirs.bookmarks,
1026
            |x, y| {
1027
                let mut heads = self.store.get_state(x)?.heads;
1028
                heads.extend(self.store.get_state(y)?.heads);
1029
                let heads = self.load_state(&heads)?.maximal(&heads);
1030
                Ok(self.store.put_state(&StateObject::new(heads))?)
1031
            },
1032
        )?;
6caacfff Andy McCall ↶ 1033
        // Two operations that both replaced one workspace's working copy
1034
        // cannot both be right: the files on disk match only one of them.
1035
        // The working-copy lock keeps this from happening; should it happen
1036
        // anyway, this operation is not recorded.
19555025 Andy McCall ↶ 1037
        let workspaces = pick(
1038
            &base.workspaces,
1039
            &ours.workspaces,
1040
            &theirs.workspaces,
6caacfff Andy McCall ↶ 1041
            |_, _| {
1042
                fail(
1043
                    "another oxy process changed this working copy at the same time; \
1044
                     this command was not recorded: check `oxy status` and run it again",
1045
                )
1046
            },
19555025 Andy McCall ↶ 1047
        )?;
1048
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
1049
        let empty = BTreeMap::new();
1050
        let names: BTreeSet<&String> = base
1051
            .remotes
1052
            .keys()
1053
            .chain(ours.remotes.keys())
1054
            .chain(theirs.remotes.keys())
1055
            .collect();
1056
        let mut remotes = BTreeMap::new();
1057
        for n in names {
1058
            let m = pick(
1059
                base.remotes.get(n).unwrap_or(&empty),
1060
                ours.remotes.get(n).unwrap_or(&empty),
1061
                theirs.remotes.get(n).unwrap_or(&empty),
1062
                |x, _| Ok(*x),
1063
            )?;
1064
            if !m.is_empty() {
1065
                remotes.insert(n.clone(), m);
1066
            }
1067
        }
1068
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
1069
            ours.policy
1070
        } else if ours.policy == base.policy {
1071
            theirs.policy
1072
        } else {
1073
            ours.policy.or(theirs.policy)
1074
        };
1075
        self.store.flush()?;
1076
        Ok(View {
1077
            bookmarks,
1078
            workspaces,
1079
            remotes,
1080
            policy,
1081
            tags,
1082
        })
98286406 Andy McCall ↶ 1083
    }
1084
1085
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
1086
        let mut out = Vec::new();
1087
        let (mut r, mut op) = self.head_op()?;
1088
        loop {
1089
            let next = op.parents.first().copied();
1090
            out.push((r, op));
1091
            match next {
1092
                Some(p) => {
1093
                    r = p;
1094
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1095
                }
1096
                None => break,
1097
            }
1098
        }
1099
        Ok(out)
1100
    }
1101
530a0fc6 Andy McCall ↶ 1102
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1103
    ///
1104
    /// The command undone is the newest one this workspace ran: operations
1105
    /// that only recorded a working-copy snapshot are skipped (the files are
1106
    /// still on disk and the next snapshot recreates them), as are pushes
1107
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1108
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1109
    /// operations are never undone, and a command an earlier undo already
1110
    /// reverted is passed over, so undoing again goes further back.
1111
    ///
1112
    /// When nothing newer came from another workspace, the operation head
1113
    /// moves back to before the command. Otherwise the command is reverted
1114
    /// in place: every reference it changed goes back to its value before
1115
    /// it, recorded as a new operation that names it, and anything another
1116
    /// workspace changed since is kept. A reference both the command and a
1117
    /// later operation of another workspace changed is not guessed at: the
1118
    /// undo is refused, naming it.
1119
    ///
1120
    /// When the working copy is clean and was clean after the command's
1121
    /// predecessor, its files follow too, since nothing on disk can be
1122
    /// lost; otherwise they stay as they are (an undone commit's edits come
1123
    /// back as uncommitted work).
1124
    pub fn undo(&self) -> Result<Undone> {
6caacfff Andy McCall ↶ 1125
        let _wc = self.lock_working_copy()?;
98a1620a Andy McCall ↶ 1126
        let clean_now =
1127
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
530a0fc6 Andy McCall ↶ 1128
        let (head_ref, head) = self.head_op()?;
1129
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
1130
        let load = |r: &ObjectRef| -> Result<Op> {
1131
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
98a1620a Andy McCall ↶ 1132
        };
530a0fc6 Andy McCall ↶ 1133
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
1134
        let mut pending_checkout: Option<Op> = None;
1135
        let mut others = 0usize;
1136
        let (mut r, mut op) = (head_ref, head.clone());
1137
        let (target_ref, target, parent) = loop {
1138
            let parent = match op.parents.first() {
1139
                Some(p) => Some((*p, load(p)?)),
1140
                None => None,
1141
            };
1142
            if skip.contains(&r) {
1143
                pending_checkout = None;
1144
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
1145
                // A push cannot be taken back: undoing it would only make
1146
                // this repository forget what the remote holds.
1147
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
1148
                others += 1;
1149
            } else if let Some(u) = op.undoes {
1150
                skip.insert(u);
1151
                pending_checkout = None;
1152
            } else if op.command.ends_with(" (checkout)") {
1153
                pending_checkout = Some(op.clone());
1154
            } else {
1155
                match parent {
1156
                    Some((_, p)) => break (r, op, p),
1157
                    None => return fail("nothing to undo in this workspace"),
98a1620a Andy McCall ↶ 1158
                }
1159
            }
530a0fc6 Andy McCall ↶ 1160
            match parent {
1161
                Some((pr, p)) => (r, op) = (pr, p),
1162
                None => return fail("nothing to undo in this workspace"),
98a1620a Andy McCall ↶ 1163
            }
98286406 Andy McCall ↶ 1164
        };
530a0fc6 Andy McCall ↶ 1165
        let before = parent.view;
1166
        let after = pending_checkout
1167
            .map(|o| o.view)
1168
            .unwrap_or_else(|| target.view.clone());
1169
        let changes = self.view_changes(&before, &after)?;
1170
        let pushed = self.pushed_by(&before, &after, &head.view)?;
1171
        let restored_wc = before.workspaces.get(&self.workspace).copied();
1172
        if others == 0 {
1173
            // Only this workspace's operations since: move the head back.
dd21fd82 Andy McCall ↶ 1174
            let _lock = if self.store.is_local() {
1175
                Some(self.lock_ops()?)
1176
            } else {
1177
                None
1178
            };
530a0fc6 Andy McCall ↶ 1179
            let parent_ref = *target.parents.first().expect("the target has a parent");
dd21fd82 Andy McCall ↶ 1180
            let (now, version) = self.read_head()?;
530a0fc6 Andy McCall ↶ 1181
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
98a1620a Andy McCall ↶ 1182
                return fail("another oxy command ran while undoing; run undo again");
1183
            }
530a0fc6 Andy McCall ↶ 1184
        } else {
1185
            let view = self.revert_view(&head.view, &before, &after)?;
1186
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
19555025 Andy McCall ↶ 1187
        }
135212de Andy McCall ↶ 1188
        self.drop_manifest();
530a0fc6 Andy McCall ↶ 1189
        if let Some(then) = restored_wc {
1190
            if clean_now && Some(then) != wc_now {
b689779e Andy McCall ↶ 1191
                // Past `core.snapshot-retention` the working copy may be
1192
                // gone: the files then stay as they are.
1193
                let Ok(wc) = self.store.get_change(&then) else {
1194
                    return Ok(Undone {
1195
                        command: target.command,
1196
                        changes,
1197
                        others_kept: others,
1198
                        pushed,
1199
                    });
1200
                };
98a1620a Andy McCall ↶ 1201
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
1202
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1203
                    // The files differ from the restored working copy by
1204
                    // exactly what the undone command did: nothing else is
1205
                    // on disk, as the working copy was clean.
1206
                    self.checkout(&base, true, "oxy undo (checkout)")?;
1207
                }
1208
            }
530a0fc6 Andy McCall ↶ 1209
        }
1210
        Ok(Undone {
1211
            command: target.command,
1212
            changes,
1213
            others_kept: others,
1214
            pushed,
1215
        })
1216
    }
1217
1218
    /// Whether operation `op` was a push: it changed only what this
1219
    /// repository knows of remotes.
1220
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
1221
        let Some(p) = parent else {
1222
            return false;
1223
        };
1224
        op.command.starts_with("oxy push")
1225
            && op.view.bookmarks == p.view.bookmarks
1226
            && op.view.tags == p.view.tags
1227
            && op.view.workspaces == p.view.workspaces
1228
            && op.view.policy == p.view.policy
1229
    }
1230
1231
    /// Whether operation `op` (whose predecessor is `parent`) was this
1232
    /// workspace's. Operations record their workspace (oxygen#99); for older
1233
    /// ones it is read from the view: one that changed only other
1234
    /// workspaces' working copies was theirs, anything else counts as ours.
1235
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
1236
        if let Some(w) = op.workspace {
1237
            return w == self.workspace;
98a1620a Andy McCall ↶ 1238
        }
530a0fc6 Andy McCall ↶ 1239
        let Some(p) = parent else {
1240
            return true;
1241
        };
1242
        let ids: BTreeSet<&WorkspaceId> = op
1243
            .view
1244
            .workspaces
1245
            .keys()
1246
            .chain(p.view.workspaces.keys())
1247
            .collect();
1248
        let moved: Vec<&WorkspaceId> = ids
1249
            .into_iter()
1250
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
1251
            .collect();
1252
        moved.is_empty() || moved.contains(&&self.workspace)
1253
    }
1254
1255
    /// `current` with what changed from `before` to `after` put back, this
1256
    /// workspace's working copy included; refused when a later operation
1257
    /// changed one of the same references again.
1258
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
1259
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
1260
            cur: &mut BTreeMap<K, V>,
1261
            before: &BTreeMap<K, V>,
1262
            after: &BTreeMap<K, V>,
1263
            name: impl Fn(&K) -> String,
1264
            clashes: &mut Vec<String>,
1265
        ) {
1266
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
1267
            for k in keys {
1268
                let (b, a) = (before.get(k), after.get(k));
1269
                if a == b {
1270
                    continue;
1271
                }
1272
                if cur.get(k) != a {
1273
                    clashes.push(name(k));
1274
                    continue;
1275
                }
1276
                match b {
1277
                    Some(v) => cur.insert(k.clone(), v.clone()),
1278
                    None => cur.remove(k),
1279
                };
1280
            }
1281
        }
1282
        let mut out = current.clone();
1283
        let mut clashes = Vec::new();
1284
        // A bookmark another workspace moved since is put back head by
1285
        // head: the heads the command added go, the heads it replaced
1286
        // return, and the other workspace's heads stay. Only when a later
1287
        // change was built on one the command added is that not possible.
1288
        let names: BTreeSet<&String> = before
1289
            .bookmarks
1290
            .keys()
1291
            .chain(after.bookmarks.keys())
1292
            .collect();
1293
        for name in names {
1294
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
1295
            let cur = current.bookmarks.get(name);
1296
            if a == b {
1297
                continue;
1298
            }
1299
            if cur == a {
1300
                match b {
1301
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
1302
                    None => out.bookmarks.remove(name),
1303
                };
1304
                continue;
1305
            }
1306
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
1307
                clashes.push(format!("bookmark {name}"));
1308
                continue;
1309
            };
1310
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
1311
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
1312
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
1313
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
1314
            if !added.iter().all(|h| now.contains(h)) {
1315
                clashes.push(format!(
1316
                    "bookmark {name} (a later change builds on this one)"
1317
                ));
1318
                continue;
1319
            }
1320
            let mut heads: Vec<ChangeHash> = now
1321
                .iter()
1322
                .filter(|h| !added.contains(h))
1323
                .chain(was.difference(&became))
1324
                .copied()
1325
                .collect();
1326
            heads.sort();
1327
            heads.dedup();
1328
            let heads = self.load_state(&heads)?.maximal(&heads);
1329
            out.bookmarks.insert(
1330
                name.clone(),
1331
                self.store.put_state(&StateObject::new(heads))?,
1332
            );
1333
        }
1334
1335
        back(
1336
            &mut out.tags,
1337
            &before.tags,
1338
            &after.tags,
1339
            |k| format!("tag {k}"),
1340
            &mut clashes,
1341
        );
1342
        let mine = self.workspace;
1343
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
1344
            v.workspaces
1345
                .iter()
1346
                .filter(|(k, _)| **k != mine)
1347
                .map(|(k, v)| (*k, *v))
1348
                .collect()
1349
        };
1350
        let mut theirs = others(&out);
1351
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
1352
            Some(p) => format!("the workspace at {}", p.display()),
1353
            None => format!("workspace {}", id.to_hex()),
1354
        };
1355
        back(
1356
            &mut theirs,
1357
            &others(before),
1358
            &others(after),
1359
            workspace_name,
1360
            &mut clashes,
1361
        );
1362
        let empty = BTreeMap::new();
1363
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
1364
        for n in names {
1365
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
1366
            back(
1367
                &mut cur,
1368
                before.remotes.get(n).unwrap_or(&empty),
1369
                after.remotes.get(n).unwrap_or(&empty),
1370
                |k| format!("{n}/{k}"),
1371
                &mut clashes,
1372
            );
1373
            if cur.is_empty() {
1374
                out.remotes.remove(n);
1375
            } else {
1376
                out.remotes.insert(n.clone(), cur);
1377
            }
1378
        }
1379
        if before.policy != after.policy {
1380
            if out.policy == after.policy {
1381
                out.policy = before.policy;
1382
            } else {
1383
                clashes.push("the policy".into());
1384
            }
1385
        }
1386
        if !clashes.is_empty() {
1387
            return fail(format!(
1388
                "undo would also take back what another workspace has done since to {}; \
1389
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
1390
                clashes.join(", ")
1391
            ));
1392
        }
1393
        out.workspaces = theirs;
1394
        match before.workspaces.get(&mine) {
1395
            Some(wc) => out.workspaces.insert(mine, *wc),
1396
            None => out.workspaces.remove(&mine),
1397
        };
1398
        Ok(out)
1399
    }
1400
1401
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1402
    /// in `now` already holds: undoing them locally leaves them there.
1403
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
1404
        let mut out = Vec::new();
1405
        for (name, st) in &after.bookmarks {
1406
            if before.bookmarks.get(name) == Some(st) {
1407
                continue;
1408
            }
1409
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
1410
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
1411
                None => BTreeSet::new(),
1412
            };
1413
            let added: Vec<ChangeHash> = self
1414
                .store
1415
                .get_state(st)?
1416
                .heads
1417
                .into_iter()
1418
                .filter(|h| !had.contains(h))
1419
                .collect();
1420
            if added.is_empty() {
1421
                continue;
1422
            }
1423
            for (remote, bookmarks) in &now.remotes {
1424
                if let Some(rs) = bookmarks.get(name) {
1425
                    let theirs = self.store.get_state(rs)?.heads;
1426
                    if added.iter().any(|h| theirs.contains(h)) {
1427
                        out.push((name.clone(), remote.clone()));
1428
                    }
1429
                }
1430
            }
1431
        }
1432
        Ok(out)
98286406 Andy McCall ↶ 1433
    }
1434
1435
    /// The last operation that was not a snapshot.
1436
    pub fn last_command(&self) -> Result<Op> {
1437
        let (_, mut op) = self.head_op()?;
1438
        while op.is_snapshot() {
75167672 Andy McCall 1439
            let Some(parent) = op.parents.first() else {
1440
                break;
1441
            };
98286406 Andy McCall ↶ 1442
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1443
        }
1444
        Ok(op)
1445
    }
1446
1447
    // ------------------------------------------------------------ states
1448
252e8cb2 Andy McCall ↶ 1449
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
98286406 Andy McCall ↶ 1450
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
252e8cb2 Andy McCall ↶ 1451
        if let Some(st) = self.load_state_checkpointed(heads)? {
1452
            return Ok(st);
1453
        }
1454
        self.load_state_full(heads)
1455
    }
1456
e8d38e47 Andy McCall ↶ 1457
    /// The state of `heads` for its history (changes, tree, metadata) with
1458
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1459
    /// and friends. Build the graphs a command needs with
1460
    /// [`Repo::load_graphs_of`].
1461
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
1462
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
1463
            return Ok(st);
1464
        }
1465
        self.load_state_replayed(heads, State::new_history_only())
1466
    }
1467
1468
    /// Build these file graphs in a history-only state.
1469
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
5552e69c Andy McCall ↶ 1470
        state
1471
            .load_graphs(
1472
                nodes,
1473
                |refs| {
1474
                    self.read_blobs(refs).map_err(|e| {
1475
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
1476
                    })
1477
                },
1478
                |h| self.change_bytes(h),
1479
            )
1480
            .map_err(|e| self.index_damage(e))
cc7a0056 Andy McCall ↶ 1481
    }
1482
c2e1d090 Andy McCall 1483
    /// The tree of `state` as every reader sees it ([`State::view`]), with
1484
    /// the graphs built that it compares: same-path additions with
1485
    /// identical content are one entry, not a name conflict.
1486
    pub fn tree_view(&self, state: &mut State) -> Result<crate::tree::TreeView> {
1487
        let need = state.unify_candidates();
1488
        if !need.is_empty() {
1489
            self.load_graphs_of(state, &need)?;
1490
        }
1491
        Ok(state.view())
1492
    }
1493
5552e69c Andy McCall ↶ 1494
    /// An error building graphs, and when it is a state index found
1495
    /// damaged (a file's history that does not match its hash), the
1496
    /// workspace's state indexes removed: they are rebuilt from history by
1497
    /// the next command.
1498
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
1499
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
1500
            return e.into();
1501
        };
1502
        for path in self.state_indexes() {
1503
            let _ = fs::remove_file(path);
1504
        }
1505
        RepoError::Msg(format!(
1506
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
1507
        ))
1508
    }
1509
57d8dc05 Andy McCall ↶ 1510
    /// The graphs of `nodes` of a history-only state, built beside it (see
1511
    /// [`State::build_graphs_detached`]).
1512
    pub fn build_graphs_detached(
1513
        &self,
1514
        state: &State,
1515
        nodes: &[crate::ids::NodeId],
1516
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
1517
        Ok(state
1518
            .build_graphs_detached(
1519
                nodes,
1520
                |refs| {
1521
                    self.read_blobs(refs).map_err(|e| {
1522
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
1523
                    })
1524
                },
1525
                |h| self.change_bytes(h),
5552e69c Andy McCall ↶ 1526
            )
1527
            .map_err(|e| self.index_damage(e))?
57d8dc05 Andy McCall ↶ 1528
            .into_iter()
1529
            .collect())
1530
    }
1531
091fef80 Andy McCall ↶ 1532
    /// The contents of texts [`State::single_text`] gave: blobs read in
1533
    /// one go, inline ones from their changes.
11e2b98a Andy McCall ↶ 1534
    pub fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
091fef80 Andy McCall ↶ 1535
        use crate::objects::TextRef;
1536
        let refs: Vec<ObjectRef> = texts
1537
            .iter()
1538
            .filter_map(|t| match t {
1539
                TextRef::Blob(r, _, _) => Some(*r),
1540
                TextRef::Inline { .. } => None,
1541
            })
1542
            .collect();
1543
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1544
        let mut out = Vec::with_capacity(texts.len());
1545
        for t in texts {
1546
            let lines = match t {
1547
                TextRef::Blob(_, count, form) => {
1548
                    let content = blobs
1549
                        .next()
1550
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
1551
                    crate::objects::text_lines(&content, *count, *form)?
1552
                }
1553
                TextRef::Inline { change, start, end } => {
1554
                    let bytes = self.change_bytes(change)?;
1555
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
1556
                        RepoError::Msg("an inline insert lies outside its change".into())
1557
                    })?;
1558
                    crate::objects::inline_lines(range)?
1559
                }
1560
            };
1561
            out.push(lines.bytes().to_vec());
1562
        }
1563
        Ok(out)
1564
    }
1565
cc7a0056 Andy McCall ↶ 1566
    /// Build every graph a history-only state still lacks, making it full.
1567
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
5552e69c Andy McCall ↶ 1568
        state
1569
            .load_all_graphs(
1570
                |refs| {
1571
                    self.read_blobs(refs).map_err(|e| {
1572
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
1573
                    })
1574
                },
1575
                |h| self.change_bytes(h),
1576
            )
1577
            .map_err(|e| self.index_damage(e))
a4fad5b0 Andy McCall ↶ 1578
    }
1579
519c7c06 Andy McCall ↶ 1580
    /// A change's encoding, for building graphs of its inline inserts. The
acadb5ed Andy McCall ↶ 1581
    /// last few read are kept: a checkout building graphs a batch at a
1582
    /// time reads the same large changes for every batch, often in turn.
a4fad5b0 Andy McCall ↶ 1583
    fn change_bytes(
1584
        &self,
1585
        h: &ChangeHash,
519c7c06 Andy McCall ↶ 1586
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
acadb5ed Andy McCall ↶ 1587
        let mut cache = self.last_change.borrow_mut();
1588
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
1589
            let hit = cache.remove(i);
1590
            let b = hit.1.clone();
1591
            cache.push(hit);
1592
            return Ok(b);
519c7c06 Andy McCall ↶ 1593
        }
1594
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
a4fad5b0 Andy McCall ↶ 1595
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
519c7c06 Andy McCall ↶ 1596
        })?);
acadb5ed Andy McCall ↶ 1597
        cache.push((*h, b.clone()));
1598
        // The last few, within a memory budget; the newest always stays.
1599
        while cache.len() > CHANGE_CACHE_COUNT
1600
            || (cache.len() > 1
1601
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
1602
        {
1603
            cache.remove(0);
1604
        }
519c7c06 Andy McCall ↶ 1605
        Ok(b)
e8d38e47 Andy McCall ↶ 1606
    }
1607
252e8cb2 Andy McCall ↶ 1608
    /// Load the dependency closure of `heads` change by change.
1609
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
e8d38e47 Andy McCall ↶ 1610
        self.load_state_replayed(heads, State::new())
1611
    }
1612
1613
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
86e1824f Andy McCall ↶ 1614
        let history = state.is_history_only();
98286406 Andy McCall ↶ 1615
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1616
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
0bdc3f91 Andy McCall ↶ 1617
        {
1618
            let _t = crate::timing::phase("load: read and add changes");
d0d52107 Andy McCall ↶ 1619
            let (mut read, mut add, mut fetch) = (
1620
                std::time::Duration::ZERO,
1621
                std::time::Duration::ZERO,
1622
                std::time::Duration::ZERO,
1623
            );
0bdc3f91 Andy McCall ↶ 1624
            while let Some(h) = stack.pop() {
f9466021 Andy McCall ↶ 1625
                // A change the state holds brings its history with it.
1626
                if !seen.insert(h) || state.contains(&h) {
0bdc3f91 Andy McCall ↶ 1627
                    continue;
1628
                }
1629
                let t0 = std::time::Instant::now();
86e1824f Andy McCall ↶ 1630
                // A history-only state reads text only for the graphs it
1631
                // builds; either way the hash is the one asked for.
1632
                let (c, texts) = if history {
d0d52107 Andy McCall ↶ 1633
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
1634
                    fetch += t0.elapsed();
1635
                    Change::decode_skeleton(&bytes, h)
1636
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
86e1824f Andy McCall ↶ 1637
                } else {
1638
                    (self.store.get_change(&h)?, Vec::new())
1639
                };
0bdc3f91 Andy McCall ↶ 1640
                read += t0.elapsed();
1641
                stack.extend(c.deps.iter().copied());
1642
                let t1 = std::time::Instant::now();
86e1824f Andy McCall ↶ 1643
                state.add_known(h, c, texts);
0bdc3f91 Andy McCall ↶ 1644
                add += t1.elapsed();
98286406 Andy McCall ↶ 1645
            }
0bdc3f91 Andy McCall ↶ 1646
            crate::timing::record("load:   of which reading", read);
d0d52107 Andy McCall ↶ 1647
            crate::timing::record("load:     of which fetching", fetch);
0bdc3f91 Andy McCall ↶ 1648
            crate::timing::record("load:   of which applying", add);
98286406 Andy McCall ↶ 1649
        }
0bdc3f91 Andy McCall ↶ 1650
        let _t = crate::timing::phase("load: validate");
98286406 Andy McCall ↶ 1651
        state.validate()?;
1652
        Ok(state)
1653
    }
1654
1655
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
e02bf0cd Andy McCall ↶ 1656
        if self.bare {
1657
            return fail("this is a bare repository: it has no working copy");
1658
        }
98286406 Andy McCall ↶ 1659
        let view = self.view()?;
1660
        let h = *view
1661
            .workspaces
1662
            .get(&self.workspace)
1663
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
1664
        Ok((h, self.store.get_change(&h)?))
1665
    }
1666
1667
    /// Heads of a bookmark's state (spec §10.1).
1668
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
1669
        match view.bookmarks.get(bookmark) {
1670
            Some(st) => Ok(self.store.get_state(st)?.heads),
1671
            None => Ok(vec![]),
1672
        }
1673
    }
1674
1675
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1676
        self.heads_of(&self.view()?, &self.config.bookmark)
1677
    }
1678
1679
    // ------------------------------------------------------------ blobs
1680
1681
    fn blob_for(content: &[u8]) -> Blob {
6f8aeb99 Andy McCall ↶ 1682
        Blob::of(content)
98286406 Andy McCall ↶ 1683
    }
1684
1685
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1686
        Self::blob_for(content).hash()
1687
    }
1688
1689
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1690
        for c in crate::chunk::chunks(content) {
1691
            self.store.put_chunk(c)?;
1692
        }
75167672 Andy McCall 1693
        Ok(self
1694
            .store
1695
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
98286406 Andy McCall ↶ 1696
    }
1697
afaba5f1 Andy McCall ↶ 1698
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1699
    /// all their chunks, are read in parallel; a blob the store lacks goes
1700
    /// through [`Repo::read_blob`], which may fetch it lazily.
1701
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1702
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
4476cdbb Andy McCall ↶ 1703
        let t = crate::timing::phase("blobs: get_many blobs");
1704
        let got_all = self.store.get_many(refs);
1705
        drop(t);
1706
        for (r, got) in refs.iter().zip(got_all) {
afaba5f1 Andy McCall ↶ 1707
            blobs.push(match got {
1708
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
1709
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
1710
                Err(crate::store::StoreError::NotFound(_)) => None,
1711
                Err(e) => return Err(e.into()),
1712
            });
1713
        }
1714
        let chunk_refs: Vec<ObjectRef> = blobs
1715
            .iter()
1716
            .flatten()
1717
            .flat_map(|b| b.chunks.iter().copied())
1718
            .collect();
4476cdbb Andy McCall ↶ 1719
        let t = crate::timing::phase("blobs: get_many chunks");
afaba5f1 Andy McCall ↶ 1720
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
4476cdbb Andy McCall ↶ 1721
        drop(t);
1722
        if crate::timing::enabled() {
1723
            eprintln!(
1724
                "timing blobs: {} blobs, {} chunks, {} one by one",
1725
                refs.len(),
1726
                chunk_refs.len(),
1727
                blobs.iter().filter(|b| b.is_none()).count()
1728
            );
1729
        }
afaba5f1 Andy McCall ↶ 1730
        let mut out = Vec::with_capacity(refs.len());
1731
        for (r, blob) in refs.iter().zip(blobs) {
1732
            match blob {
1733
                None => out.push(self.read_blob(r)?),
1734
                Some(b) => {
1735
                    let mut content = Vec::with_capacity(b.length as usize);
1736
                    for c in &b.chunks {
1737
                        match chunks.next() {
1738
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
1739
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
1740
                            Some(Err(e)) => return Err(e.into()),
1741
                            None => return fail("chunk list ended early"),
1742
                        }
1743
                    }
1744
                    out.push(content);
1745
                }
1746
            }
1747
        }
1748
        Ok(out)
1749
    }
1750
b3c5a59a Andy McCall ↶ 1751
    /// Read a blob's content, fetching it from the remote that withheld it
1752
    /// when it is lazily absent (spec §13.5).
98286406 Andy McCall ↶ 1753
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
b3c5a59a Andy McCall ↶ 1754
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
1755
            self.fetch_lazy_blob(r)?;
1756
        }
98286406 Andy McCall ↶ 1757
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1758
        let mut out = Vec::with_capacity(blob.length as usize);
1759
        for c in &blob.chunks {
1760
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1761
        }
1762
        Ok(out)
1763
    }
1764
1765
    // ------------------------------------------------------------ working copy
1766
cdb5beba Andy McCall ↶ 1767
    /// Attributes from the `.oxyattributes` files in the working directory.
1768
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
f9466021 Andy McCall ↶ 1769
        // Nested repositories and ignored paths are left out, as in a walk.
1770
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
1771
        let files: Vec<(String, Vec<u8>)> = listing
1772
            .files
1773
            .into_iter()
1774
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
1775
            .collect();
75167672 Andy McCall 1776
        crate::attributes::Attributes::from_files(
1777
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1778
        )
cdb5beba Andy McCall ↶ 1779
    }
1780
d4dbab97 Andy McCall ↶ 1781
    /// Folders holding a repository of their own that the last look at the
1782
    /// working copy left out, not being subrepos (oxygen#43).
1783
    pub fn untracked_nested(&self) -> Vec<String> {
1784
        self.untracked_nested.borrow().clone()
b689779e Andy McCall ↶ 1785
    }
1786
1787
    /// New untracked files the last snapshot left out for being larger than
1788
    /// `snapshot.max-new-file-size`, with their sizes (oxygen#98).
1789
    pub fn skipped_large(&self) -> Vec<(String, u64)> {
1790
        self.skipped_large.borrow().clone()
d4dbab97 Andy McCall ↶ 1791
    }
1792
cdb5beba Andy McCall ↶ 1793
    /// Attributes from a materialized state's `.oxyattributes` files.
1794
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
75167672 Andy McCall 1795
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
1796
            match &f.content {
1797
                FileContent::Text { bytes, .. }
1798
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1799
                {
1800
                    Some((p.as_str(), bytes.as_slice()))
1801
                }
1802
                _ => None,
1803
            }
cdb5beba Andy McCall ↶ 1804
        }))
1805
    }
1806
1807
    /// Store a blob, raw when the path is `nocompress`.
1808
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1809
        if !nocompress {
1810
            return self.store_blob(content);
1811
        }
1812
        for c in crate::chunk::chunks(content) {
1813
            self.store.put_chunk_nocompress(c)?;
1814
        }
75167672 Andy McCall 1815
        Ok(self
1816
            .store
1817
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
cdb5beba Andy McCall ↶ 1818
    }
1819
f9575918 Andy McCall ↶ 1820
    /// This workspace's state index (oxygen#41): its working copy's base,
1821
    /// saved so a snapshot reads it rather than replaying history.
638fb214 Andy McCall ↶ 1822
    /// The state index of the state with these heads: this workspace keeps
1823
    /// the last few it used, named by their heads, so moving between two
1824
    /// states finds both.
1825
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
1826
        let mut heads = heads.to_vec();
1827
        heads.sort();
1828
        let mut h = blake3::Hasher::new();
1829
        for c in &heads {
1830
            h.update(&c.0);
1831
        }
1832
        self.oxy.join("index").join(format!(
1833
            "{}{}",
1834
            self.state_index_prefix(),
1835
            &h.finalize().to_hex()[..16]
1836
        ))
f9575918 Andy McCall ↶ 1837
    }
1838
638fb214 Andy McCall ↶ 1839
    fn state_index_prefix(&self) -> String {
1840
        format!("state-{}-", self.workspace.to_hex())
1841
    }
1842
1843
    /// This workspace's state indexes, newest first.
1844
    fn state_indexes(&self) -> Vec<PathBuf> {
1845
        let prefix = self.state_index_prefix();
1846
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
1847
            .into_iter()
1848
            .flatten()
1849
            .flatten()
1850
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
1851
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
1852
            .collect();
1853
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
1854
        found.into_iter().map(|(_, p)| p).collect()
1855
    }
1856
f9575918 Andy McCall ↶ 1857
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1858
    /// from this workspace's state index when it holds that history: every
1859
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1860
    /// is loaded from history and indexed for next time.
1861
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
638fb214 Andy McCall ↶ 1862
        if let Some((st, heads)) = self.read_state_index(deps) {
f9466021 Andy McCall ↶ 1863
            let mut have = st.maximal(deps);
1864
            have.sort();
1865
            if deps.iter().all(|d| st.contains(d)) && have == heads {
5552e69c Andy McCall ↶ 1866
                // Re-encoding reads every history: one found damaged is
1867
                // left to the build that reads it, which reports it.
f9466021 Andy McCall ↶ 1868
                #[cfg(test)]
5552e69c Andy McCall ↶ 1869
                if let Some(mine) = st.write_index() {
1870
                    assert_eq!(
1871
                        Some(mine),
1872
                        self.load_state_history(deps)?.write_index(),
1873
                        "a state index holds the state history gives"
1874
                    );
1875
                }
f9466021 Andy McCall ↶ 1876
                return Ok(st);
1877
            }
1878
            // An index a few changes behind (a commit, a pull since): add
1879
            // what it lacks, as long as all it holds is history of `deps`.
1880
            // Anything amiss (a change beyond a shallow boundary) takes the
1881
            // long way instead.
1882
            let (indexed, started) = (st.len(), std::time::Instant::now());
1883
            if let Ok(st) = self.load_state_replayed(deps, st) {
1884
                let mut all = deps.to_vec();
1885
                all.extend(heads.iter().copied());
1886
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
1887
                within.sort();
1888
                want.sort();
1889
                if within == want {
1890
                    #[cfg(test)]
1891
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1892
                    // Writing the index costs far more than replaying a
1893
                    // few small changes: it is rewritten once it falls
1894
                    // behind, or when replaying took long (large changes).
1895
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
1896
                        || started.elapsed() > INDEX_REPLAY_TIME
1897
                    {
1898
                        self.write_state_index(deps, &st);
1899
                    }
1900
                    return Ok(st);
1901
                }
1902
            }
f9575918 Andy McCall ↶ 1903
        }
1904
        let st = self.load_state_history(deps)?;
1905
        self.write_state_index(deps, &st);
1906
        Ok(st)
f9466021 Andy McCall ↶ 1907
    }
1908
1909
    /// Two history-only states hold the same changes and render the same
1910
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1911
    /// the checkpoint's graphs as the bases of its files' histories.
1912
    #[cfg(test)]
1913
    fn assert_same_state(&self, a: &State, b: &State) {
1914
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1915
        assert_eq!(ids(a), ids(b), "the same changes");
1916
        let files = |s: &State| {
1917
            let mut s = s.clone();
1918
            self.load_all_graphs(&mut s).unwrap();
1919
            s.materialize().files
1920
        };
1921
        assert_eq!(files(a), files(b), "the same files");
f9575918 Andy McCall ↶ 1922
    }
1923
4cce912a Andy McCall ↶ 1924
    /// The state index file: its heads, a hash of its changes block and one
1925
    /// of the rest, then the body [`State::write_index`] gives, whose first
1926
    /// block is the changes. Hashed in two parts so the log can read and
1927
    /// check the changes alone.
638fb214 Andy McCall ↶ 1928
    /// The index of `deps` if there is one, else the newest, which the
1929
    /// caller may bring up to date.
1930
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
5552e69c Andy McCall ↶ 1931
        use std::io::Read;
f9575918 Andy McCall ↶ 1932
        let _t = crate::timing::phase("load: state index");
638fb214 Andy McCall ↶ 1933
        let exact = self.state_index_path(deps);
5552e69c Andy McCall ↶ 1934
        let reading = crate::timing::phase("load:   of which reading the file");
1935
        let mut f = match fs::File::open(&exact) {
1936
            Ok(f) => {
638fb214 Andy McCall ↶ 1937
                // Used now: the newest, so the last to be dropped.
1938
                let _ = fs::File::options()
1939
                    .write(true)
1940
                    .open(&exact)
1941
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
5552e69c Andy McCall ↶ 1942
                f
638fb214 Andy McCall ↶ 1943
            }
5552e69c Andy McCall ↶ 1944
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
638fb214 Andy McCall ↶ 1945
        };
5552e69c Andy McCall ↶ 1946
        let total = f.metadata().ok()?.len();
1947
        let mut word = [0u8; 4];
1948
        f.read_exact(&mut word).ok()?;
1949
        let n = u32::from_le_bytes(word) as usize;
1950
        let mut head = vec![0u8; 32 * n + 64 + 8];
1951
        f.read_exact(&mut head).ok()?;
1952
        let heads: Vec<ChangeHash> = head[..32 * n]
1953
            .chunks_exact(32)
1954
            .map(|c| ObjectRef(c.try_into().unwrap()))
1955
            .collect();
1956
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
1957
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
1958
        let at = (4 + head.len()) as u64;
1959
        if at.checked_add(front_len).is_none_or(|end| end > total) {
1960
            return None;
f9575918 Andy McCall ↶ 1961
        }
5552e69c Andy McCall ↶ 1962
        // The front only: the files' histories after it are read, each
1963
        // checked by its own hash, when a command builds that file.
1964
        let mut front = vec![0u8; front_len as usize];
1965
        f.read_exact(&mut front).ok()?;
1966
        drop(reading);
1967
        let checking = crate::timing::phase("load:   of which checking the file");
1968
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
1969
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
79b5a90f Andy McCall ↶ 1970
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
5552e69c Andy McCall ↶ 1971
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
f9575918 Andy McCall ↶ 1972
            return None;
1973
        }
5552e69c Andy McCall ↶ 1974
        drop(checking);
1975
        let histories = crate::state::Histories::File(
1976
            std::sync::Arc::new(f),
1977
            at + front_len,
1978
            total - at - front_len,
1979
        );
1980
        Some((State::read_index_front(&front, histories).ok()?, heads))
4cce912a Andy McCall ↶ 1981
    }
1982
1983
    /// The changes of this workspace's state index (the closure of its
1984
    /// heads), read without the rest of the index.
bf0247ee Andy McCall ↶ 1985
    #[allow(clippy::type_complexity)]
4cce912a Andy McCall ↶ 1986
    pub(crate) fn read_state_index_changes(
1987
        &self,
74b4a3c6 Andy McCall ↶ 1988
    ) -> Option<(Vec<ChangeHash>, Vec<(ChangeHash, crate::state::ChangeMeta)>)> {
4cce912a Andy McCall ↶ 1989
        use std::io::Read;
1990
        let _t = crate::timing::phase("load: state index changes");
638fb214 Andy McCall ↶ 1991
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
4cce912a Andy McCall ↶ 1992
        let mut word = [0u8; 4];
1993
        f.read_exact(&mut word).ok()?;
1994
        let n = u32::from_le_bytes(word) as usize;
5552e69c Andy McCall ↶ 1995
        // Heads, the two sums, the front's length, then the changes block.
1996
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
4cce912a Andy McCall ↶ 1997
        f.read_exact(&mut head).ok()?;
bf0247ee Andy McCall ↶ 1998
        let heads: Vec<ChangeHash> = head[..32 * n]
1999
            .chunks_exact(32)
2000
            .map(|c| ObjectRef(c.try_into().unwrap()))
2001
            .collect();
4cce912a Andy McCall ↶ 2002
        let sum = &head[32 * n..32 * n + 32];
5552e69c Andy McCall ↶ 2003
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
4cce912a Andy McCall ↶ 2004
        let mut changes = vec![0u8; 4 + len];
5552e69c Andy McCall ↶ 2005
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
4cce912a Andy McCall ↶ 2006
        f.read_exact(&mut changes[4..]).ok()?;
79b5a90f Andy McCall ↶ 2007
        let checking = crate::timing::phase("load:   of which checking");
2008
        let mut h = blake3::Hasher::new();
2009
        h.update_rayon(&changes);
2010
        if h.finalize().as_bytes() != sum {
4cce912a Andy McCall ↶ 2011
            return None;
2012
        }
79b5a90f Andy McCall ↶ 2013
        drop(checking);
2014
        let _decoding = crate::timing::phase("load:   of which decoding");
74b4a3c6 Andy McCall ↶ 2015
        Some((heads, State::read_index_changes_listed(&changes[4..]).ok()?))
f9575918 Andy McCall ↶ 2016
    }
2017
2018
    /// Save `st`, the history-only state of `deps`, as this workspace's
2019
    /// state index; quietly nothing when it cannot be (it is only a cache).
2020
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
2021
        let _t = crate::timing::phase("write: state index");
f9466021 Andy McCall ↶ 2022
        let encoding = crate::timing::phase("write:   of which encoding");
f9575918 Andy McCall ↶ 2023
        let Some(body) = st.write_index() else {
2024
            return;
2025
        };
f9466021 Andy McCall ↶ 2026
        drop(encoding);
3f1b8fe2 Andy McCall ↶ 2027
        #[cfg(test)]
2028
        assert_eq!(
2029
            State::read_index(&body).ok().and_then(|s| s.write_index()),
2030
            Some(body.clone()),
2031
            "a state index reads back as written"
2032
        );
f9575918 Andy McCall ↶ 2033
        let mut heads = st.maximal(deps);
2034
        heads.sort();
2035
        let mut w = crate::flat::Writer::default();
2036
        w.count(heads.len());
2037
        for h in &heads {
2038
            w.object(h);
2039
        }
5552e69c Andy McCall ↶ 2040
        // The body is the front's length, the front, then the files'
2041
        // histories, which carry their own hashes: the sums cover the
2042
        // front's changes block and the rest of the front.
2043
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
2044
        let front = &body[8..8 + front_len];
2045
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
2046
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
2047
        w.fixed(&sum(&front[..split]));
2048
        w.fixed(&sum(&front[split..]));
f9575918 Andy McCall ↶ 2049
        w.fixed(&body);
638fb214 Andy McCall ↶ 2050
        let path = self.state_index_path(&heads);
f9466021 Andy McCall ↶ 2051
        let _ = fs::create_dir_all(self.oxy.join("index"));
2052
        let _ = write_cache(&path, &w.0);
638fb214 Andy McCall ↶ 2053
        // The last two used: the index of a state moved away from stays for
2054
        // a move back. Older ones (and the unnamed one of before) go.
2055
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
2056
            let _ = fs::remove_file(old);
2057
        }
2058
        let _ = fs::remove_file(
2059
            self.oxy
2060
                .join("index")
2061
                .join(format!("state-{}", self.workspace.to_hex())),
2062
        );
f9575918 Andy McCall ↶ 2063
    }
2064
cdb5beba Andy McCall ↶ 2065
    fn locks_dir(&self) -> PathBuf {
2066
        self.oxy.join("locks")
2067
    }
2068
2069
    /// Whether `path` is locked locally for editing (spec §18, advisory).
2070
    pub fn is_locked(&self, path: &str) -> bool {
2071
        self.locks_dir().join(path.replace('/', "%2F")).exists()
2072
    }
2073
2074
    /// Take the advisory local lock on a `lockable` file and make it writable.
2075
    pub fn lock_path(&self, path: &str) -> Result<()> {
2076
        let attrs = self.disk_attributes();
2077
        if !attrs.lookup(path).lockable {
2078
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
2079
        }
2080
        fs::create_dir_all(self.locks_dir())?;
75167672 Andy McCall 2081
        write_atomic(
2082
            &self.locks_dir().join(path.replace('/', "%2F")),
2083
            std::process::id().to_string().as_bytes(),
2084
        )?;
cdb5beba Andy McCall ↶ 2085
        set_readonly(&self.root.join(path), false)?;
2086
        Ok(())
2087
    }
2088
2089
    /// Release the local lock and make the file read-only again.
2090
    pub fn unlock_path(&self, path: &str) -> Result<()> {
2091
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
2092
        if self.root.join(path).exists() {
2093
            set_readonly(&self.root.join(path), true)?;
2094
        }
2095
        Ok(())
2096
    }
2097
7421309f Andy McCall ↶ 2098
    /// Whether a repository path is inside the sparse filter (spec §17).
2099
    pub fn in_scope(&self, path: &str) -> bool {
75167672 Andy McCall 2100
        self.config.sparse_paths.is_empty()
2101
            || self
2102
                .config
2103
                .sparse_paths
2104
                .iter()
2105
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
7421309f Andy McCall ↶ 2106
    }
2107
98286406 Andy McCall ↶ 2108
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
696bbf29 Andy McCall ↶ 2109
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
4dee277c Andy McCall ↶ 2110
    }
2111
b7f102fc Andy McCall ↶ 2112
    /// Walk the working copy; with a manifest, a file whose size and mtime
cc7a0056 Andy McCall ↶ 2113
    /// match it is not read: an opaque file yields its known blob, and a
2114
    /// text file whose recorded graph key equals its base graph's key in
2115
    /// `keys` (path → key) is marked unchanged; other text files are read
2116
    /// but keep their known hash. Files modified within two seconds of the
2117
    /// manifest are never trusted (a racy stat).
2118
    ///
2119
    /// `.oxyattributes` files are always read, since their content is
2120
    /// needed; and when any of them is not known unchanged (added, removed,
2121
    /// edited, or changed in the base), no text file is taken as unchanged,
2122
    /// because attributes decide how a file compares with the base.
9ac1fbe2 Andy McCall ↶ 2123
    ///
2124
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
2125
    /// (the base state's files) that exists on disk is included even when
2126
    /// an ignore rule matches it, as in Git.
75167672 Andy McCall 2127
    fn walk_working_copy_with(
2128
        &self,
2129
        cache: Option<&prompt::Manifest>,
2130
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
992467d3 Andy McCall ↶ 2131
        keys: Option<&KeyOf>,
75167672 Andy McCall 2132
    ) -> Result<BTreeMap<String, FsEntry>> {
36e51aa8 Andy McCall ↶ 2133
        let mut out: BTreeMap<String, FsEntry>;
76740263 Andy McCall ↶ 2134
        let sparse = &self.config.sparse_paths;
8b276e01 Andy McCall ↶ 2135
        let in_scope = |p: &str| {
2136
            sparse.is_empty()
2137
                || sparse
2138
                    .iter()
2139
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
2140
        };
76740263 Andy McCall ↶ 2141
        let walk_phase = crate::timing::phase("walk:   of which listing");
2142
        let walk::Listing {
2143
            files,
2144
            symlinks,
2145
            nested,
1ec3f008 Andy McCall ↶ 2146
            dirs,
76740263 Andy McCall ↶ 2147
        } = match self.listing_cache.take() {
2148
            Some(l) => l,
d4dbab97 Andy McCall ↶ 2149
            // Ignore rules apply to untracked paths only, so the base's
2150
            // files are not matched against them (an added file is: a rule
2151
            // written after it was snapshotted leaves it out again).
2152
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
76740263 Andy McCall ↶ 2153
        };
b689779e Andy McCall ↶ 2154
        // A new file larger than the limit is left out and named, not taken
2155
        // in unseen (oxygen#98): a build's output or a downloaded image
2156
        // would otherwise be stored by the next status, kept by the
2157
        // operation log. Files tracked, or already in the working copy, stay.
2158
        let limit = self.config.max_new_file;
2159
        let mut skipped = Vec::new();
2160
        let files: Vec<_> = files
2161
            .into_iter()
2162
            .filter(|(rel, _, meta)| {
2163
                let new = !tracked.contains_key(rel)
2164
                    && !cache.is_some_and(|m| m.entries.contains_key(rel));
2165
                if limit > 0 && new && meta.size > limit {
2166
                    skipped.push((rel.clone(), meta.size));
2167
                    return false;
2168
                }
2169
                true
2170
            })
2171
            .collect();
2172
        *self.skipped_large.borrow_mut() = skipped;
cc7a0056 Andy McCall ↶ 2173
        let keys = keys.filter(|k| {
2174
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
2175
            let attrs_unchanged =
2176
                files
2177
                    .iter()
2178
                    .filter(|(r, _, _)| is_attributes(r))
2179
                    .all(|(rel, _, meta)| {
2180
                        stat_cached(rel, meta, cache)
992467d3 Andy McCall ↶ 2181
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
cc7a0056 Andy McCall ↶ 2182
                    });
2183
            let none_removed = tracked
2184
                .keys()
2185
                .filter(|r| is_attributes(r))
2186
                .all(|r| on_disk.contains(r.as_str()));
2187
            attrs_unchanged && none_removed
2188
        });
1ec3f008 Andy McCall ↶ 2189
        *self.walked_dirs.borrow_mut() =
2190
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
76740263 Andy McCall ↶ 2191
        drop(walk_phase);
2192
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
e7ddd552 Andy McCall ↶ 2193
        // Reading files is most of a walk's cost; do it in parallel.
2194
        {
2195
            use rayon::prelude::*;
36e51aa8 Andy McCall ↶ 2196
            let mut read: Vec<(String, FsEntry)> = files
e7ddd552 Andy McCall ↶ 2197
                .par_iter()
2198
                .map(|(rel, path, meta)| {
992467d3 Andy McCall ↶ 2199
                    // A key is worked out only for a file the manifest
2200
                    // knows with the same stat and a key of its own.
cc7a0056 Andy McCall ↶ 2201
                    let key = keys
2202
                        .filter(|_| !is_attributes(rel))
992467d3 Andy McCall ↶ 2203
                        .filter(|_| {
2204
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
2205
                        })
2206
                        .and_then(|k| k(rel));
1966f5db Andy McCall ↶ 2207
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
e7ddd552 Andy McCall ↶ 2208
                })
2209
                .collect::<Result<Vec<_>>>()?;
36e51aa8 Andy McCall ↶ 2210
            for (rel, e) in read.iter_mut() {
e7ddd552 Andy McCall ↶ 2211
                // A cached blob the store lost (gc, a partial clone): read the file after all.
2212
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
36e51aa8 Andy McCall ↶ 2213
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
e7ddd552 Andy McCall ↶ 2214
                    e.blob = None;
2215
                }
36e51aa8 Andy McCall ↶ 2216
            }
2217
            // The listing is in path order, so the map is built without
2218
            // searching.
2219
            out = read.into_iter().collect();
2220
            for (rel, target) in symlinks {
2221
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
98286406 Andy McCall ↶ 2222
            }
2223
        }
76740263 Andy McCall ↶ 2224
        drop(_read_phase);
2225
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
4dee277c Andy McCall ↶ 2226
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2227
        // already tracked as subrepo nodes, they contribute their pin;
2228
        // unregistered ones are left alone.
2229
        let modules = self.modules_on_disk();
b5e98094 Andy McCall ↶ 2230
        // A subrepo at the state its recorded pin names is unmodified,
2231
        // whatever bookmark it sits on (#147): the recorded pin stands.
2232
        let subrepo_entry = |rel: &str, pin: crate::subrepo::Pin| -> FsEntry {
2233
            if let Some((NodeKind::Subrepo, Some(b))) = tracked.get(rel) {
2234
                let recorded = self
2235
                    .read_blob(b)
2236
                    .ok()
2237
                    .and_then(|x| crate::subrepo::Pin::decode(&x).ok());
2238
                if recorded.is_some_and(|r| r.same_state(&pin)) {
2239
                    return FsEntry {
2240
                        blob: Some(*b),
2241
                        ..FsEntry::new(NodeKind::Subrepo, false, vec![])
2242
                    };
2243
                }
2244
            }
2245
            FsEntry::new(NodeKind::Subrepo, false, pin.encode())
2246
        };
64dc5197 Andy McCall ↶ 2247
        // A removal's marker is spent once the removal is recorded (no
2248
        // subrepo node is tracked there) or the path is registered again:
2249
        // dropped before it is read, or the change registering it again
2250
        // would leave it out (oxygen#152).
2251
        let mut removed = self.removed_subrepos();
2252
        removed.retain(|rel| {
2253
            let spent = tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2254
                || modules.entries.contains_key(rel);
2255
            if spent {
4dee277c Andy McCall ↶ 2256
                self.clear_removed_subrepo(rel);
2257
            }
64dc5197 Andy McCall ↶ 2258
            !spent
2259
        });
d4dbab97 Andy McCall ↶ 2260
        let mut untracked_nested = Vec::new();
76740263 Andy McCall ↶ 2261
        for dir in nested {
4dee277c Andy McCall ↶ 2262
            let rel = self.rel_path(&dir);
2263
            if !self.in_scope(&rel) || removed.contains(&rel) {
2264
                continue;
2265
            }
2266
            let registered = modules.entries.get(&rel);
75167672 Andy McCall 2267
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2268
            {
d4dbab97 Andy McCall ↶ 2269
                untracked_nested.push(rel);
4dee277c Andy McCall ↶ 2270
                continue;
2271
            }
2272
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
b5e98094 Andy McCall ↶ 2273
            let entry = subrepo_entry(&rel, pin);
2274
            out.insert(rel, entry);
4dee277c Andy McCall ↶ 2275
        }
d4dbab97 Andy McCall ↶ 2276
        untracked_nested.sort();
2277
        *self.untracked_nested.borrow_mut() = untracked_nested;
9ac1fbe2 Andy McCall ↶ 2278
        // Tracked paths the ignore rules hid.
f57bf670 Andy McCall ↶ 2279
        for (rel, (kind, blob)) in missing_from(tracked, &out) {
2280
            if !self.in_scope(rel) {
9ac1fbe2 Andy McCall ↶ 2281
                continue;
2282
            }
2283
            let path = self.root.join(rel);
4dee277c Andy McCall ↶ 2284
            if *kind == NodeKind::Subrepo {
2285
                if removed.contains(rel) {
2286
                    continue;
2287
                }
75167672 Andy McCall 2288
                let present =
2289
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
4dee277c Andy McCall ↶ 2290
                if present {
75167672 Andy McCall 2291
                    let pin = subrepos::read_pin(
2292
                        &path,
2293
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
2294
                    )?;
b5e98094 Andy McCall ↶ 2295
                    out.insert(rel.clone(), subrepo_entry(rel, pin));
4dee277c Andy McCall ↶ 2296
                } else if let Some(b) = blob {
2297
                    // Not cloned (or emptied): the pin stays as recorded, as a
2298
                    // Git gitlink does when its directory is absent.
75167672 Andy McCall 2299
                    out.insert(
2300
                        rel.clone(),
2301
                        FsEntry {
2302
                            blob: Some(*b),
cc7a0056 Andy McCall ↶ 2303
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
75167672 Andy McCall 2304
                        },
2305
                    );
4dee277c Andy McCall ↶ 2306
                }
2307
                continue;
2308
            }
75167672 Andy McCall 2309
            let Ok(meta) = fs::symlink_metadata(&path) else {
2310
                continue;
2311
            };
9ac1fbe2 Andy McCall ↶ 2312
            let ft = meta.file_type();
2313
            if ft.is_symlink() {
2314
                let target = fs::read_link(&path)?;
75167672 Andy McCall 2315
                out.insert(
2316
                    rel.clone(),
2317
                    FsEntry::new(
2318
                        NodeKind::Symlink,
2319
                        false,
2320
                        target.to_string_lossy().as_bytes().to_vec(),
2321
                    ),
2322
                );
9ac1fbe2 Andy McCall ↶ 2323
            } else if ft.is_file() {
e96a430c Andy McCall ↶ 2324
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
9ac1fbe2 Andy McCall ↶ 2325
                out.insert(rel.clone(), e);
2326
            }
2327
        }
98286406 Andy McCall ↶ 2328
        Ok(out)
2329
    }
9ac1fbe2 Andy McCall ↶ 2330
2331
    /// The entry for one regular file, read or served from the stat cache.
75167672 Andy McCall 2332
    fn file_entry(
2333
        &self,
2334
        rel: &str,
2335
        path: &Path,
e96a430c Andy McCall ↶ 2336
        meta: &walk::Stat,
75167672 Andy McCall 2337
        cache: Option<&prompt::Manifest>,
2338
    ) -> Result<FsEntry> {
696bbf29 Andy McCall ↶ 2339
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
e7ddd552 Andy McCall ↶ 2340
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
40a40bb7 Andy McCall ↶ 2341
            e.content = std::sync::Arc::new(fs::read(path)?);
e7ddd552 Andy McCall ↶ 2342
            e.blob = None;
2343
        }
2344
        Ok(e)
9ac1fbe2 Andy McCall ↶ 2345
    }
2346
4dee277c Andy McCall ↶ 2347
    /// The non-directory paths of a snapshot with their kinds, for the
2348
    /// walker's `tracked` set.
75167672 Andy McCall 2349
    pub(crate) fn tracked_kinds(
2350
        snapshot: &Snapshot,
2351
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
4dee277c Andy McCall ↶ 2352
        snapshot
2353
            .files
2354
            .iter()
2355
            .filter(|(_, f)| f.kind != NodeKind::Dir)
2356
            .map(|(p, f)| {
2357
                let blob = match &f.content {
2358
                    FileContent::Opaque { blobs } => blobs.first().copied(),
2359
                    _ => None,
2360
                };
2361
                (p.clone(), (f.kind, blob))
2362
            })
2363
            .collect()
2364
    }
2365
2366
    /// A path under the root as a `/`-separated relative string.
2367
    pub(crate) fn rel_path(&self, path: &Path) -> String {
75167672 Andy McCall 2368
        path.strip_prefix(&self.root)
2369
            .unwrap_or(path)
2370
            .components()
2371
            .map(|c| c.as_os_str().to_string_lossy().to_string())
2372
            .collect::<Vec<_>>()
2373
            .join("/")
9ac1fbe2 Andy McCall ↶ 2374
    }
98286406 Andy McCall ↶ 2375
}
2376
2377
impl Repo {
2378
    /// Changes reachable from the bookmark and the working copy, newest first.
2379
    pub fn log(&self) -> Result<Vec<LogEntry>> {
e02bf0cd Andy McCall ↶ 2380
        let heads = self.bookmark_heads()?;
2381
        if self.bare {
2382
            return self.log_state(&heads);
2383
        }
79b5a90f Andy McCall ↶ 2384
        let (wc_hash, wc) = self.working_copy()?;
e02bf0cd Andy McCall ↶ 2385
        let mut all = heads.clone();
2386
        all.push(wc_hash);
2387
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
252e8cb2 Andy McCall ↶ 2388
        let mut entries: Vec<LogEntry> = Vec::new();
4d6c9c1b Andy McCall ↶ 2389
        // A shallow clone knows changes beyond its boundary from a
2390
        // checkpoint's metadata only: its log comes from the state.
2391
        let metas = if self.is_shallow() {
2392
            self.load_state_history(&all)?
2393
                .changes()
2394
                .map(|(h, m)| (*h, m.clone()))
2395
                .collect()
2396
        } else {
79b5a90f Andy McCall ↶ 2397
            // The working copy's change is in hand, and is never in the
2398
            // state index: its metadata is not looked up again.
2399
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
2400
            below.extend(wc.deps.iter().copied());
2401
            let _t = crate::timing::phase("log: metadata");
2402
            let mut metas = self.metas_of(&below)?;
2403
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
74b4a3c6 Andy McCall ↶ 2404
                // First, where the log puts it, so the order may hold.
2405
                metas.insert(0, (wc_hash, crate::state::ChangeMeta::of(&wc)));
79b5a90f Andy McCall ↶ 2406
            }
2407
            metas
4d6c9c1b Andy McCall ↶ 2408
        };
c6e69e4b Andy McCall ↶ 2409
        entries.extend(metas.into_iter().map(|(h, meta)| LogEntry {
2410
            hash: h,
2411
            change: meta,
2412
            is_working_copy: h == wc_hash,
2413
            is_head: head_set.contains(&h),
2414
        }));
79b5a90f Andy McCall ↶ 2415
        let _sorting = crate::timing::phase("log: sort");
2416
        // The hash makes the order total, so an unstable sort gives the same.
74b4a3c6 Andy McCall ↶ 2417
        // From the state index the order already holds (oxygen#94).
2418
        let order = |a: &LogEntry, b: &LogEntry| {
75167672 Andy McCall 2419
            b.is_working_copy
2420
                .cmp(&a.is_working_copy)
74b4a3c6 Andy McCall ↶ 2421
                .then(crate::state::log_order(
2422
                    (&a.hash, &a.change.hlc),
2423
                    (&b.hash, &b.change.hlc),
2424
                ))
2425
        };
2426
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
2427
            entries.sort_unstable_by(order);
2428
        }
98286406 Andy McCall ↶ 2429
        Ok(entries)
2430
    }
2431
119bbf50 Andy McCall ↶ 2432
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2433
    /// count, for paginated views.
9d333fc9 Andy McCall ↶ 2434
    pub fn log_window(
2435
        &self,
2436
        heads: &[ChangeHash],
2437
        offset: usize,
2438
        limit: usize,
2439
    ) -> Result<(Vec<LogEntry>, usize)> {
119bbf50 Andy McCall ↶ 2440
        let all = self.log_state(heads)?;
2441
        let total = all.len();
2442
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
2443
    }
2444
e02bf0cd Andy McCall ↶ 2445
    /// The log of the state with these heads, newest first, with no working
2446
    /// copy involved (for hosted repositories and any explicit state).
2447
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
4d6c9c1b Andy McCall ↶ 2448
        // The log needs change metadata only: neither graphs nor the tree.
2449
        if self.is_shallow() {
2450
            return Ok(self.log_of(&self.load_state_history(heads)?));
2451
        }
2452
        let metas = self.metas_of(heads)?;
2453
        let depended: BTreeSet<ChangeHash> = metas
2454
            .iter()
2455
            .flat_map(|(_, m)| m.deps.iter().copied())
2456
            .collect();
2457
        let mut entries: Vec<LogEntry> = metas
2458
            .into_iter()
2459
            .map(|(h, meta)| LogEntry {
2460
                hash: h,
2461
                is_head: !depended.contains(&h),
2462
                change: meta,
2463
                is_working_copy: false,
2464
            })
2465
            .collect();
74b4a3c6 Andy McCall ↶ 2466
        let order = |a: &LogEntry, b: &LogEntry| {
2467
            crate::state::log_order((&a.hash, &a.change.hlc), (&b.hash, &b.change.hlc))
2468
        };
2469
        if !entries.is_sorted_by(|a, b| order(a, b).is_le()) {
2470
            entries.sort_unstable_by(order);
2471
        }
4d6c9c1b Andy McCall ↶ 2472
        Ok(entries)
2473
    }
2474
2475
    /// Every change of the state with these heads and its metadata, read
2476
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2477
    /// a shallow clone's boundary is left out.
2478
    pub fn metas_of(
2479
        &self,
2480
        heads: &[ChangeHash],
2481
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2482
        let boundary = self.boundary();
4cce912a Andy McCall ↶ 2483
        // The state index holds the metadata of its heads' closure: a
2484
        // change found there is not read from the store (a change object
2485
        // can be as large as the tree it adds).
bf0247ee Andy McCall ↶ 2486
        let read = self.read_state_index_changes();
2487
        // Every one of `heads` in the index, and every head of the index
2488
        // among them: their closure is the index's changes, all of them
2489
        // (it is closed), and no walk is needed to find it.
2490
        if let Some((index_heads, all)) = &read {
2491
            let asked: crate::fasthash::FastSet<&ChangeHash> = heads.iter().collect();
74b4a3c6 Andy McCall ↶ 2492
            let in_index = || {
2493
                let index_heads: crate::fasthash::FastSet<&ChangeHash> =
2494
                    index_heads.iter().collect();
2495
                // Usually the heads asked are the index's: no set of all.
2496
                heads.iter().all(|h| index_heads.contains(h)) || {
2497
                    let all: crate::fasthash::FastSet<&ChangeHash> =
2498
                        all.iter().map(|(h, _)| h).collect();
2499
                    heads.iter().all(|h| all.contains(h))
2500
                }
2501
            };
2502
            if index_heads.iter().all(|h| asked.contains(h)) && in_index() {
bf0247ee Andy McCall ↶ 2503
                let (_, all) = read.expect("matched above");
2504
                #[cfg(test)]
2505
                {
2506
                    // The walk the shortcut saves finds the same changes.
2507
                    let mut seen: HashSet<ChangeHash> = HashSet::new();
2508
                    let mut stack = heads.to_vec();
2509
                    while let Some(h) = stack.pop() {
2510
                        if seen.insert(h) {
2511
                            stack.extend(self.store.get_change_meta(&h)?.deps);
2512
                        }
2513
                    }
74b4a3c6 Andy McCall ↶ 2514
                    assert_eq!(seen, all.iter().map(|(h, _)| *h).collect::<HashSet<_>>());
bf0247ee Andy McCall ↶ 2515
                }
74b4a3c6 Andy McCall ↶ 2516
                return Ok(all);
bf0247ee Andy McCall ↶ 2517
            }
2518
        }
74b4a3c6 Andy McCall ↶ 2519
        let mut indexed: Option<crate::fasthash::FastMap<ChangeHash, crate::state::ChangeMeta>> =
2520
            read.map(|(_, all)| all.into_iter().collect());
79b5a90f Andy McCall ↶ 2521
        let _walk = crate::timing::phase("metadata: walk");
4cce912a Andy McCall ↶ 2522
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
79b5a90f Andy McCall ↶ 2523
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
4d6c9c1b Andy McCall ↶ 2524
        let mut stack: Vec<ChangeHash> = heads.to_vec();
79b5a90f Andy McCall ↶ 2525
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
4d6c9c1b Andy McCall ↶ 2526
        while let Some(h) = stack.pop() {
2527
            if !seen.insert(h) {
2528
                continue;
2529
            }
79b5a90f Andy McCall ↶ 2530
            // Taken out of the index's map, each once: not copied.
2531
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
4cce912a Andy McCall ↶ 2532
                #[cfg(test)]
2533
                assert_eq!(
74b4a3c6 Andy McCall ↶ 2534
                    meta,
4cce912a Andy McCall ↶ 2535
                    self.store.get_change_meta(&h)?,
2536
                    "the state index holds a change's metadata"
2537
                );
2538
                stack.extend(meta.deps.iter().copied());
79b5a90f Andy McCall ↶ 2539
                out.push((h, meta));
4cce912a Andy McCall ↶ 2540
                continue;
2541
            }
2542
            let started = std::time::Instant::now();
4d6c9c1b Andy McCall ↶ 2543
            let meta = match self.store.get_change_meta(&h) {
2544
                Ok(m) => m,
2545
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
2546
                Err(e) => return Err(e.into()),
2547
            };
4cce912a Andy McCall ↶ 2548
            stored += 1;
2549
            from_store += started.elapsed();
4d6c9c1b Andy McCall ↶ 2550
            stack.extend(meta.deps.iter().copied());
2551
            out.push((h, meta));
4cce912a Andy McCall ↶ 2552
        }
2553
        if stored > 0 && crate::timing::enabled() {
2554
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
4d6c9c1b Andy McCall ↶ 2555
        }
2556
        Ok(out)
bc489b6c Andy McCall ↶ 2557
    }
2558
2559
    /// The log of a state already loaded, newest first.
83d61e80 Andy McCall ↶ 2560
    /// The history of lines `first..=last` (1-based) of `path` in the
2561
    /// state `heads` make (spec §27): every change that inserted or
2562
    /// deleted one of their atoms, or an atom deleted from between them,
2563
    /// newest first. Exact, as atoms keep their identity across edits.
2564
    pub fn line_history(
2565
        &self,
2566
        heads: &[ChangeHash],
2567
        path: &str,
2568
        first: usize,
2569
        last: usize,
2570
    ) -> Result<Vec<LogEntry>> {
2571
        if first == 0 || last < first {
2572
            return fail(format!(
2573
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2574
            ));
2575
        }
2576
        let mut state = self.load_state_history(heads)?;
c2e1d090 Andy McCall 2577
        let Some(node) = self
2578
            .tree_view(&mut state)?
2579
            .entries
2580
            .get(path)
2581
            .map(|e| e.node)
2582
        else {
83d61e80 Andy McCall ↶ 2583
            return fail(format!("{path} is not in that state"));
2584
        };
2585
        self.load_graphs_of(&mut state, &[node])?;
2586
        let live = state.live_lines(&node);
2587
        if last > live.len() {
2588
            return fail(format!(
2589
                "{path} has {} lines; asked for {first},{last}",
2590
                live.len()
2591
            ));
2592
        }
2593
        let Some(g) = state.file(&node) else {
2594
            return fail(format!("{path} is not a text file"));
2595
        };
2596
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
2597
        let touched = g.touching(&atoms);
2598
        Ok(self
2599
            .log_of(&state)
2600
            .into_iter()
2601
            .filter(|e| touched.contains(&e.hash))
2602
            .collect())
2603
    }
2604
bc489b6c Andy McCall ↶ 2605
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
e02bf0cd Andy McCall ↶ 2606
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
2607
        let mut entries: Vec<LogEntry> = state
2608
            .changes()
75167672 Andy McCall 2609
            .map(|(h, meta)| LogEntry {
2610
                hash: *h,
2611
                change: meta.clone(),
2612
                is_working_copy: false,
2613
                is_head: head_set.contains(h),
2614
            })
e02bf0cd Andy McCall ↶ 2615
            .collect();
79b5a90f Andy McCall ↶ 2616
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
bc489b6c Andy McCall ↶ 2617
        entries
e02bf0cd Andy McCall ↶ 2618
    }
2619
14edbaaf Andy McCall ↶ 2620
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2621
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2622
    /// (`resolve_change`).
132b884b Andy McCall ↶ 2623
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
7b9809e6 Andy McCall ↶ 2624
        let view = self.view()?;
2625
        if let Some(st) = view.bookmarks.get(spec) {
2626
            return Ok(self.store.get_state(st)?.heads);
132b884b Andy McCall ↶ 2627
        }
14edbaaf Andy McCall ↶ 2628
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
2629
            return Ok(self.store.get_state(&st)?.heads);
2630
        }
132b884b Andy McCall ↶ 2631
        if let Some(heads) = self.tag_heads(spec)? {
2632
            return Ok(heads);
2633
        }
2634
        Ok(vec![self.resolve_change(spec)?])
2635
    }
2636
6a81dbab Andy McCall ↶ 2637
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
14edbaaf Andy McCall ↶ 2638
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
98286406 Andy McCall ↶ 2639
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
2640
        if spec == "@" {
2641
            return Ok(self.working_copy()?.0);
2642
        }
14edbaaf Andy McCall ↶ 2643
        let view = self.view()?;
2644
        let named = match view.bookmarks.get(spec) {
6a81dbab Andy McCall ↶ 2645
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
14edbaaf Andy McCall ↶ 2646
            None => match remote_bookmark(&view, spec) {
2647
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
2648
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2649
            },
6a81dbab Andy McCall ↶ 2650
        };
2651
        if let Some((kind, heads)) = named {
7b9809e6 Andy McCall ↶ 2652
            return match heads.len() {
2653
                1 => Ok(heads[0]),
6a81dbab Andy McCall ↶ 2654
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
7b9809e6 Andy McCall ↶ 2655
            };
2656
        }
98286406 Andy McCall ↶ 2657
        if spec.is_empty() || spec == "#" {
2658
            return fail("empty change specifier");
2659
        }
2660
        let entries = self.log()?;
aa4939e0 Andy McCall ↶ 2661
        // A full hash as `--json` prints it, without its `#`: 64 hex digits
2662
        // cannot be a ChangeId, which has 32 (oxygen#103).
2663
        let full_hash =
2664
            (spec.len() == 64 && spec.bytes().all(|b| b.is_ascii_hexdigit())).then_some(spec);
2665
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#').or(full_hash) {
75167672 Andy McCall 2666
            entries
2667
                .iter()
2668
                .filter(|e| e.hash.starts_with_hex(hp))
2669
                .collect()
98286406 Andy McCall ↶ 2670
        } else {
75167672 Andy McCall 2671
            entries
2672
                .iter()
2673
                .filter(|e| e.change.change_id.starts_with_hex(spec))
2674
                .collect()
98286406 Andy McCall ↶ 2675
        };
2676
        match matches.len() {
2677
            1 => Ok(matches[0].hash),
b35df36b Andy McCall ↶ 2678
            0 => match self.resolve_in_remotes(spec)? {
2679
                Some(h) => Ok(h),
2680
                None => fail(format!("no change matches {spec:?}")),
2681
            },
98286406 Andy McCall ↶ 2682
            _ => {
2683
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
2684
                if ids.len() == 1 {
75167672 Andy McCall 2685
                    fail(format!(
2686
                        "change {spec} is divergent: {} variants",
2687
                        matches.len()
2688
                    ))
98286406 Andy McCall ↶ 2689
                } else {
2690
                    fail(format!("{spec:?} is ambiguous"))
b35df36b Andy McCall ↶ 2691
                }
2692
            }
2693
        }
2694
    }
2695
2696
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2697
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2698
    /// `None` when none matches, or more than one.
2699
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
2700
        let view = self.view()?;
2701
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
2702
        for bookmarks in view.remotes.values() {
2703
            for st in bookmarks.values() {
2704
                let heads = self.store.get_state(st)?.heads;
2705
                for e in self.log_state(&heads)? {
2706
                    let hit = match spec.strip_prefix('#') {
2707
                        Some(hp) => e.hash.starts_with_hex(hp),
2708
                        None => e.change.change_id.starts_with_hex(spec),
2709
                    };
2710
                    if hit {
2711
                        found.insert(e.hash);
2712
                    }
2713
                }
2714
            }
2715
        }
2716
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
2717
    }
2718
2719
    /// Where a change is when no local bookmark or the working copy holds
2720
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2721
    /// it is held locally, or nowhere.
2722
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
2723
        if self.log()?.iter().any(|e| e.hash == *hash) {
2724
            return Ok(None);
2725
        }
2726
        let view = self.view()?;
2727
        for (remote, bookmarks) in &view.remotes {
2728
            for (name, st) in bookmarks {
2729
                let heads = self.store.get_state(st)?.heads;
2730
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
2731
                    return Ok(Some(format!("{remote}/{name}")));
98286406 Andy McCall ↶ 2732
                }
2733
            }
2734
        }
b35df36b Andy McCall ↶ 2735
        Ok(None)
98286406 Andy McCall ↶ 2736
    }
2737
2738
    /// Human-readable description of what a change does, with line content.
2739
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
2740
        let change = self.store.get_change(hash)?;
8ab265dc Andy McCall ↶ 2741
        let (base, base_snapshot) = self.change_base(&change)?;
98286406 Andy McCall ↶ 2742
        Ok(render_change(&change, &base, &base_snapshot))
8ab265dc Andy McCall ↶ 2743
    }
2744
2745
    /// The base state of `change` (its dependencies) and its rendering, as
2746
    /// much as showing the change needs: the whole tree, and the graphs and
2747
    /// contents of the files the change edits. Other text files are left
2748
    /// unrendered ([`Snapshot::unrendered`]).
2749
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
77445673 Andy McCall ↶ 2750
        let base = self.load_state_history(&change.deps)?;
2751
        self.render_base_for(change, base)
2752
    }
2753
dd6147dc Andy McCall ↶ 2754
    /// The base for showing `change` alone: the graphs of the files it
2755
    /// edits built, and the base's tree with no file rendered, which is
2756
    /// all [`render_change`](snapshot::render_change) and
2757
    /// [`diff_files_of`](snapshot::diff_files_of) read.
2758
    pub(crate) fn tree_base_for(
2759
        &self,
2760
        change: &Change,
2761
        mut base: State,
2762
    ) -> Result<(State, Snapshot)> {
2763
        let _t = crate::timing::phase("diff: the base's tree");
2764
        let edited: std::collections::HashSet<NodeId> =
2765
            change.edits.iter().map(|e| e.node()).collect();
2766
        let nodes: Vec<NodeId> = edited.into_iter().collect();
2767
        self.load_graphs_of(&mut base, &nodes)?;
2768
        let snapshot = Snapshot {
c2e1d090 Andy McCall 2769
            tree: self.tree_view(&mut base)?,
dd6147dc Andy McCall ↶ 2770
            files: BTreeMap::new(),
2771
            unrendered: BTreeSet::new(),
2772
        };
2773
        Ok((base, snapshot))
2774
    }
2775
77445673 Andy McCall ↶ 2776
    /// [`Repo::change_base`] with the base already loaded (the working
2777
    /// copy's comes from the state index).
2778
    pub(crate) fn render_base_for(
2779
        &self,
2780
        change: &Change,
2781
        mut base: State,
2782
    ) -> Result<(State, Snapshot)> {
10b4fd43 Andy McCall ↶ 2783
        let _t = crate::timing::phase("diff: render the base");
8ab265dc Andy McCall ↶ 2784
        let edited: std::collections::HashSet<NodeId> =
2785
            change.edits.iter().map(|e| e.node()).collect();
2786
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2787
        self.load_graphs_of(&mut base, &nodes)?;
c2e1d090 Andy McCall 2788
        self.tree_view(&mut base)?;
10b4fd43 Andy McCall ↶ 2789
        let snapshot = {
2790
            let _t = crate::timing::phase("diff:   of which materialize");
2791
            base.materialize_nodes(&edited)
2792
        };
8ab265dc Andy McCall ↶ 2793
        Ok((base, snapshot))
98286406 Andy McCall ↶ 2794
    }
2795
}
2796
2797
fn remove_any(path: &Path) -> std::io::Result<()> {
2798
    let m = fs::symlink_metadata(path)?;
75167672 Andy McCall 2799
    if m.is_dir() {
2800
        fs::remove_dir_all(path)
2801
    } else {
2802
        fs::remove_file(path)
2803
    }
98286406 Andy McCall ↶ 2804
}
2805
cdb5beba Andy McCall ↶ 2806
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
2807
    let mut perms = fs::metadata(path)?.permissions();
2808
    perms.set_readonly(readonly);
2809
    fs::set_permissions(path, perms)
2810
}
2811
98286406 Andy McCall ↶ 2812
#[cfg(unix)]
2813
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2814
    use std::os::unix::fs::PermissionsExt;
2815
    let mut perms = fs::metadata(path)?.permissions();
2816
    let mode = perms.mode();
2817
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
2818
    if want != mode {
2819
        perms.set_mode(want);
2820
        fs::set_permissions(path, perms)?;
2821
    }
2822
    Ok(())
2823
}
2824
#[cfg(not(unix))]
2825
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2826
    Ok(())
2827
}
2828
2829
#[cfg(unix)]
e96a430c Andy McCall ↶ 2830
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
98286406 Andy McCall ↶ 2831
    use std::os::unix::fs::PermissionsExt;
2832
    m.permissions().mode() & 0o111 != 0
2833
}
2834
#[cfg(not(unix))]
e96a430c Andy McCall ↶ 2835
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
98286406 Andy McCall ↶ 2836
    false
2837
}
2838
2839
fn op_ref(k: OpKey) -> OpRef {
75167672 Andy McCall 2840
    OpRef {
2841
        change: k.0,
2842
        index: k.1,
2843
    }
98286406 Andy McCall ↶ 2844
}
2845
2846
fn split_path(path: &str) -> (&str, &str) {
2847
    match path.rfind('/') {
2848
        Some(i) => (&path[..i], &path[i + 1..]),
2849
        None => ("", path),
2850
    }
cc7a0056 Andy McCall ↶ 2851
}
2852
2853
/// Whether `rel` is an attributes file (spec §7.6).
2854
fn is_attributes(rel: &str) -> bool {
2855
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
98286406 Andy McCall ↶ 2856
}
e7ddd552 Andy McCall ↶ 2857
cc7a0056 Andy McCall ↶ 2858
/// The manifest entry for `rel` when its size and mtime match it outside
2859
/// the racy window.
2860
fn stat_cached<'m>(
2861
    rel: &str,
e96a430c Andy McCall ↶ 2862
    meta: &walk::Stat,
cc7a0056 Andy McCall ↶ 2863
    cache: Option<&'m prompt::Manifest>,
2864
) -> Option<&'m prompt::ManifestEntry> {
2865
    let m = cache?;
2866
    let e = m.entries.get(rel)?;
e96a430c Andy McCall ↶ 2867
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
2868
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
cc7a0056 Andy McCall ↶ 2869
}
2870
2871
/// Read one working-copy file, or serve it from the stat cache (spec
2872
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2873
/// an opaque file is not read at all (its stored blob stands in), and a
2874
/// text file the manifest recorded equal to a base graph whose key is
2875
/// `key`, the key the base has now, is not read either: equal keys mean
2876
/// equal renderings, so it still equals the base. Touches no repository
2877
/// state, so the walk runs it in parallel; the caller checks that a cached
2878
/// blob is still in the store.
e7ddd552 Andy McCall ↶ 2879
fn read_file_entry(
2880
    rel: &str,
2881
    path: &Path,
e96a430c Andy McCall ↶ 2882
    meta: &walk::Stat,
e7ddd552 Andy McCall ↶ 2883
    cache: Option<&prompt::Manifest>,
1966f5db Andy McCall ↶ 2884
    key: Option<[u8; 32]>,
e7ddd552 Andy McCall ↶ 2885
) -> Result<FsEntry> {
e96a430c Andy McCall ↶ 2886
    let exec = meta.exec;
2887
    let stat = Some((meta.size, meta.mtime_ns));
8b276e01 Andy McCall ↶ 2888
    let mut e = match stat_cached(rel, meta, cache) {
e7ddd552 Andy McCall ↶ 2889
        Some(e) if e.blob.is_some() => FsEntry {
2890
            blob: e.blob,
1966f5db Andy McCall ↶ 2891
            content_hash: Some(e.hash),
cc7a0056 Andy McCall ↶ 2892
            ..FsEntry::new(NodeKind::File, exec, vec![])
2893
        },
1966f5db Andy McCall ↶ 2894
        Some(e) if key.is_some() && e.graph == key => FsEntry {
2895
            content_hash: Some(e.hash),
cc7a0056 Andy McCall ↶ 2896
            unchanged: true,
1966f5db Andy McCall ↶ 2897
            graph_key: e.graph,
cc7a0056 Andy McCall ↶ 2898
            ..FsEntry::new(NodeKind::File, exec, vec![])
2899
        },
2900
        Some(e) => FsEntry {
1966f5db Andy McCall ↶ 2901
            content_hash: Some(e.hash),
cc7a0056 Andy McCall ↶ 2902
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
e7ddd552 Andy McCall ↶ 2903
        },
2904
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
8b276e01 Andy McCall ↶ 2905
    };
2906
    // The stat the manifest records: taken before the read, so a file that
2907
    // changes meanwhile is read again next time.
2908
    e.stat = stat;
2909
    Ok(e)
e7ddd552 Andy McCall ↶ 2910
}
f57bf670 Andy McCall ↶ 2911
2912
/// Two maps side by side in key order: each key of either, with its value
2913
/// in each. Linear, with no lookups, for maps of a whole tree.
2914
pub(crate) fn join<'a, A, B>(
2915
    a: &'a BTreeMap<String, A>,
2916
    b: &'a BTreeMap<String, B>,
2917
) -> impl Iterator<Item = (&'a String, Option<&'a A>, Option<&'a B>)> {
2918
    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
2919
    std::iter::from_fn(move || match (a.peek(), b.peek()) {
2920
        (None, None) => None,
2921
        (Some(_), None) => a.next().map(|(k, v)| (k, Some(v), None)),
2922
        (None, Some(_)) => b.next().map(|(k, v)| (k, None, Some(v))),
2923
        (Some((ka, _)), Some((kb, _))) => match ka.cmp(kb) {
2924
            std::cmp::Ordering::Less => a.next().map(|(k, v)| (k, Some(v), None)),
2925
            std::cmp::Ordering::Greater => b.next().map(|(k, v)| (k, None, Some(v))),
2926
            std::cmp::Ordering::Equal => {
2927
                let (k, va) = a.next()?;
2928
                let (_, vb) = b.next()?;
2929
                Some((k, Some(va), Some(vb)))
2930
            }
2931
        },
2932
    })
2933
}
2934
2935
/// The entries of `a` whose keys `b` lacks, in key order: linear, with no
2936
/// lookups.
2937
pub(crate) fn missing_from<'a, A, B>(
2938
    a: &'a BTreeMap<String, A>,
2939
    b: &BTreeMap<String, B>,
2940
) -> Vec<(&'a String, &'a A)> {
2941
    let mut keys = b.keys().peekable();
2942
    a.iter()
2943
        .filter(|(k, _)| {
2944
            while keys.next_if(|kb| *kb < *k).is_some() {}
2945
            keys.peek() != Some(k)
2946
        })
2947
        .collect()
2948
}