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