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