OXYGENHUB
# d616faf5d136 oxygen / crates / oxy-core / src / repo / mod.rs
65.2 KiB · Rust · last changed A snapshot builds only the paths that may have changed 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
#[derive(Clone)]
135
pub(crate) struct FsEntry {
136
    pub kind: NodeKind,
137
    pub exec: bool,
138
    /// File content, or a symlink's target. Empty when `blob` is set.
139
    pub content: Vec<u8>,
140
    /// The stored blob of an opaque file whose size and mtime are unchanged
141
    /// since the last manifest (spec §12.3 stat cache); the content was not
142
    /// read.
143
    pub blob: Option<ObjectRef>,
144
    /// BLAKE3 of the content, carried over from the manifest when the stat
145
    /// is unchanged, so the manifest can be rewritten without rehashing.
146
    pub content_hash: Option<String>,
147
    /// A text file known equal to the base's rendering without reading it:
148
    /// its stat matches the manifest and the manifest recorded it equal to
149
    /// a base file graph with the same key (spec §12.3). `content` is empty.
150
    pub unchanged: bool,
151
    /// The base graph key this file equals, for the next manifest.
152
    pub graph_key: Option<String>,
153
}
154
155
impl FsEntry {
156
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
157
        FsEntry {
158
            kind,
159
            exec,
160
            content,
161
            blob: None,
162
            content_hash: None,
163
            unchanged: false,
164
            graph_key: None,
165
        }
166
    }
167
}
168
169
pub struct Repo {
170
    /// Oxygen-pinned subrepos skipped by the running Git export.
171
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
172
    /// The manifest as last read, with the file identity it was read from,
173
    /// so one command parses it once (see `read_manifest`).
174
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
175
    root: PathBuf,
176
    oxy: PathBuf,
177
    store: Store,
178
    workspace: WorkspaceId,
179
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
180
    bare: bool,
181
    keys_dir: PathBuf,
182
    user_config: PathBuf,
183
    pub config: Config,
184
    /// What the working copy's file system can represent (spec §7.7).
185
    platform: crate::portable::Platform,
186
    /// The encoding of the change last read for its inline inserts.
187
    last_change: std::cell::RefCell<Option<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
188
}
189
190
/// Marker file of a bare repository, inside `.oxy/`.
191
const BARE_MARKER: &str = "bare";
192
/// Marker of a hosted repository that has no id yet: the first push binds
193
/// it to the pusher's id (spec §16.1).
194
const UNBOUND_MARKER: &str = "unbound";
195
196
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
197
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
198
pub fn default_home() -> PathBuf {
199
    if let Ok(h) = std::env::var("OXY_HOME") {
200
        return PathBuf::from(h);
201
    }
202
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
203
        return PathBuf::from(x).join("oxy");
204
    }
205
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
206
    PathBuf::from(home).join(".config").join("oxy")
207
}
208
209
pub fn default_keys_dir() -> PathBuf {
210
    default_home().join("keys")
211
}
212
213
pub fn default_user_config() -> PathBuf {
214
    default_home().join("config.toml")
215
}
216
217
/// Where `create_identity` records the author.
218
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219
pub enum IdentityScope {
220
    /// The user file: every repository of this user signs with it.
221
    User,
222
    /// This repository only.
223
    Repo,
224
}
225
226
impl Repo {
227
    // ------------------------------------------------------------ lifecycle
228
229
    pub fn init(root: &Path) -> Result<Repo> {
230
        let mut id = [0u8; 16];
231
        rand::rngs::OsRng.fill_bytes(&mut id);
232
        Self::init_with_id(root, id)
233
    }
234
235
    /// Initialize a repository with a given repository ID (clones share the
236
    /// ID of their origin, spec §14.4).
237
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
238
        fs::create_dir_all(root)?;
239
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
240
        let oxy = root.join(OXY_DIR);
241
        if oxy.exists() {
242
            return fail(format!("{} is already an oxy repository", root.display()));
243
        }
244
        fs::create_dir_all(oxy.join("ops"))?;
245
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
246
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
247
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
248
        config.save(&oxy.join("config"))?;
249
        let workspace = WorkspaceId::random();
250
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
251
        let store = Store::open(oxy.join("objects"))?;
252
        let repo = Repo {
253
            last_change: Default::default(),
254
            git_export_skipped: Default::default(),
255
            manifest_cache: Default::default(),
256
            root,
257
            oxy,
258
            store,
259
            workspace,
260
            bare: false,
261
            keys_dir: default_keys_dir(),
262
            platform: crate::portable::Platform::current(),
263
            user_config: default_user_config(),
264
            config,
265
        };
266
        repo.register_workspace(&workspace, &repo.root)?;
267
268
        let wc = repo.new_working_copy(vec![], "");
269
        let wc_hash = repo.store.put_change(&wc)?;
270
        let mut view = View::default();
271
        view.bookmarks.insert(
272
            repo.config.bookmark.clone(),
273
            repo.store.put_state(&StateObject::new(vec![]))?,
274
        );
275
        view.workspaces.insert(workspace, wc_hash);
276
        repo.record_op(&[], "oxy init", view)?;
277
        Ok(repo)
278
    }
279
280
    /// Create a bare repository: an object store, operation log and
281
    /// references with no workspace and no working copy, for hosting
282
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
283
    pub fn init_bare(root: &Path) -> Result<Repo> {
284
        let mut id = [0u8; 16];
285
        rand::rngs::OsRng.fill_bytes(&mut id);
286
        Self::init_bare_with_id(root, id)
287
    }
288
289
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
290
        fs::create_dir_all(root)?;
