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