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