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