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