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