OXYGENHUB
# 4dcb8c0916b7 oxygen / crates / oxy-core / src / repo / mod.rs
43.1 KiB · Rust · last changed Crash safety: durable writes and the op head as commit point 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};
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 fsck;
66
mod gc;
67
mod git;
68
mod history;
69
mod hooks;
70
mod hosted;
71
mod identity;
72
mod inspect;
73
mod policy;
74
mod prompt;
75
mod snapshot;
76
mod subrepos;
77
mod sync;
78
mod tags;
79
#[cfg(test)]
80
mod tests;
81
mod workspace;
82
83
pub use bookmarks::{BookmarkInfo, MergeReport};
84
pub use checkout::CheckoutReport;
85
pub use config::{parse_size, read_config_file, Config};
86
pub use fsck::{FsckReport, Problem, Severity};
87
pub use gc::GcReport;
88
pub use git::{GitExportReport, GitImportReport};
89
pub use hooks::{json_array, json_str, HookOutcome};
90
pub use hosted::FileEdit;
91
pub use identity::{Rotation, SignatureStatus};
92
pub use inspect::{BisectStep, BlameLine};
93
pub use policy::PolicyUpdate;
94
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
95
pub use snapshot::{
96
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
97
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
98
    Selection, SnapshotResult,
99
};
100
pub use subrepos::{SubrepoInfo, SubrepoSync};
101
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated};
102
pub use tags::TagInfo;
103
pub use workspace::{SnapshotLock, WorkspaceInfo};
104
105
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
106
    Ok(crate::durable::write_atomic(path, data)?)
107
}
108
109
pub struct LogEntry {
110
    pub hash: ChangeHash,
111
    /// Metadata from the state; the full change may be absent in a shallow repository.
112
    pub change: crate::state::ChangeMeta,
113
    pub is_working_copy: bool,
114
    pub is_head: bool,
115
}
116
117
/// A file as found on disk or in an imported tree.
118
pub(crate) struct FsEntry {
119
    pub kind: NodeKind,
120
    pub exec: bool,
121
    /// File content, or a symlink's target. Empty when `blob` is set.
122
    pub content: Vec<u8>,
123
    /// The stored blob of an opaque file whose size and mtime are unchanged
124
    /// since the last manifest (spec §12.3 stat cache); the content was not
125
    /// read.
126
    pub blob: Option<ObjectRef>,
127
    /// BLAKE3 of the content, carried over from the manifest when the stat
128
    /// is unchanged, so the manifest can be rewritten without rehashing.
129
    pub content_hash: Option<String>,
130
}
131
132
impl FsEntry {
133
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
134
        FsEntry {
135
            kind,
136
            exec,
137
            content,
138
            blob: None,
139
            content_hash: None,
140
        }
141
    }
142
}
143
144
pub struct Repo {
145
    /// Oxygen-pinned subrepos skipped by the running Git export.
146
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
147
    root: PathBuf,
148
    oxy: PathBuf,
149
    store: Store,
150
    workspace: WorkspaceId,
151
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
152
    bare: bool,
153
    keys_dir: PathBuf,
154
    user_config: PathBuf,
155
    pub config: Config,
156
}
157
158
/// Marker file of a bare repository, inside `.oxy/`.
159
const BARE_MARKER: &str = "bare";
160
/// Marker of a hosted repository that has no id yet: the first push binds
161
/// it to the pusher's id (spec §16.1).
162
const UNBOUND_MARKER: &str = "unbound";
163
164
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
165
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
166
pub fn default_home() -> PathBuf {
167
    if let Ok(h) = std::env::var("OXY_HOME") {
168
        return PathBuf::from(h);
169
    }
170
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
171
        return PathBuf::from(x).join("oxy");
172
    }
173
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
174
    PathBuf::from(home).join(".config").join("oxy")