291
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
292
        let oxy = root.join(OXY_DIR);
293
        if oxy.exists() {
294
            return fail(format!("{} is already an oxy repository", root.display()));
295
        }
296
        fs::create_dir_all(oxy.join("ops"))?;
297
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
298
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
299
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
300
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
301
        config.save(&oxy.join("config"))?;
302
        let store = Store::open(oxy.join("objects"))?;
303
        let repo = Repo {
304
            last_change: Default::default(),
305
            git_export_skipped: Default::default(),
306
            manifest_cache: Default::default(),
307
            root,
308
            oxy,
309
            store,
310
            workspace: WorkspaceId::ZERO,
311
            bare: true,
312
            keys_dir: default_keys_dir(),
313
            platform: crate::portable::Platform::current(),
314
            user_config: default_user_config(),
315
            config,
316
        };
317
        let mut view = View::default();
318
        view.bookmarks.insert(
319
            repo.config.bookmark.clone(),
320
            repo.store.put_state(&StateObject::new(vec![]))?,
321
        );
322
        repo.record_op(&[], "oxy init --bare", view)?;
323
        Ok(repo)
324
    }
325
326
    /// A bare repository with no id yet. Its `id()` is all zero until the
327
    /// first push binds it (`bind_id`), so an existing repository can be
328
    /// pushed to a freshly created hosted one and keep its identity.
329
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
330
        let repo = Self::init_bare_with_id(root, [0; 16])?;
331
        fs::remove_file(repo.oxy.join("id"))?;
332
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
333
        Ok(repo)
334
    }
335
336
    pub fn is_unbound(&self) -> bool {
337
        self.oxy.join(UNBOUND_MARKER).is_file()
338
    }
339
340
    /// Give an unbound repository its id.
341
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
342
        if !self.is_unbound() {
343
            return fail("this repository already has an id");
344
        }
345
        if id == [0; 16] {
346
            return fail("a repository id cannot be all zero");
347
        }
348
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
349
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
350
        Ok(())
351
    }
352
353
    /// Whether this repository has no working copy (`init_bare`).
354
    pub fn is_bare(&self) -> bool {
355
        self.bare
356
    }
357
358
    /// Open the repository containing `start` (searching upwards).
359
    pub fn open(start: &Path) -> Result<Repo> {
360
        let start = start.canonicalize()?;
361
        let mut dir: Option<&Path> = Some(&start);
362
        while let Some(d) = dir {
363
            let oxy = d.join(OXY_DIR);
364
            if oxy.is_file() {
365
                // A secondary workspace (spec §12.2): the file points at the repository.
366
                let text = fs::read_to_string(&oxy)?;
367
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
368
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
369
                };
370
                let format = fs::read_to_string(shared.join("format"))?;
371
                if format != FORMAT_LINE {
372
                    return fail(format!("unsupported repository format: {}", format.trim()));
373
                }
374
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
375
                let store = Store::open(shared.join("objects"))?;
376
                let mut repo = Repo {
377
                    last_change: Default::default(),
378
                    git_export_skipped: Default::default(),
379
                    manifest_cache: Default::default(),
380
                    root: d.to_path_buf(),
381
                    oxy: shared,
382
                    store,
383
                    workspace,
384
                    bare: false,
385
                    keys_dir: default_keys_dir(),
386
                    platform: crate::portable::Platform::current(),
387
                    user_config: default_user_config(),
388
                    config,
389
                };
390
                repo.apply_workspace_bookmark();
391
                return Ok(repo);
392
            }
393
            if oxy.is_dir() {
394
                let format = fs::read_to_string(oxy.join("format"))?;
395
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
396
                let bare = oxy.join(BARE_MARKER).is_file();
397
                let workspace = if bare {
398
                    WorkspaceId::ZERO
399
                } else {
400
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
401
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
402
                };
403
                let store = Store::open(oxy.join("objects"))?;
404
                let mut repo = Repo {
405
                    last_change: Default::default(),
406
                    git_export_skipped: Default::default(),
407
                    manifest_cache: Default::default(),
408
                    root: d.to_path_buf(),
409
                    oxy,
410
                    store,
411
                    workspace,
412
                    bare,
413
                    keys_dir: default_keys_dir(),
414
                    platform: crate::portable::Platform::current(),
415
                    user_config: default_user_config(),
416
                    config,
417
                };
418
                if !bare {
419
                    repo.apply_workspace_bookmark();
420
                }
421
                if format == FORMAT1_LINE {
422
                    repo.migrate_format1()?;
423
                } else if format != FORMAT_LINE {
424
                    return fail(format!("unsupported repository format: {}", format.trim()));
425
                }
426
                return Ok(repo);
427
            }
428
            dir = d.parent();
429
        }
430
        fail(format!(
431
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
432
            start.display()
433
        ))
434
    }
435
436
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
437
    /// into format 2, where each bookmark names a `state` object.
438
    fn migrate_format1(&self) -> Result<()> {
439
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
440
        let head = ObjectRef::from_hex(hex.trim())
441
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
442
        // Collect the chain root-first.
443
        let mut chain: Vec<Format1Op> = Vec::new();
444
        let mut cur = Some(head);
445
        while let Some(r) = cur {
446
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
447
            cur = op.parents.first().copied();
448
            chain.push(op);
449
        }
450
        chain.reverse();
451
        let mut new_parent: Option<ObjectRef> = None;
452
        for old in chain {
453
            let mut view = View::default();
454
            for (name, heads) in &old.view.bookmarks {
455
                view.bookmarks.insert(
456
                    name.clone(),
457
                    self.store.put_state(&StateObject::new(heads.clone()))?,
458
                );
459
            }
460
            view.workspaces = old.view.workspaces.clone();
461
            let op = Op {
462
                parents: new_parent.into_iter().collect(),
463
                hlc: old.hlc,
464
                command: old.command,
465
                view,
466
            };
467
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
468
        }
469
        write_atomic(
470
            &self.oxy.join("ops").join("head"),
471
            new_parent.unwrap().to_hex().as_bytes(),
472
        )?;
473
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
474
        Ok(())
475
    }
