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