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