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