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