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