OXYGENHUB
# f6451fbbae3f oxygen / crates / oxy-core / src / repo / mod.rs
65.2 KiB · Rust · last changed Verify a Git import from each parent's state 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) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
909
            while let Some(h) = stack.pop() {
910
                if !seen.insert(h) {
911
                    continue;
912
                }
913
                let t0 = std::time::Instant::now();
914
                // A history-only state reads text only for the graphs it
915
                // builds; either way the hash is the one asked for.
916
                let (c, texts) = if history {
917
                    self.store.get_change_lazy(&h)?
918
                } else {
919
                    (self.store.get_change(&h)?, Vec::new())
920
                };
921
                read += t0.elapsed();
922
                stack.extend(c.deps.iter().copied());
923
                let t1 = std::time::Instant::now();
924
                state.add_known(h, c, texts);
925
                add += t1.elapsed();
926
            }
927
            crate::timing::record("load:   of which reading", read);
928
            crate::timing::record("load:   of which applying", add);
929
        }
930
        let _t = crate::timing::phase("load: validate");
931
        state.validate()?;
932
        Ok(state)
933
    }
934
935
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
936
        if self.bare {
937
            return fail("this is a bare repository: it has no working copy");
938
        }
939
        let view = self.view()?;
940
        let h = *view
941
            .workspaces
942
            .get(&self.workspace)
943
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
944
        Ok((h, self.store.get_change(&h)?))
945
    }
946
947
    /// Heads of a bookmark's state (spec §10.1).
948
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
949
        match view.bookmarks.get(bookmark) {
950
            Some(st) => Ok(self.store.get_state(st)?.heads),
951
            None => Ok(vec![]),
952
        }
953
    }
954
955
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
956
        self.heads_of(&self.view()?, &self.config.bookmark)
957
    }
958
959
    // ------------------------------------------------------------ blobs
960
961
    fn blob_for(content: &[u8]) -> Blob {
962
        Blob::of(content)
963
    }
964
965
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
966
        Self::blob_for(content).hash()
967
    }
968
969
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
970
        for c in crate::chunk::chunks(content) {
971
            self.store.put_chunk(c)?;
972
        }
973
        Ok(self
974
            .store
975
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
976
    }
977
978
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
979
    /// all their chunks, are read in parallel; a blob the store lacks goes
980
    /// through [`Repo::read_blob`], which may fetch it lazily.
981
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
982
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
983
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
984
            blobs.push(match got {
985
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
986
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
987
                Err(crate::store::StoreError::NotFound(_)) => None,
988
                Err(e) => return Err(e.into()),
989
            });
990
        }
991
        let chunk_refs: Vec<ObjectRef> = blobs
992
            .iter()
993
            .flatten()
994
            .flat_map(|b| b.chunks.iter().copied())
995
            .collect();
996
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
997
        let mut out = Vec::with_capacity(refs.len());
998
        for (r, blob) in refs.iter().zip(blobs) {
999
            match blob {
1000
                None => out.push(self.read_blob(r)?),
1001
                Some(b) => {
1002
                    let mut content = Vec::with_capacity(b.length as usize);
1003
                    for c in &b.chunks {
1004
                        match chunks.next() {
1005
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
1006
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
1007
                            Some(Err(e)) => return Err(e.into()),
1008
                            None => return fail("chunk list ended early"),
1009
                        }
1010
                    }
1011
                    out.push(content);
1012
                }
1013
            }
1014
        }
1015
        Ok(out)
1016
    }
1017
1018
    /// Read a blob's content, fetching it from the remote that withheld it
1019
    /// when it is lazily absent (spec §13.5).
1020
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1021
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
1022
            self.fetch_lazy_blob(r)?;
1023
        }
1024
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1025
        let mut out = Vec::with_capacity(blob.length as usize);
1026
        for c in &blob.chunks {
1027
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1028
        }
1029
        Ok(out)
1030
    }
1031
1032
    // ------------------------------------------------------------ working copy
1033
1034
    /// Attributes from the `.oxyattributes` files in the working directory.
1035
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1036
        let mut files: Vec<(String, Vec<u8>)> = Vec::new();
1037
        if let Ok(b) = fs::read(self.root.join(".oxyattributes")) {
1038
            files.push((".oxyattributes".into(), b));
1039
        }
1040
        let mut wb = ignore::WalkBuilder::new(&self.root);