175
}
176
177
pub fn default_keys_dir() -> PathBuf {
178
    default_home().join("keys")
179
}
180
181
pub fn default_user_config() -> PathBuf {
182
    default_home().join("config.toml")
183
}
184
185
/// Where `create_identity` records the author.
186
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
187
pub enum IdentityScope {
188
    /// The user file: every repository of this user signs with it.
189
    User,
190
    /// This repository only.
191
    Repo,
192
}
193
194
impl Repo {
195
    // ------------------------------------------------------------ lifecycle
196
197
    pub fn init(root: &Path) -> Result<Repo> {
198
        let mut id = [0u8; 16];
199
        rand::rngs::OsRng.fill_bytes(&mut id);
200
        Self::init_with_id(root, id)
201
    }
202
203
    /// Initialize a repository with a given repository ID (clones share the
204
    /// ID of their origin, spec §14.4).
205
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
206
        fs::create_dir_all(root)?;
207
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
208
        let oxy = root.join(OXY_DIR);
209
        if oxy.exists() {
210
            return fail(format!("{} is already an oxy repository", root.display()));
211
        }
212
        fs::create_dir_all(oxy.join("ops"))?;
213
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
214
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
215
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
216
        config.save(&oxy.join("config"))?;
217
        let workspace = WorkspaceId::random();
218
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
219
        let store = Store::open(oxy.join("objects"))?;
220
        let repo = Repo {
221
            git_export_skipped: Default::default(),
222
            root,
223
            oxy,
224
            store,
225
            workspace,
226
            bare: false,
227
            keys_dir: default_keys_dir(),
228
            user_config: default_user_config(),
229
            config,
230
        };
231
        repo.register_workspace(&workspace, &repo.root)?;
232
233
        let wc = repo.new_working_copy(vec![], "");
234
        let wc_hash = repo.store.put_change(&wc)?;
235
        let mut view = View::default();
236
        view.bookmarks.insert(
237
            repo.config.bookmark.clone(),
238
            repo.store.put_state(&StateObject::new(vec![]))?,
239
        );
240
        view.workspaces.insert(workspace, wc_hash);
241
        repo.record_op(&[], "oxy init", view)?;
242
        Ok(repo)
243
    }
244
245
    /// Create a bare repository: an object store, operation log and
246
    /// references with no workspace and no working copy, for hosting
247
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
248
    pub fn init_bare(root: &Path) -> Result<Repo> {
249
        let mut id = [0u8; 16];
250
        rand::rngs::OsRng.fill_bytes(&mut id);
251
        Self::init_bare_with_id(root, id)
252
    }
253
254
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
255
        fs::create_dir_all(root)?;
256
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
257
        let oxy = root.join(OXY_DIR);
258
        if oxy.exists() {
259
            return fail(format!("{} is already an oxy repository", root.display()));
260
        }
261
        fs::create_dir_all(oxy.join("ops"))?;
262
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
263
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
264
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
265
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
266
        config.save(&oxy.join("config"))?;
267
        let store = Store::open(oxy.join("objects"))?;
268
        let repo = Repo {
269
            git_export_skipped: Default::default(),
270
            root,
271
            oxy,
272
            store,
273
            workspace: WorkspaceId::ZERO,
274
            bare: true,
275
            keys_dir: default_keys_dir(),
276
            user_config: default_user_config(),
277
            config,
278
        };
279
        let mut view = View::default();
280
        view.bookmarks.insert(
281
            repo.config.bookmark.clone(),
282
            repo.store.put_state(&StateObject::new(vec![]))?,
283
        );
284
        repo.record_op(&[], "oxy init --bare", view)?;
285
        Ok(repo)
286
    }
287
288
    /// A bare repository with no id yet. Its `id()` is all zero until the
289
    /// first push binds it (`bind_id`), so an existing repository can be
290
    /// pushed to a freshly created hosted one and keep its identity.
291
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
292
        let repo = Self::init_bare_with_id(root, [0; 16])?;
293
        fs::remove_file(repo.oxy.join("id"))?;
294
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
295
        Ok(repo)
296
    }
297
298
    pub fn is_unbound(&self) -> bool {
299
        self.oxy.join(UNBOUND_MARKER).is_file()
300
    }
301
302
    /// Give an unbound repository its id.
303
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
304
        if !self.is_unbound() {
305
            return fail("this repository already has an id");
306
        }
307
        if id == [0; 16] {
308
            return fail("a repository id cannot be all zero");
309
        }
310
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
311
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
312
        Ok(())
313
    }
314
315
    /// Whether this repository has no working copy (`init_bare`).
316
    pub fn is_bare(&self) -> bool {
317
        self.bare
318
    }
319
320
    /// Open the repository containing `start` (searching upwards).
