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