1041
        wb.hidden(false)
1042
            .git_ignore(false)
1043
            .git_global(false)
1044
            .git_exclude(false)
1045
            .require_git(false)
1046
            .follow_links(false)
1047
            .add_custom_ignore_filename(".oxyignore");
1048
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
1049
        for entry in wb.build().flatten() {
1050
            if entry.file_name() == ".oxyattributes"
1051
                && entry.path() != self.root.join(".oxyattributes")
1052
            {
1053
                if let Ok(b) = fs::read(entry.path()) {
1054
                    let rel: String = entry
1055
                        .path()
1056
                        .strip_prefix(&self.root)
1057
                        .unwrap()
1058
                        .components()
1059
                        .map(|c| c.as_os_str().to_string_lossy().to_string())
1060
                        .collect::<Vec<_>>()
1061
                        .join("/");
1062
                    files.push((rel, b));
1063
                }
1064
            }
1065
        }
1066
        crate::attributes::Attributes::from_files(
1067
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1068
        )
1069
    }
1070
1071
    /// Attributes from a materialized state's `.oxyattributes` files.
1072
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
1073
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
1074
            match &f.content {
1075
                FileContent::Text { bytes, .. }
1076
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1077
                {
1078
                    Some((p.as_str(), bytes.as_slice()))
1079
                }
1080
                _ => None,
1081
            }
1082
        }))
1083
    }
1084
1085
    /// Store a blob, raw when the path is `nocompress`.
1086
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1087
        if !nocompress {
1088
            return self.store_blob(content);
1089
        }
1090
        for c in crate::chunk::chunks(content) {
1091
            self.store.put_chunk_nocompress(c)?;
1092
        }
1093
        Ok(self
1094
            .store
1095
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1096
    }
1097
1098
    fn locks_dir(&self) -> PathBuf {
1099
        self.oxy.join("locks")
1100
    }
1101
1102
    /// Whether `path` is locked locally for editing (spec §18, advisory).
1103
    pub fn is_locked(&self, path: &str) -> bool {
1104
        self.locks_dir().join(path.replace('/', "%2F")).exists()
1105
    }
1106
1107
    /// Take the advisory local lock on a `lockable` file and make it writable.
1108
    pub fn lock_path(&self, path: &str) -> Result<()> {
1109
        let attrs = self.disk_attributes();
1110
        if !attrs.lookup(path).lockable {
1111
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
1112
        }
1113
        fs::create_dir_all(self.locks_dir())?;
1114
        write_atomic(
1115
            &self.locks_dir().join(path.replace('/', "%2F")),
1116
            std::process::id().to_string().as_bytes(),
1117
        )?;
1118
        set_readonly(&self.root.join(path), false)?;
1119
        Ok(())
1120
    }
1121
1122
    /// Release the local lock and make the file read-only again.
1123
    pub fn unlock_path(&self, path: &str) -> Result<()> {
1124
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
1125
        if self.root.join(path).exists() {
1126
            set_readonly(&self.root.join(path), true)?;
1127
        }
1128
        Ok(())
1129
    }
1130
1131
    /// Whether a repository path is inside the sparse filter (spec §17).
1132
    pub fn in_scope(&self, path: &str) -> bool {
1133
        self.config.sparse_paths.is_empty()
1134
            || self
1135
                .config
1136
                .sparse_paths
1137
                .iter()
1138
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
1139
    }
1140
1141
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
1142
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
1143
    }
1144
1145
    /// A walker over the working copy that never enters a nested repository
1146
    /// (a directory below the root holding `.oxy` or `.git`); the directories
1147
    /// it skipped are collected into `nested`.
1148
    pub(crate) fn walker(
1149
        &self,
1150
        nested: &std::sync::Arc<std::sync::Mutex<Vec<PathBuf>>>,
1151
    ) -> ignore::WalkBuilder {
1152
        let mut wb = ignore::WalkBuilder::new(&self.root);
1153
        wb.hidden(false)
1154
            .git_ignore(false)
1155
            .git_global(false)
1156
            .git_exclude(false)
1157
            .require_git(false)
1158
            .follow_links(false)
1159
            .add_custom_ignore_filename(".oxyignore");
1160
        let nested = nested.clone();
1161
        wb.filter_entry(move |e| {
1162
            if e.file_name() == OXY_DIR {
1163
                return false;
1164
            }
1165
            if e.depth() > 0
1166
                && e.file_type().is_some_and(|t| t.is_dir())
1167
                && (e.path().join(OXY_DIR).exists() || e.path().join(".git").exists())
1168
            {
1169
                nested.lock().unwrap().push(e.path().to_path_buf());
1170
                return false;
1171
            }
1172
            true
1173
        });
1174
        wb
1175
    }
