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