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