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