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