321
    pub fn open(start: &Path) -> Result<Repo> {
322
        let start = start.canonicalize()?;
323
        let mut dir: Option<&Path> = Some(&start);
324
        while let Some(d) = dir {
325
            let oxy = d.join(OXY_DIR);
326
            if oxy.is_file() {
327
                // A secondary workspace (spec §12.2): the file points at the repository.
328
                let text = fs::read_to_string(&oxy)?;
329
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
330
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
331
                };
332
                let format = fs::read_to_string(shared.join("format"))?;
333
                if format != FORMAT_LINE {
334
                    return fail(format!("unsupported repository format: {}", format.trim()));
335
                }
336
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
337
                let store = Store::open(shared.join("objects"))?;
338
                let mut repo = Repo {
339
                    git_export_skipped: Default::default(),
340
                    root: d.to_path_buf(),
341
                    oxy: shared,
342
                    store,
343
                    workspace,
344
                    bare: false,
345
                    keys_dir: default_keys_dir(),
346
                    user_config: default_user_config(),
347
                    config,
348
                };
349
                repo.apply_workspace_bookmark();
350
                return Ok(repo);
351
            }
352
            if oxy.is_dir() {
353
                let format = fs::read_to_string(oxy.join("format"))?;
354
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
355
                let bare = oxy.join(BARE_MARKER).is_file();
356
                let workspace = if bare {
357
                    WorkspaceId::ZERO
358
                } else {
359
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
360
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
361
                };
362
                let store = Store::open(oxy.join("objects"))?;
363
                let mut repo = Repo {
364
                    git_export_skipped: Default::default(),
365
                    root: d.to_path_buf(),
366
                    oxy,
367
                    store,
368
                    workspace,
369
                    bare,
370
                    keys_dir: default_keys_dir(),
371
                    user_config: default_user_config(),
372
                    config,
373
                };
374
                if !bare {
375
                    repo.apply_workspace_bookmark();
376
                }
377
                if format == FORMAT1_LINE {
378
                    repo.migrate_format1()?;
379
                } else if format != FORMAT_LINE {
380
                    return fail(format!("unsupported repository format: {}", format.trim()));
381
                }
382
                return Ok(repo);
383
            }
384
            dir = d.parent();
385
        }
386
        fail(format!(
387
            "no oxy repository found at or above {}",
388
            start.display()
389
        ))
390
    }
391
392
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
393
    /// into format 2, where each bookmark names a `state` object.
394
    fn migrate_format1(&self) -> Result<()> {
395
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
396
        let head = ObjectRef::from_hex(hex.trim())
397
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
398
        // Collect the chain root-first.
399
        let mut chain: Vec<Format1Op> = Vec::new();
400
        let mut cur = Some(head);
401
        while let Some(r) = cur {
402
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
403
            cur = op.parents.first().copied();
404
            chain.push(op);
405
        }
406
        chain.reverse();
407
        let mut new_parent: Option<ObjectRef> = None;
408
        for old in chain {
409
            let mut view = View::default();
410
            for (name, heads) in &old.view.bookmarks {
411
                view.bookmarks.insert(
412
                    name.clone(),
413
                    self.store.put_state(&StateObject::new(heads.clone()))?,
414
                );
415
            }
416
            view.workspaces = old.view.workspaces.clone();
417
            let op = Op {
418
                parents: new_parent.into_iter().collect(),
419
                hlc: old.hlc,
420
                command: old.command,
421
                view,
422
            };
423
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
424
        }
425
        write_atomic(
426
            &self.oxy.join("ops").join("head"),
427
            new_parent.unwrap().to_hex().as_bytes(),
428
        )?;
429
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
430
        Ok(())
431
    }
432
433
    /// Pack automatically once many loose objects have accumulated.
434
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
435
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
436
            self.store.pack_loose()?;
437
            self.store.merge_packs()?;
438
        }
439
        Ok(())
440
    }
441
442
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
443
    pub fn id(&self) -> Result<[u8; 16]> {
444
        if self.is_unbound() {
445
            return Ok([0; 16]);
446
        }
447
        let path = self.oxy.join("id");
448
        match fs::read_to_string(&path) {
449
            Ok(h) => hex::decode(h.trim())
450
                .ok()
451
                .and_then(|v| v.try_into().ok())
452
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
453
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
454
                let mut id = [0u8; 16];
455
                rand::rngs::OsRng.fill_bytes(&mut id);
456
                write_atomic(&path, hex::encode(id).as_bytes())?;
457
                Ok(id)
458
            }
459
            Err(e) => Err(e.into()),
460
        }
461
    }
462
463
    pub fn root(&self) -> &Path {
464
        &self.root
465
    }
466
    pub fn store(&self) -> &Store {
467
        &self.store
468
    }
469
    pub fn workspace(&self) -> WorkspaceId {
470
        self.workspace
471
    }
472
473
    /// Use a different user directory for keys and the user config file
474
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
475
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
476
        let dir = dir.into();
477
        self.keys_dir = dir.join("keys");
478
        self.user_config = dir.join("config.toml");
479
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
480
            self.config = c;
481
        }
482
        self.apply_workspace_bookmark();
483
        self
484
    }
485
486
    /// The workspace's current bookmark (spec §10.1) overrides the
487
    /// configured default when `oxy bookmark switch` has recorded one.
