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