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