488
    fn apply_workspace_bookmark(&mut self) {
489
        if let Ok(b) = fs::read_to_string(
490
            self.oxy
491
                .join("workspaces")
492
                .join(self.workspace.to_hex())
493
                .join("bookmark"),
494
        ) {
495
            let b = b.trim();
496
            if !b.is_empty() {
497
                self.config.bookmark = b.to_string();
498
            }
499
        }
500
    }
501
502
    pub fn user_config_path(&self) -> &Path {
503
        &self.user_config
504
    }
505
506
    /// Set a key in the user file and refresh the effective configuration.
507
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
508
        Config::set_user(&self.user_config, key, value)?;
509
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
510
        Ok(())
511
    }
512
513
    pub fn save_config(&self) -> Result<()> {
514
        self.config.save(&self.oxy.join("config"))
515
    }
516
517
    fn author(&self) -> KeyId {
518
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
519
    }
520
}
521
522
impl Repo {
523
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
524
        let mut c = Change {
525
            change_id: ChangeId::random(),
526
            deps,
527
            author: self.author(),
528
            hlc: Hlc::now(),
529
            message: message.into(),
530
            tree_ops: vec![],
531
            edits: vec![],
532
            kind: ChangeKind::WorkingCopy,
533
        };
534
        c.normalize();
535
        c
536
    }
537
538
    // ------------------------------------------------------------ operation log
539
540
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
541
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
542
        let r = ObjectRef::from_hex(hex.trim())
543
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
544
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
545
        Ok((r, op))
546
    }
547
548
    pub fn view(&self) -> Result<View> {
549
        Ok(self.head_op()?.1.view)
550
    }
551
552
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
553
        let op = Op {
554
            parents: parents.to_vec(),
555
            hlc: Hlc::now(),
556
            command: command.into(),
557
            view,
558
        };
559
        let r = self.store.put(ObjectType::Op, &op.encode())?;
560
        // The head is the commit point: everything it names must be on disk first.
561
        self.store.flush()?;
562
        write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?;
563
        Ok(r)
564
    }
565
566
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
567
        let mut out = Vec::new();
568
        let (mut r, mut op) = self.head_op()?;
569
        loop {
570
            let next = op.parents.first().copied();
571
            out.push((r, op));
572
            match next {
573
                Some(p) => {
574
                    r = p;
575
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
576
                }
577
                None => break,
578
            }
579
        }
580
        Ok(out)
581
    }
582
583
    /// Undo the last user command (spec §12.1). Operations that only recorded
584
    /// a working-copy snapshot are skipped, since the files are still on disk
585
    /// and the next snapshot recreates them.
586
    pub fn undo(&self) -> Result<Op> {
587
        let (_, mut op) = self.head_op()?;
588
        while op.is_snapshot() {
589
            let Some(parent) = op.parents.first() else {
590
                break;
591
            };
592
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
593
        }
594
        let Some(parent) = op.parents.first() else {
595
            return fail("nothing to undo");
596
        };
597
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
598
        write_atomic(
599
            &self.oxy.join("ops").join("head"),
600
            parent.to_hex().as_bytes(),
601
        )?;
602
        self.drop_manifest();
603
        Ok(parent_op)
604
    }
605
606
    /// The last operation that was not a snapshot.
607
    pub fn last_command(&self) -> Result<Op> {
608
        let (_, mut op) = self.head_op()?;
609
        while op.is_snapshot() {
610
            let Some(parent) = op.parents.first() else {
611
                break;
612
            };
613
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
614
        }
615
        Ok(op)
616
    }
617
618
    // ------------------------------------------------------------ states
619
620
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
621
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
622
        if let Some(st) = self.load_state_checkpointed(heads)? {
623
            return Ok(st);
624
        }
625
        self.load_state_full(heads)
626
    }
627
628
    /// Load the dependency closure of `heads` change by change.
629
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
630
        let mut state = State::new();
631
        let mut stack: Vec<ChangeHash> = heads.to_vec();
632
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
633
        while let Some(h) = stack.pop() {
634
            if !seen.insert(h) {
635
                continue;
636
            }
637
            let c = self.store.get_change(&h)?;
638
            stack.extend(c.deps.iter().copied());
639
            state.add_unchecked(c);
640
        }
641
        state.validate()?;
642
        Ok(state)
643
    }
644
645
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
646
        if self.bare {
647
            return fail("this is a bare repository: it has no working copy");
648
        }
649
        let view = self.view()?;
650
        let h = *view
651
            .workspaces
652
            .get(&self.workspace)
653
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
654
        Ok((h, self.store.get_change(&h)?))
655
    }
656
657
    /// Heads of a bookmark's state (spec §10.1).
658
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
659
        match view.bookmarks.get(bookmark) {
660
            Some(st) => Ok(self.store.get_state(st)?.heads),
661
            None => Ok(vec![]),
662
        }
663
    }