476
477
    /// Pack automatically once many loose objects have accumulated.
478
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
479
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
480
            self.store.pack_loose()?;
481
            self.store.merge_packs()?;
482
        }
483
        Ok(())
484
    }
485
486
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
487
    pub fn id(&self) -> Result<[u8; 16]> {
488
        if self.is_unbound() {
489
            return Ok([0; 16]);
490
        }
491
        let path = self.oxy.join("id");
492
        match fs::read_to_string(&path) {
493
            Ok(h) => hex::decode(h.trim())
494
                .ok()
495
                .and_then(|v| v.try_into().ok())
496
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
497
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
498
                let mut id = [0u8; 16];
499
                rand::rngs::OsRng.fill_bytes(&mut id);
500
                write_atomic(&path, hex::encode(id).as_bytes())?;
501
                Ok(id)
502
            }
503
            Err(e) => Err(e.into()),
504
        }
505
    }
506
507
    pub fn root(&self) -> &Path {
508
        &self.root
509
    }
510
    pub fn store(&self) -> &Store {
511
        &self.store
512
    }
513
    pub fn workspace(&self) -> WorkspaceId {
514
        self.workspace
515
    }
516
517
    /// Use a different user directory for keys and the user config file
518
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
519
    /// Act as if the working copy were on another platform's file system
520
    /// (tests of Windows and macOS behaviour on any host).
521
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
522
        self.platform = platform;
523
        self
524
    }
525
526
    pub fn platform(&self) -> crate::portable::Platform {
527
        self.platform
528
    }
529
530
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
531
        let dir = dir.into();
532
        self.keys_dir = dir.join("keys");
533
        self.user_config = dir.join("config.toml");
534
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
535
            self.config = c;
536
        }
537
        self.apply_workspace_bookmark();
538
        self
539
    }
540
541
    /// The workspace's current bookmark (spec §10.1) overrides the
542
    /// configured default when `oxy bookmark switch` has recorded one.
543
    fn apply_workspace_bookmark(&mut self) {
544
        if let Ok(b) = fs::read_to_string(
545
            self.oxy
546
                .join("workspaces")
547
                .join(self.workspace.to_hex())
548
                .join("bookmark"),
549
        ) {
550
            let b = b.trim();
551
            if !b.is_empty() {
552
                self.config.bookmark = b.to_string();
553
            }
554
        }
555
    }
556
557
    pub fn user_config_path(&self) -> &Path {
558
        &self.user_config
559
    }
560
561
    /// Set a key in the user file and refresh the effective configuration.
562
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
563
        Config::set_user(&self.user_config, key, value)?;
564
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
565
        Ok(())
566
    }
567
568
    pub fn save_config(&self) -> Result<()> {
569
        self.config.save(&self.oxy.join("config"))
570
    }
571
572
    fn author(&self) -> KeyId {
573
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
574
    }
575
}
576
577
impl Repo {
578
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
579
        let mut c = Change {
580
            version: crate::objects::CHANGE_VERSION,
581
            change_id: ChangeId::random(),
582
            deps,
583
            author: self.author(),
584
            hlc: Hlc::now(),
585
            message: message.into(),
586
            tree_ops: vec![],
587
            edits: vec![],
588
            kind: ChangeKind::WorkingCopy,
589
        };
590
        c.normalize();
591
        c
592
    }
593
594
    // ------------------------------------------------------------ operation log
595
596
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
597
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
598
        let r = ObjectRef::from_hex(hex.trim())
599
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
600
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
601
        Ok((r, op))
602
    }
603
604
    pub fn view(&self) -> Result<View> {
605
        Ok(self.head_op()?.1.view)
606
    }
607
608
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
609
        let op = Op {
610
            parents: parents.to_vec(),
611
            hlc: Hlc::now(),
612
            command: command.into(),
613
            view,
614
        };
615
        let r = self.store.put(ObjectType::Op, &op.encode())?;
616
        // The head is the commit point: everything it names must be on disk first.
617
        self.store.flush()?;
618
        // Compare and swap under a short lock (spec §12.1): when another
619
        // process recorded an operation since this one read the head, the
620
        // two are merged instead of one overwriting the other.
621
        let _lock = self.lock_ops()?;
622
        let current = match parents.first() {
623
            // The first operation (init): there is no head yet.
624
            None => None,
625
            Some(_) => Some(self.head_ref()?),
626
        };
627
        let Some(current) = current.filter(|c| Some(c) != parents.first()) else {
628
            write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?;
629
            return Ok(r);
630
        };
631
        let base = match parents.first() {
632
            Some(p) => Op::decode(&self.store.get_typed(p, ObjectType::Op)?)?.view,
633
            None => View::default(),
634
        };
635
        let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
636
        let merged = Op {
637
            parents: vec![current, r],
638
            hlc: Hlc::now(),
639
            command: format!("{command} (merged with a concurrent operation)"),
640
            view: self.merge_views(&base, &op.view, &theirs)?,
641
        };
642
        let m = self.store.put(ObjectType::Op, &merged.encode())?;
643
        self.store.flush()?;
644
        write_atomic(&self.oxy.join("ops").join("head"), m.to_hex().as_bytes())?;
