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