664
665
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
666
        self.heads_of(&self.view()?, &self.config.bookmark)
667
    }
668
669
    // ------------------------------------------------------------ blobs
670
671
    fn blob_for(content: &[u8]) -> Blob {
672
        Blob {
673
            length: content.len() as u64,
674
            chunks: crate::chunk::chunks(content)
675
                .into_iter()
676
                .map(|c| hash_object(ObjectType::Chunk, c))
677
                .collect(),
678
        }
679
    }
680
681
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
682
        Self::blob_for(content).hash()
683
    }
684
685
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
686
        for c in crate::chunk::chunks(content) {
687
            self.store.put_chunk(c)?;
688
        }
689
        Ok(self
690
            .store
691
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
692
    }
693
694
    /// Read a blob's content, fetching it from the remote that withheld it
695
    /// when it is lazily absent (spec §13.5).
696
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
697
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
698
            self.fetch_lazy_blob(r)?;
699
        }
700
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
701
        let mut out = Vec::with_capacity(blob.length as usize);
702
        for c in &blob.chunks {
703
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
704
        }
705
        Ok(out)
706
    }
707
708
    // ------------------------------------------------------------ working copy
709
710
    /// Attributes from the `.oxyattributes` files in the working directory.
711
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
712
        let mut files: Vec<(String, Vec<u8>)> = Vec::new();
713
        if let Ok(b) = fs::read(self.root.join(".oxyattributes")) {
714
            files.push((".oxyattributes".into(), b));
715
        }
716
        let mut wb = ignore::WalkBuilder::new(&self.root);
717
        wb.hidden(false)
718
            .git_ignore(false)
719
            .git_global(false)
720
            .git_exclude(false)
721
            .require_git(false)
722
            .follow_links(false)
723
            .add_custom_ignore_filename(".oxyignore");
724
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
725
        for entry in wb.build().flatten() {
726
            if entry.file_name() == ".oxyattributes"
727
                && entry.path() != self.root.join(".oxyattributes")
728
            {
729
                if let Ok(b) = fs::read(entry.path()) {
730
                    let rel: String = entry
731
                        .path()
732
                        .strip_prefix(&self.root)
733
                        .unwrap()
734
                        .components()
735
                        .map(|c| c.as_os_str().to_string_lossy().to_string())
736
                        .collect::<Vec<_>>()
737
                        .join("/");
738
                    files.push((rel, b));
739
                }
740
            }
741
        }
742
        crate::attributes::Attributes::from_files(
743
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
744
        )
745
    }
746
747
    /// Attributes from a materialized state's `.oxyattributes` files.
748
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
749
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
750
            match &f.content {
751
                FileContent::Text { bytes, .. }
752
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
753
                {
754
                    Some((p.as_str(), bytes.as_slice()))
755
                }
756
                _ => None,
757
            }
758
        }))
759
    }
760
761
    /// Store a blob, raw when the path is `nocompress`.
762
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
763
        if !nocompress {
764
            return self.store_blob(content);
765
        }
766
        for c in crate::chunk::chunks(content) {
767
            self.store.put_chunk_nocompress(c)?;
768
        }
769
        Ok(self
770
            .store
771
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
772
    }
773
774
    fn locks_dir(&self) -> PathBuf {
775
        self.oxy.join("locks")
776
    }
777
778
    /// Whether `path` is locked locally for editing (spec §18, advisory).
779
    pub fn is_locked(&self, path: &str) -> bool {
780
        self.locks_dir().join(path.replace('/', "%2F")).exists()
781
    }
782
783
    /// Take the advisory local lock on a `lockable` file and make it writable.
784
    pub fn lock_path(&self, path: &str) -> Result<()> {
785
        let attrs = self.disk_attributes();
786
        if !attrs.lookup(path).lockable {
787
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
788
        }
789
        fs::create_dir_all(self.locks_dir())?;
790
        write_atomic(
791
            &self.locks_dir().join(path.replace('/', "%2F")),
792
            std::process::id().to_string().as_bytes(),
793
        )?;
794
        set_readonly(&self.root.join(path), false)?;
795
        Ok(())
796
    }
797
798
    /// Release the local lock and make the file read-only again.
799
    pub fn unlock_path(&self, path: &str) -> Result<()> {
800
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
801
        if self.root.join(path).exists() {
802
            set_readonly(&self.root.join(path), true)?;
803
        }
804
        Ok(())
805
    }
806
807
    /// Whether a repository path is inside the sparse filter (spec §17).
808
    pub fn in_scope(&self, path: &str) -> bool {
809
        self.config.sparse_paths.is_empty()
810
            || self
811
                .config
812
                .sparse_paths
813
                .iter()
814
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
815
    }
