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