645
        Ok(m)
646
    }
647
648
    /// The operation head's lock, held only while the head pointer moves.
649
    fn lock_ops(&self) -> Result<FileLock> {
650
        fs::create_dir_all(self.oxy.join("ops"))?;
651
        FileLock::acquire(
652
            self.oxy.join("ops").join("lock"),
653
            "another oxy process holds the operation log",
654
        )
655
    }
656
657
    fn head_ref(&self) -> Result<ObjectRef> {
658
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
659
        ObjectRef::from_hex(hex.trim())
660
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))
661
    }
662
663
    /// Three-way merge of two views that both started from `base` (spec
664
    /// §12.1). A reference only one side changed takes that side's value.
665
    /// When both changed it differently: a bookmark keeps both sides'
666
    /// heads (it may then have several), a change beats a deletion, a
667
    /// workspace changed by both is an error (only one of them matches the
668
    /// files on disk), and otherwise this process's value wins for remote
669
    /// references and the policy, the first value for a tag (tags never
670
    /// move).
671
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
672
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
673
            b: &BTreeMap<K, V>,
674
            o: &BTreeMap<K, V>,
675
            t: &BTreeMap<K, V>,
676
            mut both: impl FnMut(&V, &V) -> Result<V>,
677
        ) -> Result<BTreeMap<K, V>> {
678
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
679
            let mut out = BTreeMap::new();
680
            for k in keys {
681
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
682
                let v = if ov == tv || tv == bv {
683
                    ov.cloned()
684
                } else if ov == bv {
685
                    tv.cloned()
686
                } else {
687
                    match (ov, tv) {
688
                        (Some(x), Some(y)) => Some(both(x, y)?),
689
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
690
                        (None, None) => None,
691
                    }
692
                };
693
                if let Some(v) = v {
694
                    out.insert(k.clone(), v);
695
                }
696
            }
697
            Ok(out)
698
        }
699
        let bookmarks = pick(
700
            &base.bookmarks,
701
            &ours.bookmarks,
702
            &theirs.bookmarks,
703
            |x, y| {
704
                let mut heads = self.store.get_state(x)?.heads;
705
                heads.extend(self.store.get_state(y)?.heads);
706
                let heads = self.load_state(&heads)?.maximal(&heads);
707
                Ok(self.store.put_state(&StateObject::new(heads))?)
708
            },
709
        )?;
710
        // Two operations that both replaced one workspace's working copy
711
        // cannot both be right: the files on disk match only one of them.
712
        // The working-copy lock keeps this from happening; should it happen
713
        // anyway, this operation is not recorded.
714
        let workspaces = pick(
715
            &base.workspaces,
716
            &ours.workspaces,
717
            &theirs.workspaces,
718
            |_, _| {
719
                fail(
720
                    "another oxy process changed this working copy at the same time; \
721
                     this command was not recorded: check `oxy status` and run it again",
722
                )
723
            },
724
        )?;
725
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
726
        let empty = BTreeMap::new();
727
        let names: BTreeSet<&String> = base
728
            .remotes
729
            .keys()
730
            .chain(ours.remotes.keys())
731
            .chain(theirs.remotes.keys())
732
            .collect();
733
        let mut remotes = BTreeMap::new();
734
        for n in names {
735
            let m = pick(
736
                base.remotes.get(n).unwrap_or(&empty),
737
                ours.remotes.get(n).unwrap_or(&empty),
738
                theirs.remotes.get(n).unwrap_or(&empty),
739
                |x, _| Ok(*x),
740
            )?;
741
            if !m.is_empty() {
742
                remotes.insert(n.clone(), m);
743
            }
744
        }
745
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
746
            ours.policy
747
        } else if ours.policy == base.policy {
748
            theirs.policy
749
        } else {
750
            ours.policy.or(theirs.policy)
751
        };
752
        self.store.flush()?;
753
        Ok(View {
754
            bookmarks,
755
            workspaces,
756
            remotes,
757
            policy,
758
            tags,
759
        })
760
    }
761
762
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
763
        let mut out = Vec::new();
764
        let (mut r, mut op) = self.head_op()?;
765
        loop {
766
            let next = op.parents.first().copied();
767
            out.push((r, op));
768
            match next {
769
                Some(p) => {
770
                    r = p;
771
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
772
                }
773
                None => break,
774
            }
775
        }
776
        Ok(out)
777
    }
778
779
    /// Undo the last user command (spec §12.1). Operations that only recorded
780
    /// a working-copy snapshot are skipped, since the files are still on disk
781
    /// and the next snapshot recreates them.
782
    pub fn undo(&self) -> Result<Op> {
783
        let _wc = self.lock_working_copy()?;
784
        let (read_head, mut op) = self.head_op()?;
785
        while op.is_snapshot() {
786
            let Some(parent) = op.parents.first() else {
787
                break;
788
            };
789
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
790
        }
791
        let Some(parent) = op.parents.first() else {
792
            return fail("nothing to undo");
793
        };
794
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
795
        let _lock = self.lock_ops()?;
796
        if self.head_ref()? != read_head {
797
            return fail("another oxy command ran while undoing; run undo again");
798
        }
799
        write_atomic(
800
            &self.oxy.join("ops").join("head"),
801
            parent.to_hex().as_bytes(),
802
        )?;
803
        self.drop_manifest();
804
        Ok(parent_op)
805
    }
806
807
    /// The last operation that was not a snapshot.
808
    pub fn last_command(&self) -> Result<Op> {
809
        let (_, mut op) = self.head_op()?;
810
        while op.is_snapshot() {
811
            let Some(parent) = op.parents.first() else {
812
                break;
813
            };
814
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
815
        }
816
        Ok(op)
817
    }