816
817
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
818
        self.walk_working_copy_with(None, &BTreeMap::new())
819
    }
820
821
    /// A walker over the working copy that never enters a nested repository
822
    /// (a directory below the root holding `.oxy` or `.git`); the directories
823
    /// it skipped are collected into `nested`.
824
    pub(crate) fn walker(
825
        &self,
826
        nested: &std::sync::Arc<std::sync::Mutex<Vec<PathBuf>>>,
827
    ) -> ignore::WalkBuilder {
828
        let mut wb = ignore::WalkBuilder::new(&self.root);
829
        wb.hidden(false)
830
            .git_ignore(false)
831
            .git_global(false)
832
            .git_exclude(false)
833
            .require_git(false)
834
            .follow_links(false)
835
            .add_custom_ignore_filename(".oxyignore");
836
        let nested = nested.clone();
837
        wb.filter_entry(move |e| {
838
            if e.file_name() == OXY_DIR {
839
                return false;
840
            }
841
            if e.depth() > 0
842
                && e.file_type().is_some_and(|t| t.is_dir())
843
                && (e.path().join(OXY_DIR).exists() || e.path().join(".git").exists())
844
            {
845
                nested.lock().unwrap().push(e.path().to_path_buf());
846
                return false;
847
            }
848
            true
849
        });
850
        wb
851
    }
852
853
    /// Walk the working copy; with a manifest, a file whose size and mtime
854
    /// match it is not read: an opaque file yields its known blob, a text
855
    /// file is read but keeps its known hash. Files modified within two
856
    /// seconds of the manifest are never trusted (a racy stat).
857
    ///
858
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
859
    /// (the base state's files) that exists on disk is included even when
860
    /// an ignore rule matches it, as in Git.
861
    fn walk_working_copy_with(
862
        &self,
863
        cache: Option<&prompt::Manifest>,
864
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
865
    ) -> Result<BTreeMap<String, FsEntry>> {
866
        let nested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
867
        let wb = self.walker(&nested);
868
        let mut out = BTreeMap::new();
869
        for entry in wb.build() {
870
            let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?;
871
            let path = entry.path();
872
            if path == self.root {
873
                continue;
874
            }
875
            let rel = path.strip_prefix(&self.root).unwrap();
876
            let rel: String = rel
877
                .components()
878
                .map(|c| c.as_os_str().to_string_lossy().to_string())
879
                .collect::<Vec<_>>()
880
                .join("/");
881
            let Some(ft) = entry.file_type() else {
882
                continue;
883
            };
884
            if ft.is_dir() || !self.in_scope(&rel) {
885
                continue;
886
            }
887
            if ft.is_symlink() {
888
                let target = fs::read_link(path)?;
889
                out.insert(
890
                    rel,
891
                    FsEntry::new(
892
                        NodeKind::Symlink,
893
                        false,
894
                        target.to_string_lossy().as_bytes().to_vec(),
895
                    ),
896
                );
897
            } else if ft.is_file() {
898
                let meta = entry
899
                    .metadata()
900
                    .map_err(|e| RepoError::Msg(e.to_string()))?;
901
                let e = self.file_entry(&rel, path, &meta, cache)?;
902
                out.insert(rel, e);
903
            }
904
        }
905
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
906
        // already tracked as subrepo nodes, they contribute their pin;
907
        // unregistered ones are left alone.
908
        let modules = self.modules_on_disk();
909
        let removed = self.removed_subrepos();
910
        for rel in &removed {
911
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
912
                self.clear_removed_subrepo(rel);
913
            }
914
        }
915
        let nested_dirs = std::mem::take(&mut *nested.lock().unwrap());
916
        for dir in nested_dirs {
917
            let rel = self.rel_path(&dir);
918
            if !self.in_scope(&rel) || removed.contains(&rel) {
919
                continue;
920
            }
921
            let registered = modules.entries.get(&rel);
922
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
923
            {
924
                continue;
925
            }
926
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
927
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
928
        }
929
        // Tracked paths the ignore rules hid.
