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