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