1176
1177
    /// Walk the working copy; with a manifest, a file whose size and mtime
1178
    /// match it is not read: an opaque file yields its known blob, and a
1179
    /// text file whose recorded graph key equals its base graph's key in
1180
    /// `keys` (path → key) is marked unchanged; other text files are read
1181
    /// but keep their known hash. Files modified within two seconds of the
1182
    /// manifest are never trusted (a racy stat).
1183
    ///
1184
    /// `.oxyattributes` files are always read, since their content is
1185
    /// needed; and when any of them is not known unchanged (added, removed,
1186
    /// edited, or changed in the base), no text file is taken as unchanged,
1187
    /// because attributes decide how a file compares with the base.
1188
    ///
1189
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
1190
    /// (the base state's files) that exists on disk is included even when
1191
    /// an ignore rule matches it, as in Git.
1192
    fn walk_working_copy_with(
1193
        &self,
1194
        cache: Option<&prompt::Manifest>,
1195
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
1196
        keys: Option<&HashMap<String, String>>,
1197
    ) -> Result<BTreeMap<String, FsEntry>> {
1198
        let nested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1199
        let wb = self.walker(&nested);
1200
        let mut out = BTreeMap::new();
1201
        // The walk itself runs on every core: each entry is found and
1202
        // statted on its own.
1203
        enum Found {
1204
            File(String, PathBuf, fs::Metadata),
1205
            Symlink(String, Vec<u8>),
1206
        }
1207
        let found: std::sync::Mutex<Vec<Found>> = std::sync::Mutex::new(Vec::new());
1208
        let failed: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
1209
        let (root, sparse) = (&self.root, &self.config.sparse_paths);
1210
        let in_scope = |p: &str| {
1211
            sparse.is_empty()
1212
                || sparse
1213
                    .iter()
1214
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
1215
        };
1216
        wb.build_parallel().run(|| {
1217
            let (found, failed) = (&found, &failed);
1218
            Box::new(move |entry| {
1219
                use ignore::WalkState;
1220
                let step = || -> std::result::Result<Option<Found>, String> {
1221
                    let entry = entry.map_err(|e| e.to_string())?;
1222
                    let path = entry.path();
1223
                    if path == root {
1224
                        return Ok(None);
1225
                    }
1226
                    let rel: String = path
1227
                        .strip_prefix(root)
1228
                        .unwrap()
1229
                        .components()
1230
                        .map(|c| c.as_os_str().to_string_lossy().to_string())
1231
                        .collect::<Vec<_>>()
1232
                        .join("/");
1233
                    let Some(ft) = entry.file_type() else {
1234
                        return Ok(None);
1235
                    };
1236
                    if ft.is_dir() || !in_scope(&rel) {
1237
                        return Ok(None);
1238
                    }
1239
                    if ft.is_symlink() {
1240
                        let target = fs::read_link(path).map_err(|e| e.to_string())?;
1241
                        return Ok(Some(Found::Symlink(
1242
                            rel,
1243
                            target.to_string_lossy().as_bytes().to_vec(),
1244
                        )));
1245
                    }
1246
                    if ft.is_file() {
1247
                        let meta = entry.metadata().map_err(|e| e.to_string())?;
1248
                        return Ok(Some(Found::File(rel, path.to_path_buf(), meta)));
1249
                    }
1250
                    Ok(None)
1251
                };
1252
                match step() {
1253
                    Ok(Some(f)) => found.lock().unwrap().push(f),
1254
                    Ok(None) => {}
1255
                    Err(e) => {
1256
                        failed.lock().unwrap().get_or_insert(e);
1257
                        return WalkState::Quit;
1258
                    }
1259
                }
1260
                WalkState::Continue
1261
            })
1262
        });
1263
        if let Some(e) = failed.into_inner().unwrap() {
1264
            return fail(e);
1265
        }
1266
        let mut files: Vec<(String, PathBuf, fs::Metadata)> = Vec::new();
1267
        for f in found.into_inner().unwrap() {
1268
            match f {
1269
                Found::File(rel, path, meta) => files.push((rel, path, meta)),
1270
                Found::Symlink(rel, target) => {
1271
                    out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
1272
                }
1273
            }
1274
        }
1275
        let keys = keys.filter(|k| {
1276
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
1277
            let attrs_unchanged =
1278
                files
1279
                    .iter()
1280
                    .filter(|(r, _, _)| is_attributes(r))
1281
                    .all(|(rel, _, meta)| {
1282
                        stat_cached(rel, meta, cache)
1283
                            .is_some_and(|e| e.graph.is_some() && e.graph.as_ref() == k.get(rel))
1284
                    });
1285
            let none_removed = tracked
1286
                .keys()
1287
                .filter(|r| is_attributes(r))
1288
                .all(|r| on_disk.contains(r.as_str()));
1289
            attrs_unchanged && none_removed
1290
        });
1291
        // Reading files is most of a walk's cost; do it in parallel.
1292
        {
1293
            use rayon::prelude::*;
1294
            let read: Vec<(String, FsEntry)> = files
1295
                .par_iter()
1296
                .map(|(rel, path, meta)| {
1297
                    let key = keys
1298
                        .filter(|_| !is_attributes(rel))
1299
                        .and_then(|k| k.get(rel))
1300
                        .map(String::as_str);
1301
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
1302
                })
1303
                .collect::<Result<Vec<_>>>()?;
1304
            for (rel, mut e) in read {
1305
                // A cached blob the store lost (gc, a partial clone): read the file after all.
1306
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
1307
                    e.content = fs::read(self.root.join(&rel))?;
1308
                    e.blob = None;
1309
                }
1310
                out.insert(rel, e);
1311
            }
1312
        }
