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