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