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