818
819
    // ------------------------------------------------------------ states
820
821
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
822
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
823
        if let Some(st) = self.load_state_checkpointed(heads)? {
824
            return Ok(st);
825
        }
826
        self.load_state_full(heads)
827
    }
828
829
    /// The state of `heads` for its history (changes, tree, metadata) with
830
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
831
    /// and friends. Build the graphs a command needs with
832
    /// [`Repo::load_graphs_of`].
833
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
834
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
835
            return Ok(st);
836
        }
837
        self.load_state_replayed(heads, State::new_history_only())
838
    }
839
840
    /// Build these file graphs in a history-only state.
841
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
842
        Ok(state.load_graphs(
843
            nodes,
844
            |refs| {
845
                self.read_blobs(refs).map_err(|e| {
846
                    crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
847
                })
848
            },
849
            |h| self.change_bytes(h),
850
        )?)
851
    }
852
853
    /// Build every graph a history-only state still lacks, making it full.
854
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
855
        Ok(state.load_all_graphs(
856
            |refs| {
857
                self.read_blobs(refs).map_err(|e| {
858
                    crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
859
                })
860
            },
861
            |h| self.change_bytes(h),
862
        )?)
863
    }
864
865
    /// A change's encoding, for building graphs of its inline inserts. The
866
    /// last one read is kept: a checkout building graphs a batch at a time
867
    /// reads the same large change for every batch.
868
    fn change_bytes(
869
        &self,
870
        h: &ChangeHash,
871
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
872
        if let Some((k, b)) = &*self.last_change.borrow() {
873
            if k == h {
874
                return Ok(b.clone());
875
            }
876
        }
877
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
878
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
879
        })?);
880
        *self.last_change.borrow_mut() = Some((*h, b.clone()));
881
        Ok(b)
882
    }
883
884
    /// Load the dependency closure of `heads` change by change.
885
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
886
        self.load_state_replayed(heads, State::new())
887
    }
888
889
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
890
        let history = state.is_history_only();
891
        let mut stack: Vec<ChangeHash> = heads.to_vec();
892
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
893
        {
894
            let _t = crate::timing::phase("load: read and add changes");
895
            let (mut read, mut add) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
896
            while let Some(h) = stack.pop() {
897
                if !seen.insert(h) {
898
                    continue;
899
                }
900
                let t0 = std::time::Instant::now();
901
                // A history-only state reads text only for the graphs it
902
                // builds; either way the hash is the one asked for.
903
                let (c, texts) = if history {
904
                    self.store.get_change_lazy(&h)?
905
                } else {
906
                    (self.store.get_change(&h)?, Vec::new())
907
                };
908
                read += t0.elapsed();
909
                stack.extend(c.deps.iter().copied());
910
                let t1 = std::time::Instant::now();
911
                state.add_known(h, c, texts);
912
                add += t1.elapsed();
913
            }
914
            crate::timing::record("load:   of which reading", read);
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 under = path.strip_prefix(root).unwrap();
1214
                    // Already `/`-separated where that is the separator.
1215
                    let rel: String = match under.to_str() {
1216
                        Some(s) if std::path::MAIN_SEPARATOR == '/' => s.to_string(),
1217
                        _ => under
1218
                            .components()
1219
                            .map(|c| c.as_os_str().to_string_lossy().to_string())
1220
                            .collect::<Vec<_>>()
1221
                            .join("/"),
1222
                    };
1223
                    let Some(ft) = entry.file_type() else {
1224
                        return Ok(None);
1225
                    };
1226
                    if ft.is_dir() || !in_scope(&rel) {
1227
                        return Ok(None);
1228
                    }
1229
                    if ft.is_symlink() {
1230
                        let target = fs::read_link(path).map_err(|e| e.to_string())?;
1231
                        return Ok(Some(Found::Symlink(
1232
                            rel,
1233
                            target.to_string_lossy().as_bytes().to_vec(),
1234
                        )));
1235
                    }
1236
                    if ft.is_file() {
1237
                        let meta = entry.metadata().map_err(|e| e.to_string())?;
1238
                        return Ok(Some(Found::File(rel, path.to_path_buf(), meta)));
1239
                    }
1240
                    Ok(None)
1241
                };
1242
                match step() {
1243
                    Ok(Some(f)) => found.lock().unwrap().push(f),
1244
                    Ok(None) => {}
1245
                    Err(e) => {
1246
                        failed.lock().unwrap().get_or_insert(e);
1247
                        return WalkState::Quit;
1248
                    }
1249
                }
1250
                WalkState::Continue
1251
            })
1252
        });
1253
        if let Some(e) = failed.into_inner().unwrap() {
1254
            return fail(e);
1255
        }
1256
        let mut files: Vec<(String, PathBuf, fs::Metadata)> = Vec::new();
1257
        for f in found.into_inner().unwrap() {
1258
            match f {
1259
                Found::File(rel, path, meta) => files.push((rel, path, meta)),
1260
                Found::Symlink(rel, target) => {
1261
                    out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
1262
                }
1263
            }
1264
        }
1265
        let keys = keys.filter(|k| {
1266
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
1267
            let attrs_unchanged =
1268
                files
1269
                    .iter()
1270
                    .filter(|(r, _, _)| is_attributes(r))
1271
                    .all(|(rel, _, meta)| {
1272
                        stat_cached(rel, meta, cache)
1273
                            .is_some_and(|e| e.graph.is_some() && e.graph.as_ref() == k.get(rel))
1274
                    });
1275
            let none_removed = tracked
1276
                .keys()
1277
                .filter(|r| is_attributes(r))
1278
                .all(|r| on_disk.contains(r.as_str()));
1279
            attrs_unchanged && none_removed
1280
        });