930
        for (rel, (kind, blob)) in tracked {
931
            if out.contains_key(rel) || !self.in_scope(rel) {
932
                continue;
933
            }
934
            let path = self.root.join(rel);
935
            if *kind == NodeKind::Subrepo {
936
                if removed.contains(rel) {
937
                    continue;
938
                }
939
                let present =
940
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
941
                if present {
942
                    let pin = subrepos::read_pin(
943
                        &path,
944
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
945
                    )?;
946
                    out.insert(
947
                        rel.clone(),
948
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
949
                    );
950
                } else if let Some(b) = blob {
951
                    // Not cloned (or emptied): the pin stays as recorded, as a
952
                    // Git gitlink does when its directory is absent.
953
                    out.insert(
954
                        rel.clone(),
955
                        FsEntry {
956
                            kind: NodeKind::Subrepo,
957
                            exec: false,
958
                            content: vec![],
959
                            blob: Some(*b),
960
                            content_hash: None,
961
                        },
962
                    );
963
                }
964
                continue;
965
            }
966
            let Ok(meta) = fs::symlink_metadata(&path) else {
967
                continue;
968
            };
969
            let ft = meta.file_type();
970
            if ft.is_symlink() {
971
                let target = fs::read_link(&path)?;
972
                out.insert(
973
                    rel.clone(),
974
                    FsEntry::new(
975
                        NodeKind::Symlink,
976
                        false,
977
                        target.to_string_lossy().as_bytes().to_vec(),
978
                    ),
979
                );
980
            } else if ft.is_file() {
981
                let e = self.file_entry(rel, &path, &meta, cache)?;
982
                out.insert(rel.clone(), e);
983
            }
984
        }
985
        Ok(out)
986
    }
987
988
    /// The entry for one regular file, read or served from the stat cache.
989
    fn file_entry(
990
        &self,
991
        rel: &str,
992
        path: &Path,
993
        meta: &fs::Metadata,
994
        cache: Option<&prompt::Manifest>,
995
    ) -> Result<FsEntry> {
996
        let exec = is_executable(meta);
997
        let cached = cache.and_then(|m| {
998
            let e = m.entries.get(rel)?;
999
            let mtime_ns = prompt::mtime_ns(meta);
1000
            let racy = mtime_ns + 2_000_000_000 >= m.written_ns;
1001
            (e.size == meta.len() && e.mtime_ns == mtime_ns && !racy).then_some(e)
1002
        });
1003
        Ok(match cached {
1004
            Some(e) if e.blob.is_some_and(|b| self.store.has(&b)) => FsEntry {
1005
                kind: NodeKind::File,
1006
                exec,
1007
                content: vec![],
1008
                blob: e.blob,
1009
                content_hash: Some(e.hash.clone()),
1010
            },
1011
            Some(e) => FsEntry {
1012
                kind: NodeKind::File,
1013
                exec,
1014
                content: fs::read(path)?,
1015
                blob: None,
1016
                content_hash: Some(e.hash.clone()),
1017
            },
1018
            None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
1019
        })
1020
    }
1021
1022
    /// The non-directory paths of a snapshot with their kinds, for the
1023
    /// walker's `tracked` set.
1024
    pub(crate) fn tracked_kinds(
1025
        snapshot: &Snapshot,
1026
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
1027
        snapshot
1028
            .files
1029
            .iter()
1030
            .filter(|(_, f)| f.kind != NodeKind::Dir)
1031
            .map(|(p, f)| {
1032
                let blob = match &f.content {
1033
                    FileContent::Opaque { blobs } => blobs.first().copied(),
1034
                    _ => None,
1035
                };
1036
                (p.clone(), (f.kind, blob))
1037
            })
1038
            .collect()
1039
    }
1040
1041
    /// A path under the root as a `/`-separated relative string.
1042
    pub(crate) fn rel_path(&self, path: &Path) -> String {
1043
        path.strip_prefix(&self.root)
1044
            .unwrap_or(path)
1045
            .components()
1046
            .map(|c| c.as_os_str().to_string_lossy().to_string())
1047
            .collect::<Vec<_>>()
1048
            .join("/")
1049
    }
1050
}
1051
1052
impl Repo {
1053
    /// Changes reachable from the bookmark and the working copy, newest first.
1054
    pub fn log(&self) -> Result<Vec<LogEntry>> {
1055
        let heads = self.bookmark_heads()?;
1056
        if self.bare {
1057
            return self.log_state(&heads);
1058
        }
1059
        let (wc_hash, _) = self.working_copy()?;
1060
        let mut all = heads.clone();
1061
        all.push(wc_hash);
1062
        let state = self.load_state(&all)?;
1063
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
1064
        let mut entries: Vec<LogEntry> = Vec::new();
1065
        for (h, meta) in state.changes() {
1066
            entries.push(LogEntry {
1067
                hash: *h,
1068
                change: meta.clone(),
1069
                is_working_copy: *h == wc_hash,
1070
                is_head: head_set.contains(h),
1071
            });
1072
        }
1073
        entries.sort_by(|a, b| {
1074
            b.is_working_copy
1075
                .cmp(&a.is_working_copy)
1076
                .then(b.change.hlc.cmp(&a.change.hlc))
1077
                .then(b.hash.cmp(&a.hash))
1078
        });
1079
        Ok(entries)
1080
    }
1081
1082
    /// The log of the state with these heads, newest first, with no working
1083
    /// copy involved (for hosted repositories and any explicit state).
1084
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1085
        let state = self.load_state(heads)?;
1086
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
1087
        let mut entries: Vec<LogEntry> = state
1088
            .changes()
1089
            .map(|(h, meta)| LogEntry {
1090
                hash: *h,
1091
                change: meta.clone(),
1092
                is_working_copy: false,
1093
                is_head: head_set.contains(h),
1094
            })
1095
            .collect();
1096
        entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
1097
        Ok(entries)
1098
    }
