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