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