1313
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
1314
        // already tracked as subrepo nodes, they contribute their pin;
1315
        // unregistered ones are left alone.
1316
        let modules = self.modules_on_disk();
1317
        let removed = self.removed_subrepos();
1318
        for rel in &removed {
1319
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
1320
                self.clear_removed_subrepo(rel);
1321
            }
1322
        }
1323
        let nested_dirs = std::mem::take(&mut *nested.lock().unwrap());
1324
        for dir in nested_dirs {
1325
            let rel = self.rel_path(&dir);
1326
            if !self.in_scope(&rel) || removed.contains(&rel) {
1327
                continue;
1328
            }
1329
            let registered = modules.entries.get(&rel);
1330
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
1331
            {
1332
                continue;
1333
            }
1334
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
1335
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
1336
        }
1337
        // Tracked paths the ignore rules hid.
1338
        for (rel, (kind, blob)) in tracked {
1339
            if out.contains_key(rel) || !self.in_scope(rel) {
1340
                continue;
1341
            }
1342
            let path = self.root.join(rel);
1343
            if *kind == NodeKind::Subrepo {
1344
                if removed.contains(rel) {
1345
                    continue;
1346
                }
1347
                let present =
1348
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
1349
                if present {
1350
                    let pin = subrepos::read_pin(
1351
                        &path,
1352
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
1353
                    )?;
1354
                    out.insert(
1355
                        rel.clone(),
1356
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
1357
                    );
1358
                } else if let Some(b) = blob {
1359
                    // Not cloned (or emptied): the pin stays as recorded, as a
1360
                    // Git gitlink does when its directory is absent.
1361
                    out.insert(
1362
                        rel.clone(),
1363
                        FsEntry {
1364
                            blob: Some(*b),
1365
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
1366
                        },
1367
                    );
1368
                }
1369
                continue;
1370
            }
1371
            let Ok(meta) = fs::symlink_metadata(&path) else {
1372
                continue;
1373
            };
1374
            let ft = meta.file_type();
1375
            if ft.is_symlink() {
1376
                let target = fs::read_link(&path)?;
1377
                out.insert(
1378
                    rel.clone(),
1379
                    FsEntry::new(
1380
                        NodeKind::Symlink,
1381
                        false,
1382
                        target.to_string_lossy().as_bytes().to_vec(),
1383
                    ),
1384
                );
1385
            } else if ft.is_file() {
1386
                let e = self.file_entry(rel, &path, &meta, cache)?;
1387
                out.insert(rel.clone(), e);
1388
            }
1389
        }
1390
        Ok(out)
1391
    }
1392
1393
    /// The entry for one regular file, read or served from the stat cache.
