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