1281
        // Reading files is most of a walk's cost; do it in parallel.
1282
        {
1283
            use rayon::prelude::*;
1284
            let read: Vec<(String, FsEntry)> = files
1285
                .par_iter()
1286
                .map(|(rel, path, meta)| {
1287
                    let key = keys
1288
                        .filter(|_| !is_attributes(rel))
1289
                        .and_then(|k| k.get(rel))
1290
                        .map(String::as_str);
1291
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
1292
                })
1293
                .collect::<Result<Vec<_>>>()?;
1294
            for (rel, mut e) in read {
1295
                // A cached blob the store lost (gc, a partial clone): read the file after all.
1296
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
1297
                    e.content = fs::read(self.root.join(&rel))?;
1298
                    e.blob = None;
1299
                }
1300
                out.insert(rel, e);
1301
            }
1302
        }
1303
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
1304
        // already tracked as subrepo nodes, they contribute their pin;
1305
        // unregistered ones are left alone.
1306
        let modules = self.modules_on_disk();
1307
        let removed = self.removed_subrepos();
1308
        for rel in &removed {
1309
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
1310
                self.clear_removed_subrepo(rel);
1311
            }
1312
        }
1313
        let nested_dirs = std::mem::take(&mut *nested.lock().unwrap());
1314
        for dir in nested_dirs {
1315
            let rel = self.rel_path(&dir);
1316
            if !self.in_scope(&rel) || removed.contains(&rel) {
1317
                continue;
1318
            }
1319
            let registered = modules.entries.get(&rel);
1320
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
1321
            {
1322
                continue;
1323
            }
1324
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
1325
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
1326
        }
1327
        // Tracked paths the ignore rules hid.
1328
        for (rel, (kind, blob)) in tracked {
1329
            if out.contains_key(rel) || !self.in_scope(rel) {
1330
                continue;
1331
            }
1332
            let path = self.root.join(rel);
1333
            if *kind == NodeKind::Subrepo {
1334
                if removed.contains(rel) {
1335
                    continue;
1336
                }
1337
                let present =
1338
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
1339
                if present {
1340
                    let pin = subrepos::read_pin(
1341
                        &path,
1342
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
1343
                    )?;
1344
                    out.insert(
1345
                        rel.clone(),
1346
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
1347
                    );
1348
                } else if let Some(b) = blob {
1349
                    // Not cloned (or emptied): the pin stays as recorded, as a
1350
                    // Git gitlink does when its directory is absent.
1351
                    out.insert(
1352
                        rel.clone(),
1353
                        FsEntry {
1354
                            blob: Some(*b),
1355
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
1356
                        },
1357
                    );
1358
                }
1359
                continue;
1360
            }
1361
            let Ok(meta) = fs::symlink_metadata(&path) else {
1362
                continue;
1363
            };
1364
            let ft = meta.file_type();
1365
            if ft.is_symlink() {
1366
                let target = fs::read_link(&path)?;
1367
                out.insert(
1368
                    rel.clone(),
1369
                    FsEntry::new(
1370
                        NodeKind::Symlink,
1371
                        false,
1372
                        target.to_string_lossy().as_bytes().to_vec(),
1373
                    ),
1374
                );
1375
            } else if ft.is_file() {
1376
                let e = self.file_entry(rel, &path, &meta, cache)?;
1377
                out.insert(rel.clone(), e);
1378
            }
1379
        }
1380
        Ok(out)
1381
    }
1382
1383
    /// The entry for one regular file, read or served from the stat cache.
1384
    fn file_entry(
1385
        &self,
1386
        rel: &str,
1387
        path: &Path,
1388
        meta: &fs::Metadata,
1389
        cache: Option<&prompt::Manifest>,
1390
    ) -> Result<FsEntry> {
1391
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
1392
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
1393
            e.content = fs::read(path)?;
1394
            e.blob = None;
1395
        }
1396
        Ok(e)
1397
    }
1398
1399
    /// The non-directory paths of a snapshot with their kinds, for the
1400
    /// walker's `tracked` set.
1401
    pub(crate) fn tracked_kinds(
1402
        snapshot: &Snapshot,
1403
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
1404
        snapshot
1405
            .files
1406
            .iter()
1407
            .filter(|(_, f)| f.kind != NodeKind::Dir)
1408
            .map(|(p, f)| {
1409
                let blob = match &f.content {
1410
                    FileContent::Opaque { blobs } => blobs.first().copied(),
1411
                    _ => None,
1412
                };
1413
                (p.clone(), (f.kind, blob))
1414
            })
1415
            .collect()
1416
    }
1417
1418
    /// A path under the root as a `/`-separated relative string.
1419
    pub(crate) fn rel_path(&self, path: &Path) -> String {
1420
        path.strip_prefix(&self.root)
1421
            .unwrap_or(path)
1422
            .components()
1423
            .map(|c| c.as_os_str().to_string_lossy().to_string())
1424
            .collect::<Vec<_>>()
1425
            .join("/")
1426
    }
