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