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