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