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