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