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