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