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