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