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