1099
1100
    /// Resolve a spec to a set of heads: a tag name, the current bookmark's
1101
    /// name, or a single change (`resolve_change`).
1102
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
1103
        let view = self.view()?;
1104
        if let Some(st) = view.bookmarks.get(spec) {
1105
            return Ok(self.store.get_state(st)?.heads);
1106
        }
1107
        if let Some(heads) = self.tag_heads(spec)? {
1108
            return Ok(heads);
1109
        }
1110
        Ok(vec![self.resolve_change(spec)?])
1111
    }
1112
1113
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working copy), or bookmark.
1114
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
1115
        if spec == "@" {
1116
            return Ok(self.working_copy()?.0);
1117
        }
1118
        if let Some(st) = self.view()?.bookmarks.get(spec) {
1119
            let heads = self.store.get_state(st)?.heads;
1120
            return match heads.len() {
1121
                1 => Ok(heads[0]),
1122
                n => fail(format!("bookmark {spec} has {n} heads; name a change, or use it where a state is expected")),
1123
            };
1124
        }
1125
        if spec.is_empty() || spec == "#" {
1126
            return fail("empty change specifier");
1127
        }
1128
        let entries = self.log()?;
1129
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
1130
            entries
1131
                .iter()
1132
                .filter(|e| e.hash.starts_with_hex(hp))
1133
                .collect()
1134
        } else {
1135
            entries
1136
                .iter()
1137
                .filter(|e| e.change.change_id.starts_with_hex(spec))
1138
                .collect()
1139
        };
1140
        match matches.len() {
1141
            1 => Ok(matches[0].hash),
1142
            0 => fail(format!("no change matches {spec:?}")),
1143
            _ => {
1144
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
1145
                if ids.len() == 1 {
1146
                    fail(format!(
1147
                        "change {spec} is divergent: {} variants",
1148
                        matches.len()
1149
                    ))
1150
                } else {
1151
                    fail(format!("{spec:?} is ambiguous"))
1152
                }
1153
            }
1154
        }
1155
    }
1156
1157
    /// Human-readable description of what a change does, with line content.
1158
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
1159
        let change = self.store.get_change(hash)?;
1160
        let base = self.load_state(&change.deps)?;
1161
        let base_snapshot = base.materialize();
1162
        Ok(render_change(&change, &base, &base_snapshot))
1163
    }
1164
}
1165
1166
fn remove_any(path: &Path) -> std::io::Result<()> {
1167
    let m = fs::symlink_metadata(path)?;
1168
    if m.is_dir() {
1169
        fs::remove_dir_all(path)
1170
    } else {
1171
        fs::remove_file(path)
1172
    }
1173
}
1174
1175
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
1176
    let mut perms = fs::metadata(path)?.permissions();
1177
    perms.set_readonly(readonly);
1178
    fs::set_permissions(path, perms)
1179
}
1180
1181
#[cfg(unix)]
1182
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
1183
    use std::os::unix::fs::PermissionsExt;
1184
    let mut perms = fs::metadata(path)?.permissions();
1185
    let mode = perms.mode();
1186
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
1187
    if want != mode {
1188
        perms.set_mode(want);
1189
        fs::set_permissions(path, perms)?;
1190
    }
1191
    Ok(())
1192
}
1193
#[cfg(not(unix))]
1194
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
1195
    Ok(())
1196
}
1197
1198
#[cfg(unix)]
1199
fn is_executable(m: &fs::Metadata) -> bool {
1200
    use std::os::unix::fs::PermissionsExt;
1201
    m.permissions().mode() & 0o111 != 0
1202
}
1203
#[cfg(not(unix))]
1204
fn is_executable(_m: &fs::Metadata) -> bool {
1205
    false
1206
}
1207
1208
fn op_ref(k: OpKey) -> OpRef {
1209
    OpRef {
1210
        change: k.0,
1211
        index: k.1,
1212
    }
1213
}
1214
1215
fn split_path(path: &str) -> (&str, &str) {
1216
    match path.rfind('/') {
1217
        Some(i) => (&path[..i], &path[i + 1..]),
1218
        None => ("", path),
1219
    }
1220
}