1394
    fn file_entry(
1395
        &self,
1396
        rel: &str,
1397
        path: &Path,
1398
        meta: &fs::Metadata,
1399
        cache: Option<&prompt::Manifest>,
1400
    ) -> Result<FsEntry> {
1401
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
1402
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
1403
            e.content = fs::read(path)?;
1404
            e.blob = None;
1405
        }
1406
        Ok(e)
1407
    }
1408
1409
    /// The non-directory paths of a snapshot with their kinds, for the
1410
    /// walker's `tracked` set.
1411
    pub(crate) fn tracked_kinds(
1412
        snapshot: &Snapshot,
1413
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
1414
        snapshot
1415
            .files
1416
            .iter()
1417
            .filter(|(_, f)| f.kind != NodeKind::Dir)
1418
            .map(|(p, f)| {
1419
                let blob = match &f.content {
1420
                    FileContent::Opaque { blobs } => blobs.first().copied(),
1421
                    _ => None,
1422
                };
1423
                (p.clone(), (f.kind, blob))
1424
            })
1425
            .collect()
1426
    }
1427
1428
    /// A path under the root as a `/`-separated relative string.
1429
    pub(crate) fn rel_path(&self, path: &Path) -> String {
1430
        path.strip_prefix(&self.root)
1431
            .unwrap_or(path)
1432
            .components()
1433
            .map(|c| c.as_os_str().to_string_lossy().to_string())
1434
            .collect::<Vec<_>>()
1435
            .join("/")
1436
    }
1437
}
1438
1439
impl Repo {
1440
    /// Changes reachable from the bookmark and the working copy, newest first.
1441
    pub fn log(&self) -> Result<Vec<LogEntry>> {
1442
        let heads = self.bookmark_heads()?;
1443
        if self.bare {
1444
            return self.log_state(&heads);
1445
        }
1446
        let (wc_hash, _) = self.working_copy()?;
1447
        let mut all = heads.clone();
1448
        all.push(wc_hash);
1449
        let state = self.load_state_history(&all)?;
1450
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
1451
        let mut entries: Vec<LogEntry> = Vec::new();
1452
        for (h, meta) in state.changes() {
1453
            entries.push(LogEntry {
1454
                hash: *h,
1455
                change: meta.clone(),
1456
                is_working_copy: *h == wc_hash,
1457
                is_head: head_set.contains(h),
1458
            });
1459
        }
1460
        entries.sort_by(|a, b| {
1461
            b.is_working_copy
1462
                .cmp(&a.is_working_copy)
1463
                .then(b.change.hlc.cmp(&a.change.hlc))
1464
                .then(b.hash.cmp(&a.hash))
1465
        });
1466
        Ok(entries)
1467
    }
1468
1469
    /// A window of `log_state`: entries `offset..offset+limit` and the total
1470
    /// count, for paginated views.
1471
    pub fn log_window(
1472
        &self,
1473
        heads: &[ChangeHash],
1474
        offset: usize,
1475
        limit: usize,
1476
    ) -> Result<(Vec<LogEntry>, usize)> {
1477
        let all = self.log_state(heads)?;
1478
        let total = all.len();
1479
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
1480
    }
1481
1482
    /// The log of the state with these heads, newest first, with no working
1483
    /// copy involved (for hosted repositories and any explicit state).
1484
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1485
        // The log needs change metadata only: no file graph is built.
1486
        Ok(self.log_of(&self.load_state_history(heads)?))
1487
    }
1488
1489
    /// The log of a state already loaded, newest first.
1490
    /// The history of lines `first..=last` (1-based) of `path` in the
1491
    /// state `heads` make (spec §27): every change that inserted or
1492
    /// deleted one of their atoms, or an atom deleted from between them,
1493
    /// newest first. Exact, as atoms keep their identity across edits.
1494
    pub fn line_history(
1495
        &self,
1496
        heads: &[ChangeHash],
1497
        path: &str,
1498
        first: usize,
1499
        last: usize,
1500
    ) -> Result<Vec<LogEntry>> {
1501
        if first == 0 || last < first {
1502
            return fail(format!(
1503
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
1504
            ));
1505
        }
1506
        let mut state = self.load_state_history(heads)?;
1507
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
1508
            return fail(format!("{path} is not in that state"));
1509
        };
1510
        self.load_graphs_of(&mut state, &[node])?;
1511
        let live = state.live_lines(&node);
