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