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