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