1512
        if last > live.len() {
1513
            return fail(format!(
1514
                "{path} has {} lines; asked for {first},{last}",
1515
                live.len()
1516
            ));
1517
        }
1518
        let Some(g) = state.file(&node) else {
1519
            return fail(format!("{path} is not a text file"));
1520
        };
1521
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
1522
        let touched = g.touching(&atoms);
1523
        Ok(self
1524
            .log_of(&state)
1525
            .into_iter()
1526
            .filter(|e| touched.contains(&e.hash))
1527
            .collect())
1528
    }
1529
1530
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
1531
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
1532
        let mut entries: Vec<LogEntry> = state
1533
            .changes()
1534
            .map(|(h, meta)| LogEntry {
1535
                hash: *h,
1536
                change: meta.clone(),
1537
                is_working_copy: false,
1538
                is_head: head_set.contains(h),
1539
            })
1540
            .collect();
1541
        entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
1542
        entries
1543
    }
1544
1545
    /// Resolve a spec to a set of heads: a tag name, the current bookmark's
1546
    /// name, or a single change (`resolve_change`).
1547
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
1548
        let view = self.view()?;
1549
        if let Some(st) = view.bookmarks.get(spec) {
1550
            return Ok(self.store.get_state(st)?.heads);
1551
        }
1552
        if let Some(heads) = self.tag_heads(spec)? {
1553
            return Ok(heads);
1554
        }
1555
        Ok(vec![self.resolve_change(spec)?])
1556
    }
1557
1558
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
1559
    /// copy), bookmark or tag (the one head of its state).
1560
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
1561
        if spec == "@" {
1562
            return Ok(self.working_copy()?.0);
1563
        }
1564
        let named = match self.view()?.bookmarks.get(spec) {
1565
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
1566
            None => self.tag_heads(spec)?.map(|h| ("tag", h)),
1567
        };
1568
        if let Some((kind, heads)) = named {
1569
            return match heads.len() {
1570
                1 => Ok(heads[0]),
1571
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
1572
            };
1573
        }
1574
        if spec.is_empty() || spec == "#" {
1575
            return fail("empty change specifier");
1576
        }
1577
        let entries = self.log()?;
1578
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
1579
            entries
1580
                .iter()
1581
                .filter(|e| e.hash.starts_with_hex(hp))
1582
                .collect()
1583
        } else {
1584
            entries
1585
                .iter()
1586
                .filter(|e| e.change.change_id.starts_with_hex(spec))
1587
                .collect()
1588
        };
1589
        match matches.len() {
1590
            1 => Ok(matches[0].hash),
1591
            0 => fail(format!("no change matches {spec:?}")),
1592
            _ => {
1593
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
1594
                if ids.len() == 1 {
1595
                    fail(format!(
1596
                        "change {spec} is divergent: {} variants",
1597
                        matches.len()
1598
                    ))
1599
                } else {
1600
                    fail(format!("{spec:?} is ambiguous"))
1601
                }
1602
            }
1603
        }
1604
    }
1605
1606
    /// Human-readable description of what a change does, with line content.
1607
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
1608
        let change = self.store.get_change(hash)?;
1609
        let (base, base_snapshot) = self.change_base(&change)?;
1610
        Ok(render_change(&change, &base, &base_snapshot))
1611
    }
1612
1613
    /// The base state of `change` (its dependencies) and its rendering, as
1614
    /// much as showing the change needs: the whole tree, and the graphs and
1615
    /// contents of the files the change edits. Other text files are left
1616
    /// unrendered ([`Snapshot::unrendered`]).
1617
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
1618
        let mut base = self.load_state_history(&change.deps)?;
1619
        let edited: std::collections::HashSet<NodeId> =
1620
            change.edits.iter().map(|e| e.node()).collect();
1621
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
1622
        self.load_graphs_of(&mut base, &nodes)?;
1623
        let skip: std::collections::HashSet<NodeId> = base
1624
            .tree()
1625
            .view()
1626
            .entries
1627
            .values()
1628
            .filter(|e| e.kind == crate::objects::NodeKind::File && !edited.contains(&e.node))
1629
            .map(|e| e.node)
1630
            .collect();
1631
        let snapshot = base.materialize_except(&skip);
1632
        Ok((base, snapshot))
1633
    }
