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