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