1427
}
1428
1429
impl Repo {
1430
    /// Changes reachable from the bookmark and the working copy, newest first.
1431
    pub fn log(&self) -> Result<Vec<LogEntry>> {
1432
        let heads = self.bookmark_heads()?;
1433
        if self.bare {
1434
            return self.log_state(&heads);
1435
        }
1436
        let (wc_hash, _) = self.working_copy()?;
1437
        let mut all = heads.clone();
1438
        all.push(wc_hash);
1439
        let state = self.load_state_history(&all)?;
1440
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
1441
        let mut entries: Vec<LogEntry> = Vec::new();
1442
        for (h, meta) in state.changes() {
1443
            entries.push(LogEntry {
1444
                hash: *h,
1445
                change: meta.clone(),
1446
                is_working_copy: *h == wc_hash,
1447
                is_head: head_set.contains(h),
1448
            });
1449
        }
1450
        entries.sort_by(|a, b| {
1451
            b.is_working_copy
1452
                .cmp(&a.is_working_copy)
1453
                .then(b.change.hlc.cmp(&a.change.hlc))
1454
                .then(b.hash.cmp(&a.hash))
1455
        });
1456
        Ok(entries)
1457
    }
1458
1459
    /// A window of `log_state`: entries `offset..offset+limit` and the total
1460
    /// count, for paginated views.
1461
    pub fn log_window(
1462
        &self,
1463
        heads: &[ChangeHash],
1464
        offset: usize,
1465
        limit: usize,
1466
    ) -> Result<(Vec<LogEntry>, usize)> {
1467
        let all = self.log_state(heads)?;
1468
        let total = all.len();
1469
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
1470
    }
1471
1472
    /// The log of the state with these heads, newest first, with no working
1473
    /// copy involved (for hosted repositories and any explicit state).
1474
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1475
        // The log needs change metadata only: no file graph is built.
1476
        Ok(self.log_of(&self.load_state_history(heads)?))
1477
    }
1478
1479
    /// The log of a state already loaded, newest first.
1480
    /// The history of lines `first..=last` (1-based) of `path` in the
1481
    /// state `heads` make (spec §27): every change that inserted or
1482
    /// deleted one of their atoms, or an atom deleted from between them,
1483
    /// newest first. Exact, as atoms keep their identity across edits.
1484
    pub fn line_history(
1485
        &self,
1486
        heads: &[ChangeHash],
1487
        path: &str,
1488
        first: usize,
1489
        last: usize,
1490
    ) -> Result<Vec<LogEntry>> {
1491
        if first == 0 || last < first {
1492
            return fail(format!(
1493
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
1494
            ));
1495
        }
1496
        let mut state = self.load_state_history(heads)?;
1497
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
1498
            return fail(format!("{path} is not in that state"));
1499
        };
1500
        self.load_graphs_of(&mut state, &[node])?;
1501
        let live = state.live_lines(&node);
1502
        if last > live.len() {
1503
            return fail(format!(
1504
                "{path} has {} lines; asked for {first},{last}",
1505
                live.len()
1506
            ));
1507
        }
1508
        let Some(g) = state.file(&node) else {
1509
            return fail(format!("{path} is not a text file"));
1510
        };
1511
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
1512
        let touched = g.touching(&atoms);
1513
        Ok(self
1514
            .log_of(&state)
1515
            .into_iter()
1516
            .filter(|e| touched.contains(&e.hash))
1517
            .collect())
1518
    }
1519
1520
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
1521
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
1522
        let mut entries: Vec<LogEntry> = state
1523
            .changes()
1524
            .map(|(h, meta)| LogEntry {
1525
                hash: *h,
1526
                change: meta.clone(),
1527
                is_working_copy: false,
1528
                is_head: head_set.contains(h),
1529
            })
1530
            .collect();
1531
        entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
1532
        entries
1533
    }
1534
1535
    /// Resolve a spec to a set of heads: a tag name, the current bookmark's
1536
    /// name, or a single change (`resolve_change`).
1537
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
1538
        let view = self.view()?;
1539
        if let Some(st) = view.bookmarks.get(spec) {
1540
            return Ok(self.store.get_state(st)?.heads);
1541
        }
1542
        if let Some(heads) = self.tag_heads(spec)? {
1543
            return Ok(heads);
1544
        }
1545
        Ok(vec![self.resolve_change(spec)?])
1546
    }
1547
1548
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
1549
    /// copy), bookmark or tag (the one head of its state).
1550
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
1551
        if spec == "@" {
1552
            return Ok(self.working_copy()?.0);
1553
        }
1554
        let named = match self.view()?.bookmarks.get(spec) {
1555
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
1556
            None => self.tag_heads(spec)?.map(|h| ("tag", h)),
1557
        };
1558
        if let Some((kind, heads)) = named {
1559
            return match heads.len() {
1560
                1 => Ok(heads[0]),
1561
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
1562
            };
1563
        }
1564
        if spec.is_empty() || spec == "#" {
1565
            return fail("empty change specifier");
1566
        }
1567
        let entries = self.log()?;
1568
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
1569
            entries
1570
                .iter()
1571
                .filter(|e| e.hash.starts_with_hex(hp))
1572
                .collect()
1573
        } else {
1574
            entries
1575
                .iter()
1576
                .filter(|e| e.change.change_id.starts_with_hex(spec))
1577
                .collect()
1578
        };
1579
        match matches.len() {
1580
            1 => Ok(matches[0].hash),
1581
            0 => fail(format!("no change matches {spec:?}")),
1582
            _ => {
1583
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
1584
                if ids.len() == 1 {
1585
                    fail(format!(
1586
                        "change {spec} is divergent: {} variants",
1587
                        matches.len()
1588
                    ))
1589
                } else {
1590
                    fail(format!("{spec:?} is ambiguous"))
1591
                }
1592
            }
1593
        }
1594
    }
1595
1596
    /// Human-readable description of what a change does, with line content.
1597
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
1598
        let change = self.store.get_change(hash)?;
