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