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