1634
}
1635
1636
fn remove_any(path: &Path) -> std::io::Result<()> {
1637
    let m = fs::symlink_metadata(path)?;
1638
    if m.is_dir() {
1639
        fs::remove_dir_all(path)
1640
    } else {
1641
        fs::remove_file(path)
1642
    }
1643
}
1644
1645
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
1646
    let mut perms = fs::metadata(path)?.permissions();
1647
    perms.set_readonly(readonly);
1648
    fs::set_permissions(path, perms)
1649
}
1650
1651
#[cfg(unix)]
1652
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
1653
    use std::os::unix::fs::PermissionsExt;
1654
    let mut perms = fs::metadata(path)?.permissions();
1655
    let mode = perms.mode();
1656
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
1657
    if want != mode {
1658
        perms.set_mode(want);
1659
        fs::set_permissions(path, perms)?;
1660
    }
1661
    Ok(())
1662
}
1663
#[cfg(not(unix))]
1664
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
1665
    Ok(())
1666
}
1667
1668
#[cfg(unix)]
1669
fn is_executable(m: &fs::Metadata) -> bool {
1670
    use std::os::unix::fs::PermissionsExt;
1671
    m.permissions().mode() & 0o111 != 0
1672
}
1673
#[cfg(not(unix))]
1674
fn is_executable(_m: &fs::Metadata) -> bool {
1675
    false
1676
}
1677
1678
fn op_ref(k: OpKey) -> OpRef {
1679
    OpRef {
1680
        change: k.0,
1681
        index: k.1,
1682
    }
1683
}
1684
1685
fn split_path(path: &str) -> (&str, &str) {
1686
    match path.rfind('/') {
1687
        Some(i) => (&path[..i], &path[i + 1..]),
1688
        None => ("", path),
1689
    }
1690
}
1691
1692
/// Whether `rel` is an attributes file (spec §7.6).
1693
fn is_attributes(rel: &str) -> bool {
1694
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
1695
}
1696
1697
/// The manifest entry for `rel` when its size and mtime match it outside
1698
/// the racy window.
1699
fn stat_cached<'m>(
1700
    rel: &str,
1701
    meta: &fs::Metadata,
1702
    cache: Option<&'m prompt::Manifest>,
1703
) -> Option<&'m prompt::ManifestEntry> {
1704
    let m = cache?;
1705
    let e = m.entries.get(rel)?;
1706
    let mtime_ns = prompt::mtime_ns(meta);
1707
    let racy = mtime_ns + 2_000_000_000 >= m.written_ns;
1708
    (e.size == meta.len() && e.mtime_ns == mtime_ns && !racy).then_some(e)
1709
}
1710
1711
/// Read one working-copy file, or serve it from the stat cache (spec
1712
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
1713
/// an opaque file is not read at all (its stored blob stands in), and a
1714
/// text file the manifest recorded equal to a base graph whose key is
1715
/// `key`, the key the base has now, is not read either: equal keys mean
1716
/// equal renderings, so it still equals the base. Touches no repository
1717
/// state, so the walk runs it in parallel; the caller checks that a cached
1718
/// blob is still in the store.
1719
fn read_file_entry(
1720
    rel: &str,
1721
    path: &Path,
1722
    meta: &fs::Metadata,
1723
    cache: Option<&prompt::Manifest>,
1724
    key: Option<&str>,
1725
) -> Result<FsEntry> {
1726
    let exec = is_executable(meta);
1727
    let stat = Some((meta.len(), prompt::mtime_ns(meta)));
1728
    let mut e = match stat_cached(rel, meta, cache) {
1729
        Some(e) if e.blob.is_some() => FsEntry {
1730
            blob: e.blob,
1731
            content_hash: Some(e.hash.clone()),
1732
            ..FsEntry::new(NodeKind::File, exec, vec![])
1733
        },
1734
        Some(e) if key.is_some() && e.graph.as_deref() == key => FsEntry {
1735
            content_hash: Some(e.hash.clone()),
1736
            unchanged: true,
1737
            graph_key: e.graph.clone(),
1738
            ..FsEntry::new(NodeKind::File, exec, vec![])
1739
        },
1740
        Some(e) => FsEntry {
1741
            content_hash: Some(e.hash.clone()),
1742
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
1743
        },
1744
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
1745
    };
1746
    // The stat the manifest records: taken before the read, so a file that
1747
    // changes meanwhile is read again next time.
1748
    e.stat = stat;
1749
    Ok(e)
1750
}