1599
        let (base, base_snapshot) = self.change_base(&change)?;
1600
        Ok(render_change(&change, &base, &base_snapshot))
1601
    }
1602
1603
    /// The base state of `change` (its dependencies) and its rendering, as
1604
    /// much as showing the change needs: the whole tree, and the graphs and
1605
    /// contents of the files the change edits. Other text files are left
1606
    /// unrendered ([`Snapshot::unrendered`]).
1607
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
1608
        let mut base = self.load_state_history(&change.deps)?;
1609
        let edited: std::collections::HashSet<NodeId> =
1610
            change.edits.iter().map(|e| e.node()).collect();
1611
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
1612
        self.load_graphs_of(&mut base, &nodes)?;
1613
        let skip: std::collections::HashSet<NodeId> = base
1614
            .tree()
1615
            .view()
1616
            .entries
1617
            .values()
1618
            .filter(|e| e.kind == crate::objects::NodeKind::File && !edited.contains(&e.node))
1619
            .map(|e| e.node)
1620
            .collect();
1621
        let snapshot = base.materialize_except(&skip);
1622
        Ok((base, snapshot))
1623
    }
1624
}
1625
1626
fn remove_any(path: &Path) -> std::io::Result<()> {
1627
    let m = fs::symlink_metadata(path)?;
1628
    if m.is_dir() {
1629
        fs::remove_dir_all(path)
1630
    } else {
1631
        fs::remove_file(path)
1632
    }
1633
}
1634
1635
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
1636
    let mut perms = fs::metadata(path)?.permissions();
1637
    perms.set_readonly(readonly);
1638
    fs::set_permissions(path, perms)
1639
}
1640
1641
#[cfg(unix)]
1642
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
1643
    use std::os::unix::fs::PermissionsExt;
1644
    let mut perms = fs::metadata(path)?.permissions();
1645
    let mode = perms.mode();
1646
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
1647
    if want != mode {
1648
        perms.set_mode(want);
1649
        fs::set_permissions(path, perms)?;
1650
    }
1651
    Ok(())
1652
}
1653
#[cfg(not(unix))]
1654
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
1655
    Ok(())
1656
}
1657
1658
#[cfg(unix)]
1659
fn is_executable(m: &fs::Metadata) -> bool {
1660
    use std::os::unix::fs::PermissionsExt;
1661
    m.permissions().mode() & 0o111 != 0
1662
}
1663
#[cfg(not(unix))]
1664
fn is_executable(_m: &fs::Metadata) -> bool {
1665
    false
1666
}
1667
1668
fn op_ref(k: OpKey) -> OpRef {
1669
    OpRef {
1670
        change: k.0,
1671
        index: k.1,
1672
    }
1673
}
1674
1675
fn split_path(path: &str) -> (&str, &str) {
1676
    match path.rfind('/') {
1677
        Some(i) => (&path[..i], &path[i + 1..]),
1678
        None => ("", path),
1679
    }
1680
}
1681
1682
/// Whether `rel` is an attributes file (spec §7.6).
1683
fn is_attributes(rel: &str) -> bool {
1684
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
1685
}
1686
1687
/// The manifest entry for `rel` when its size and mtime match it outside
1688
/// the racy window.
1689
fn stat_cached<'m>(
1690
    rel: &str,
1691
    meta: &fs::Metadata,
1692
    cache: Option<&'m prompt::Manifest>,
1693
) -> Option<&'m prompt::ManifestEntry> {
1694
    let m = cache?;
1695
    let e = m.entries.get(rel)?;
1696
    let mtime_ns = prompt::mtime_ns(meta);
1697
    let racy = mtime_ns + 2_000_000_000 >= m.written_ns;
1698
    (e.size == meta.len() && e.mtime_ns == mtime_ns && !racy).then_some(e)
1699
}
1700
1701
/// Read one working-copy file, or serve it from the stat cache (spec
1702
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
1703
/// an opaque file is not read at all (its stored blob stands in), and a
1704
/// text file the manifest recorded equal to a base graph whose key is
1705
/// `key`, the key the base has now, is not read either: equal keys mean
1706
/// equal renderings, so it still equals the base. Touches no repository
1707
/// state, so the walk runs it in parallel; the caller checks that a cached
1708
/// blob is still in the store.
1709
fn read_file_entry(
1710
    rel: &str,
1711
    path: &Path,
1712
    meta: &fs::Metadata,
1713
    cache: Option<&prompt::Manifest>,
1714
    key: Option<&str>,
1715
) -> Result<FsEntry> {
1716
    let exec = is_executable(meta);
1717
    let stat = Some((meta.len(), prompt::mtime_ns(meta)));
1718
    let mut e = match stat_cached(rel, meta, cache) {
1719
        Some(e) if e.blob.is_some() => FsEntry {
1720
            blob: e.blob,
1721
            content_hash: Some(e.hash.clone()),
1722
            ..FsEntry::new(NodeKind::File, exec, vec![])
1723
        },
1724
        Some(e) if key.is_some() && e.graph.as_deref() == key => FsEntry {
1725
            content_hash: Some(e.hash.clone()),
1726
            unchanged: true,
1727
            graph_key: e.graph.clone(),
1728
            ..FsEntry::new(NodeKind::File, exec, vec![])
1729
        },
1730
        Some(e) => FsEntry {
1731
            content_hash: Some(e.hash.clone()),
1732
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
1733
        },
1734
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
1735
    };
1736
    // The stat the manifest records: taken before the read, so a file that
1737
    // changes meanwhile is read again next time.
1738
    e.stat = stat;
1739
    Ok(e)
1740
}