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