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