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