OXYGENHUB
# 530a0fc650a2 oxygen / crates / oxy-core / src / repo / mod.rs
104.6 KiB · Rust · last changed undo: this workspace's last command, saying what it undid 26 days 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::{
14
    verify as verify_signature, Delegate, Domain, Identity, Scope, SecretKey, Signature,
15
};
16
use crate::ids::{ChangeId, NodeId, WorkspaceId};
17
use crate::objects::{
18
    Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp,
19
};
20
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
21
use crate::protocol::{
22
    open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef,
23
    SignedAttest, SignedPolicy,
24
};
25
use crate::state::{FileContent, Snapshot, State};
26
use crate::store::{Store, StoreError};
27
#[allow(unused_imports)]
28
use crate::subrepo::Pin;
29
use crate::tree::OpKey;
30
use rand::RngCore;
31
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
32
use std::fs;
33
use std::io::Write;
34
use std::path::{Path, PathBuf};
35
36
pub const OXY_DIR: &str = ".oxy";
37
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
38
const FORMAT1_LINE: &str = "oxy repository format 1\n";
39
const BINARY_SNIFF: usize = 8 * 1024;
40
/// Loose objects tolerated before a commit packs them (spec §13.4).
41
pub const AUTOPACK_THRESHOLD: usize = 4096;
42
43
#[derive(Debug, thiserror::Error)]
44
pub enum RepoError {
45
    #[error("io: {0}")]
46
    Io(#[from] std::io::Error),
47
    #[error(transparent)]
48
    Store(#[from] StoreError),
49
    #[error(transparent)]
50
    Object(#[from] crate::objects::ObjectError),
51
    #[error(transparent)]
52
    State(#[from] crate::state::StateError),
53
    #[error("{0}")]
54
    Msg(String),
55
    /// The operation would leave a conflict where none may be (a rebased
56
    /// change cannot hold one); the caller may offer another way.
57
    #[error("{0}")]
58
    Conflicted(String),
59
}
60
61
pub type Result<T> = std::result::Result<T, RepoError>;
62
63
/// The operation head's reference record on a store that is not this
64
/// disk's directory (oxygen#68).
65
pub const HEAD_RECORD: &str = "ops/head";
66
67
/// How often recording an operation reads the head again when other
68
/// processes keep moving it.
69
const HEAD_TRIES: usize = 8;
70
71
/// The object store of the repository directory `oxy`: `.oxy/objects`,
72
/// or the store `storage.url` names behind a cache of `storage.cache`
73
/// bytes in `.oxy/cache` (oxygen#68). `.oxy/objects` is then only
74
/// scratch space: packs being written, and derived caches.
75
fn open_objects(oxy: &Path, config: &Config) -> Result<Store> {
76
    let Some(url) = &config.storage_url else {
77
        return Ok(Store::open(oxy.join("objects"))?);
78
    };
79
    let options = crate::protocol::RemoteOptions {
80
        cache_dir: Some(oxy.join("cache")),
81
        ..Default::default()
82
    };
83
    let remote = crate::protocol::open_store(url, &options)
84
        .ok_or_else(|| {
85
            RepoError::Msg(format!(
86
                "storage.url {url}: this oxy cannot open that kind of store (dir://, or s3://, gs:// and az:// in builds with cloud stores)"
87
            ))
88
        })?
89
        .map_err(|e| RepoError::Msg(format!("open the repository's store {url}: {e}")))?;
90
    let cached = crate::strata::CachingStore::open(
91
        std::sync::Arc::from(remote),
92
        oxy.join("cache"),
93
        config.storage_cache,
94
    )
95
    .map_err(|e| RepoError::Msg(format!("open the cache for {url}: {e}")))?;
96
    Ok(Store::open_on(
97
        std::sync::Arc::new(cached),
98
        oxy.join("objects"),
99
    )?)
100
}
101
102
fn fail<T>(s: impl Into<String>) -> Result<T> {
103
    Err(RepoError::Msg(s.into()))
104
}
105
106
mod bookmarks;
107
mod checkout;
108
mod checkpoint;
109
mod config;
110
mod doctor;
111
mod fsck;
112
mod gc;
113
mod git;
114
mod history;
115
mod hooks;
116
mod hosted;
117
mod identity;
118
mod inspect;
119
mod ops;
120
mod policy;
121
mod prompt;
122
mod receipts;
123
mod revset;
124
mod snapshot;
125
pub mod strata;
126
mod subrepos;
127
mod sync;
128
mod tags;
129
#[cfg(test)]
130
mod tests;
131
mod touched;
132
mod walk;
133
mod workspace;
134
135
pub use bookmarks::{remote_bookmark, BookmarkInfo, MergeReport, RemoteOnlyBookmark, StateGap};
136
pub use checkout::CheckoutReport;
137
pub use config::{parse_size, read_config_file, Config};
138
pub use doctor::{Check, DoctorReport, Health};
139
pub use fsck::{FsckReport, Problem, Severity};
140
pub use gc::GcReport;
141
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
142
pub use hooks::{json_array, json_str, HookOutcome};
143
pub use hosted::FileEdit;
144
pub use identity::{Rotation, SignatureStatus};
145
pub use inspect::{BisectStep, BlameLine, Description};
146
pub use ops::{RestoreReport, RevertReport, Undone, ViewChange};
147
pub use policy::PolicyUpdate;
148
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
149
pub use receipts::ReceiptInfo;
150
pub use revset::{Revset, REVSET_BUDGET};
151
pub use snapshot::{
152
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
153
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
154
    Selection, SnapshotResult,
155
};
156
pub use subrepos::{SubrepoInfo, SubrepoSync};
157
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated, OBJECTS_RESULT};
158
pub use tags::TagInfo;
159
pub use workspace::{FileLock, SnapshotLock, WorkingCopyLock, WorkspaceInfo};
160
161
/// The file name under which per-bookmark or per-tag data is kept: `/`
162
/// (and `%`) escaped, so `feature/x` is one file beside `feature` rather
163
/// than a directory that would clash with it.
164
pub(crate) fn name_file(name: &str) -> String {
165
    name.replace('%', "%25").replace('/', "%2F")
166
}
167
168
/// The name a [`name_file`] file name stands for.
169
pub(crate) fn file_name_to_name(file: &str) -> String {
170
    file.replace("%2F", "/").replace("%25", "%")
171
}
172
173
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
174
    Ok(crate::durable::write_atomic(path, data)?)
175
}
176
177
/// Replace a cache file: whole or not at all, but without waiting for the
178
/// disk. A cache checks its own bytes when read, so one a crash leaves
179
/// short or stale is rebuilt rather than trusted.
180
/// How many changes a state index may fall behind its working copy before
181
/// it is written again; until then each load replays them.
182
const INDEX_REPLAY_LIMIT: usize = 16;
183
/// The changes whose encodings are kept for building graphs: a batch of
184
/// files often takes inline text from a few changes in turn.
185
const CHANGE_CACHE_COUNT: usize = 4;
186
const CHANGE_CACHE_BYTES: usize = 512 << 20;
187
/// How many state indexes a workspace keeps.
188
const STATE_INDEXES_KEPT: usize = 2;
189
const INDEX_REPLAY_TIME: std::time::Duration = std::time::Duration::from_millis(50);
190
191
pub(crate) fn write_cache(path: &Path, data: &[u8]) -> Result<()> {
192
    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
193
    fs::write(&tmp, data)?;
194
    fs::rename(&tmp, path)?;
195
    Ok(())
196
}
197
198
pub struct LogEntry {
199
    pub hash: ChangeHash,
200
    /// Metadata from the state; the full change may be absent in a shallow repository.
201
    pub change: crate::state::ChangeMeta,
202
    pub is_working_copy: bool,
203
    pub is_head: bool,
204
}
205
206
/// A text file's base graph key, by path, as a walk asks for it.
207
pub(crate) type KeyOf<'a> = dyn Fn(&str) -> Option<[u8; 32]> + Sync + 'a;
208
209
/// A file as found on disk or in an imported tree.
210
#[derive(Clone)]
211
pub(crate) struct FsEntry {
212
    pub kind: NodeKind,
213
    pub exec: bool,
214
    /// File content, or a symlink's target. Empty when `blob` is set.
215
    /// Shared, so a new file's insert holds it without a copy.
216
    pub content: std::sync::Arc<Vec<u8>>,
217
    /// The stored blob of an opaque file whose size and mtime are unchanged
218
    /// since the last manifest (spec §12.3 stat cache); the content was not
219
    /// read.
220
    pub blob: Option<ObjectRef>,
221
    /// BLAKE3 of the content, carried over from the manifest when the stat
222
    /// is unchanged, so the manifest can be rewritten without rehashing.
223
    pub content_hash: Option<[u8; 32]>,
224
    /// A text file known equal to the base's rendering without reading it:
225
    /// its stat matches the manifest and the manifest recorded it equal to
226
    /// a base file graph with the same key (spec §12.3). `content` is empty.
227
    pub unchanged: bool,
228
    /// The base graph key this file equals, for the next manifest.
229
    pub graph_key: Option<[u8; 32]>,
230
    /// Size and mtime already known to be current (a checkout leaving the
231
    /// file as it was), so the manifest need not stat it again.
232
    pub stat: Option<(u64, u128)>,
233
}
234
235
impl FsEntry {
236
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
237
        FsEntry {
238
            kind,
239
            exec,
240
            content: std::sync::Arc::new(content),
241
            blob: None,
242
            content_hash: None,
243
            unchanged: false,
244
            graph_key: None,
245
            stat: None,
246
        }
247
    }
248
}
249
250
pub struct Repo {
251
    /// Oxygen-pinned subrepos skipped by the running Git export.
252
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
253
    /// The manifest as last read, with the file identity it was read from,
254
    /// so one command parses it once (see `read_manifest`).
255
    pub(crate) manifest_cache: std::cell::RefCell<Option<prompt::CachedManifest>>,
256
    /// A listing of the working copy left by a failed clean check, for the
257
    /// snapshot that follows it to reuse; taken by the next walk and
258
    /// dropped whenever the manifest is written.
259
    pub(crate) listing_cache: std::cell::RefCell<Option<walk::Listing>>,
260
    /// The nested repositories the last walk left out, being neither
261
    /// registered nor tracked subrepos (oxygen#43).
262
    pub(crate) untracked_nested: std::cell::RefCell<Vec<String>>,
263
    root: PathBuf,
264
    oxy: PathBuf,
265
    store: Store,
266
    workspace: WorkspaceId,
267
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
268
    bare: bool,
269
    keys_dir: PathBuf,
270
    user_config: PathBuf,
271
    pub config: Config,
272
    /// What the working copy's file system can represent (spec §7.7).
273
    platform: crate::portable::Platform,
274
    /// The encodings of the changes last read for their inline inserts,
275
    /// oldest first.
276
    last_change: std::cell::RefCell<Vec<(ChangeHash, std::sync::Arc<Vec<u8>>)>>,
277
    /// `--at-op`: read the repository as it was after this operation;
278
    /// recording an operation is refused.
279
    at_op: Option<ObjectRef>,
280
    /// The directories (with their times) and nested repositories of the
281
    /// last walk, for the manifest written from it.
282
    pub(crate) walked_dirs: std::cell::RefCell<Option<WalkedDirs>>,
283
    /// The directories a manifest check listed, for its restamp only.
284
    pub(crate) listed_dirs: std::cell::RefCell<Option<WalkedDirs>>,
285
}
286
287
/// A walk's directories with their times, and its nested repositories.
288
pub(crate) type WalkedDirs = (Vec<(String, u128)>, Vec<String>);
289
290
/// Marker file of a bare repository, inside `.oxy/`.
291
const BARE_MARKER: &str = "bare";
292
/// Marker of a hosted repository that has no id yet: the first push binds
293
/// it to the pusher's id (spec §16.1).
294
const UNBOUND_MARKER: &str = "unbound";
295
296
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
297
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
298
pub fn default_home() -> PathBuf {
299
    if let Ok(h) = std::env::var("OXY_HOME") {
300
        return PathBuf::from(h);
301
    }
302
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
303
        return PathBuf::from(x).join("oxy");
304
    }
305
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
306
    PathBuf::from(home).join(".config").join("oxy")
307
}
308
309
pub fn default_keys_dir() -> PathBuf {
310
    default_home().join("keys")
311
}
312
313
pub fn default_user_config() -> PathBuf {
314
    default_home().join("config.toml")
315
}
316
317
/// Where `create_identity` records the author.
318
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
319
pub enum IdentityScope {
320
    /// The user file: every repository of this user signs with it.
321
    User,
322
    /// This repository only.
323
    Repo,
324
}
325
326
impl Repo {
327
    // ------------------------------------------------------------ lifecycle
328
329
    pub fn init(root: &Path) -> Result<Repo> {
330
        let mut id = [0u8; 16];
331
        rand::rngs::OsRng.fill_bytes(&mut id);
332
        Self::init_with_id(root, id)
333
    }
334
335
    /// Initialize a repository with a given repository ID (clones share the
336
    /// ID of their origin, spec §14.4).
337
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
338
        Self::init_on(root, id, None)
339
    }
340
341
    /// A new repository with a fresh id, bare or not, on `storage` or in
342
    /// `.oxy/objects` (`oxy init [--bare] [--store URL]`).
343
    pub fn init_new(root: &Path, bare: bool, storage: Option<&str>) -> Result<Repo> {
344
        let mut id = [0u8; 16];
345
        rand::rngs::OsRng.fill_bytes(&mut id);
346
        if bare {
347
            Self::init_bare_on(root, id, storage)
348
        } else {
349
            Self::init_on(root, id, storage)
350
        }
351
    }
352
353
    /// Initialize a repository whose objects and operation head are kept
354
    /// on the store at `storage` (`storage.url`), or in `.oxy/objects`.
355
    pub fn init_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
356
        fs::create_dir_all(root)?;
357
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
358
        let oxy = root.join(OXY_DIR);
359
        if oxy.exists() {
360
            return fail(format!("{} is already an oxy repository", root.display()));
361
        }
362
        fs::create_dir_all(oxy.join("ops"))?;
363
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
364
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
365
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
366
        if let Some(url) = storage {
367
            config.set("storage.url", url)?;
368
        }
369
        config.save(&oxy.join("config"))?;
370
        let workspace = WorkspaceId::random();
371
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
372
        let store = open_objects(&oxy, &config)?;
373
        let repo = Repo {
374
            last_change: Default::default(),
375
            at_op: None,
376
            walked_dirs: Default::default(),
377
            listed_dirs: Default::default(),
378
            git_export_skipped: Default::default(),
379
            manifest_cache: Default::default(),
380
            listing_cache: Default::default(),
381
            untracked_nested: Default::default(),
382
            root,
383
            oxy,
384
            store,
385
            workspace,
386
            bare: false,
387
            keys_dir: default_keys_dir(),
388
            platform: crate::portable::Platform::current(),
389
            user_config: default_user_config(),
390
            config,
391
        };
392
        repo.register_workspace(&workspace, &repo.root)?;
393
394
        let wc = repo.new_working_copy(vec![], "");
395
        let wc_hash = repo.store.put_change(&wc)?;
396
        let mut view = View::default();
397
        view.bookmarks.insert(
398
            repo.config.bookmark.clone(),
399
            repo.store.put_state(&StateObject::new(vec![]))?,
400
        );
401
        view.workspaces.insert(workspace, wc_hash);
402
        repo.record_op(&[], "oxy init", view)?;
403
        Ok(repo)
404
    }
405
406
    /// Create a bare repository: an object store, operation log and
407
    /// references with no workspace and no working copy, for hosting
408
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
409
    pub fn init_bare(root: &Path) -> Result<Repo> {
410
        let mut id = [0u8; 16];
411
        rand::rngs::OsRng.fill_bytes(&mut id);
412
        Self::init_bare_with_id(root, id)
413
    }
414
415
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
416
        Self::init_bare_on(root, id, None)
417
    }
418
419
    /// [`Repo::init_on`] for a bare repository.
420
    pub fn init_bare_on(root: &Path, id: [u8; 16], storage: Option<&str>) -> Result<Repo> {
421
        fs::create_dir_all(root)?;
422
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
423
        let oxy = root.join(OXY_DIR);
424
        if oxy.exists() {
425
            return fail(format!("{} is already an oxy repository", root.display()));
426
        }
427
        fs::create_dir_all(oxy.join("ops"))?;
428
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
429
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
430
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
431
        let mut config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
432
        if let Some(url) = storage {
433
            config.set("storage.url", url)?;
434
        }
435
        config.save(&oxy.join("config"))?;
436
        let store = open_objects(&oxy, &config)?;
437
        let repo = Repo {
438
            last_change: Default::default(),
439
            at_op: None,
440
            walked_dirs: Default::default(),
441
            listed_dirs: Default::default(),
442
            git_export_skipped: Default::default(),
443
            manifest_cache: Default::default(),
444
            listing_cache: Default::default(),
445
            untracked_nested: Default::default(),
446
            root,
447
            oxy,
448
            store,
449
            workspace: WorkspaceId::ZERO,
450
            bare: true,
451
            keys_dir: default_keys_dir(),
452
            platform: crate::portable::Platform::current(),
453
            user_config: default_user_config(),
454
            config,
455
        };
456
        let mut view = View::default();
457
        view.bookmarks.insert(
458
            repo.config.bookmark.clone(),
459
            repo.store.put_state(&StateObject::new(vec![]))?,
460
        );
461
        repo.record_op(&[], "oxy init --bare", view)?;
462
        Ok(repo)
463
    }
464
465
    /// A bare repository with no id yet. Its `id()` is all zero until the
466
    /// first push binds it (`bind_id`), so an existing repository can be
467
    /// pushed to a freshly created hosted one and keep its identity.
468
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
469
        let repo = Self::init_bare_with_id(root, [0; 16])?;
470
        fs::remove_file(repo.oxy.join("id"))?;
471
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
472
        Ok(repo)
473
    }
474
475
    pub fn is_unbound(&self) -> bool {
476
        self.oxy.join(UNBOUND_MARKER).is_file()
477
    }
478
479
    /// Give an unbound repository its id.
480
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
481
        if !self.is_unbound() {
482
            return fail("this repository already has an id");
483
        }
484
        if id == [0; 16] {
485
            return fail("a repository id cannot be all zero");
486
        }
487
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
488
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
489
        Ok(())
490
    }
491
492
    /// Whether this repository has no working copy (`init_bare`).
493
    pub fn is_bare(&self) -> bool {
494
        self.bare
495
    }
496
497
    /// Open the repository containing `start` (searching upwards).
498
    pub fn open(start: &Path) -> Result<Repo> {
499
        let start = start.canonicalize()?;
500
        let mut dir: Option<&Path> = Some(&start);
501
        while let Some(d) = dir {
502
            let oxy = d.join(OXY_DIR);
503
            if oxy.is_file() {
504
                // A secondary workspace (spec §12.2): the file points at the repository.
505
                let text = fs::read_to_string(&oxy)?;
506
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
507
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
508
                };
509
                let format = fs::read_to_string(shared.join("format"))?;
510
                if format != FORMAT_LINE {
511
                    return fail(format!("unsupported repository format: {}", format.trim()));
512
                }
513
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
514
                let store = open_objects(&shared, &config)?;
515
                let mut repo = Repo {
516
                    last_change: Default::default(),
517
                    at_op: None,
518
                    walked_dirs: Default::default(),
519
                    listed_dirs: Default::default(),
520
                    git_export_skipped: Default::default(),
521
                    manifest_cache: Default::default(),
522
                    listing_cache: Default::default(),
523
                    untracked_nested: Default::default(),
524
                    root: d.to_path_buf(),
525
                    oxy: shared,
526
                    store,
527
                    workspace,
528
                    bare: false,
529
                    keys_dir: default_keys_dir(),
530
                    platform: crate::portable::Platform::current(),
531
                    user_config: default_user_config(),
532
                    config,
533
                };
534
                repo.apply_workspace_bookmark();
535
                return Ok(repo);
536
            }
537
            if oxy.is_dir() {
538
                let format = fs::read_to_string(oxy.join("format"))?;
539
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
540
                let bare = oxy.join(BARE_MARKER).is_file();
541
                let workspace = if bare {
542
                    WorkspaceId::ZERO
543
                } else {
544
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
545
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
546
                };
547
                let store = open_objects(&oxy, &config)?;
548
                let mut repo = Repo {
549
                    last_change: Default::default(),
550
                    at_op: None,
551
                    walked_dirs: Default::default(),
552
                    listed_dirs: Default::default(),
553
                    git_export_skipped: Default::default(),
554
                    manifest_cache: Default::default(),
555
                    listing_cache: Default::default(),
556
                    untracked_nested: Default::default(),
557
                    root: d.to_path_buf(),
558
                    oxy,
559
                    store,
560
                    workspace,
561
                    bare,
562
                    keys_dir: default_keys_dir(),
563
                    platform: crate::portable::Platform::current(),
564
                    user_config: default_user_config(),
565
                    config,
566
                };
567
                if !bare {
568
                    repo.apply_workspace_bookmark();
569
                }
570
                if format == FORMAT1_LINE {
571
                    repo.migrate_format1()?;
572
                } else if format != FORMAT_LINE {
573
                    return fail(format!("unsupported repository format: {}", format.trim()));
574
                }
575
                return Ok(repo);
576
            }
577
            dir = d.parent();
578
        }
579
        fail(format!(
580
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
581
            start.display()
582
        ))
583
    }
584
585
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
586
    /// into format 2, where each bookmark names a `state` object.
587
    fn migrate_format1(&self) -> Result<()> {
588
        let (head, version) = self.read_head()?;
589
        // Collect the chain root-first.
590
        let mut chain: Vec<Format1Op> = Vec::new();
591
        let mut cur = Some(head);
592
        while let Some(r) = cur {
593
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
594
            cur = op.parents.first().copied();
595
            chain.push(op);
596
        }
597
        chain.reverse();
598
        let mut new_parent: Option<ObjectRef> = None;
599
        for old in chain {
600
            let mut view = View::default();
601
            for (name, heads) in &old.view.bookmarks {
602
                view.bookmarks.insert(
603
                    name.clone(),
604
                    self.store.put_state(&StateObject::new(heads.clone()))?,
605
                );
606
            }
607
            view.workspaces = old.view.workspaces.clone();
608
            let op = Op {
609
                parents: new_parent.into_iter().collect(),
610
                hlc: old.hlc,
611
                command: old.command,
612
                view,
613
                workspace: None,
614
                undoes: None,
615
            };
616
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
617
        }
618
        if !self.swap_head(&new_parent.unwrap(), version.as_ref())? {
619
            return fail("the operation log changed while it was rewritten; run the command again");
620
        }
621
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
622
        Ok(())
623
    }
624
625
    /// Pack automatically once many loose objects have accumulated.
626
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
627
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
628
            self.store.pack_loose()?;
629
            self.store.merge_packs()?;
630
        }
631
        Ok(())
632
    }
633
634
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
635
    pub fn id(&self) -> Result<[u8; 16]> {
636
        if self.is_unbound() {
637
            return Ok([0; 16]);
638
        }
639
        let path = self.oxy.join("id");
640
        match fs::read_to_string(&path) {
641
            Ok(h) => hex::decode(h.trim())
642
                .ok()
643
                .and_then(|v| v.try_into().ok())
644
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
645
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
646
                let mut id = [0u8; 16];
647
                rand::rngs::OsRng.fill_bytes(&mut id);
648
                write_atomic(&path, hex::encode(id).as_bytes())?;
649
                Ok(id)
650
            }
651
            Err(e) => Err(e.into()),
652
        }
653
    }
654
655
    pub fn root(&self) -> &Path {
656
        &self.root
657
    }
658
    pub fn store(&self) -> &Store {
659
        &self.store
660
    }
661
    pub fn workspace(&self) -> WorkspaceId {
662
        self.workspace
663
    }
664
665
    /// Use a different user directory for keys and the user config file
666
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
667
    /// Act as if the working copy were on another platform's file system
668
    /// (tests of Windows and macOS behaviour on any host).
669
    pub fn with_platform(mut self, platform: crate::portable::Platform) -> Repo {
670
        self.platform = platform;
671
        self
672
    }
673
674
    pub fn platform(&self) -> crate::portable::Platform {
675
        self.platform
676
    }
677
678
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
679
        let dir = dir.into();
680
        self.keys_dir = dir.join("keys");
681
        self.user_config = dir.join("config.toml");
682
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
683
            self.config = c;
684
        }
685
        self.apply_workspace_bookmark();
686
        self
687
    }
688
689
    /// The workspace's current bookmark (spec §10.1) overrides the
690
    /// configured default when `oxy bookmark switch` has recorded one.
691
    fn apply_workspace_bookmark(&mut self) {
692
        if let Ok(b) = fs::read_to_string(
693
            self.oxy
694
                .join("workspaces")
695
                .join(self.workspace.to_hex())
696
                .join("bookmark"),
697
        ) {
698
            let b = b.trim();
699
            if !b.is_empty() {
700
                self.config.bookmark = b.to_string();
701
            }
702
        }
703
    }
704
705
    pub fn user_config_path(&self) -> &Path {
706
        &self.user_config
707
    }
708
709
    /// Set a key in the user file and refresh the effective configuration.
710
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
711
        Config::set_user(&self.user_config, key, value)?;
712
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
713
        Ok(())
714
    }
715
716
    pub fn save_config(&self) -> Result<()> {
717
        self.config.save(&self.oxy.join("config"))
718
    }
719
720
    fn author(&self) -> KeyId {
721
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
722
    }
723
}
724
725
impl Repo {
726
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
727
        let mut c = Change {
728
            version: crate::objects::CHANGE_VERSION,
729
            change_id: ChangeId::random(),
730
            deps,
731
            author: self.author(),
732
            hlc: Hlc::now(),
733
            message: message.into(),
734
            tree_ops: vec![],
735
            edits: vec![],
736
            kind: ChangeKind::WorkingCopy,
737
        };
738
        c.normalize();
739
        c
740
    }
741
742
    // ------------------------------------------------------------ operation log
743
744
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
745
        if let Some(r) = self.at_op {
746
            return Ok((r, Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?));
747
        }
748
        let r = self.head_ref()?;
749
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
750
        Ok((r, op))
751
    }
752
753
    pub fn view(&self) -> Result<View> {
754
        Ok(self.head_op()?.1.view)
755
    }
756
757
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
758
        self.record_op_undoing(parents, command, view, None)
759
    }
760
761
    /// [`Repo::record_op`], for an undo that reverts operation `undoes`.
762
    fn record_op_undoing(
763
        &self,
764
        parents: &[ObjectRef],
765
        command: &str,
766
        view: View,
767
        undoes: Option<ObjectRef>,
768
    ) -> Result<ObjectRef> {
769
        if self.at_op.is_some() {
770
            return fail(
771
                "--at-op shows the repository as it was; this command would change it (run it without --at-op)",
772
            );
773
        }
774
        let op = Op {
775
            parents: parents.to_vec(),
776
            hlc: Hlc::now(),
777
            command: command.into(),
778
            view,
779
            workspace: Some(self.workspace),
780
            undoes,
781
        };
782
        let r = self.store.put(ObjectType::Op, &op.encode())?;
783
        // The head is the commit point: everything it names must be on disk first.
784
        let flushing = crate::timing::phase("op: flush the store");
785
        self.store.flush()?;
786
        drop(flushing);
787
        // Compare and swap (spec §12.1): when another process recorded an
788
        // operation since this one read the head, the two are merged
789
        // instead of one overwriting the other. On this disk the head moves
790
        // under a short lock; on any other store by its record's version,
791
        // and a record that moved meanwhile is read again and merged again.
792
        let _lock = if self.store.is_local() {
793
            Some(self.lock_ops()?)
794
        } else {
795
            None
796
        };
797
        let Some(parent) = parents.first() else {
798
            // The first operation (init): there is no head yet.
799
            if !self.swap_head(&r, None)? {
800
                return fail(format!(
801
                    "{} already holds a repository's operation log",
802
                    self.store.backend().describe()
803
                ));
804
            }
805
            return Ok(r);
806
        };
807
        let base = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?.view;
808
        for _ in 0..HEAD_TRIES {
809
            let (current, version) = self.read_head()?;
810
            let to = if current == *parent {
811
                r
812
            } else {
813
                let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
814
                let merged = Op {
815
                    parents: vec![current, r],
816
                    hlc: Hlc::now(),
817
                    command: format!("{command} (merged with a concurrent operation)"),
818
                    view: self.merge_views(&base, &op.view, &theirs)?,
819
                    workspace: Some(self.workspace),
820
                    undoes: None,
821
                };
822
                let m = self.store.put(ObjectType::Op, &merged.encode())?;
823
                self.store.flush()?;
824
                m
825
            };
826
            if self.swap_head(&to, version.as_ref())? {
827
                return Ok(to);
828
            }
829
        }
830
        fail("other oxy processes kept changing the operation log while this one recorded; run the command again")
831
    }
832
833
    /// The operation head's lock, held only while the head pointer moves.
834
    fn lock_ops(&self) -> Result<FileLock> {
835
        fs::create_dir_all(self.oxy.join("ops"))?;
836
        FileLock::acquire(
837
            self.oxy.join("ops").join("lock"),
838
            "another oxy process holds the operation log",
839
        )
840
    }
841
842
    fn head_ref(&self) -> Result<ObjectRef> {
843
        Ok(self.read_head()?.0)
844
    }
845
846
    /// The operation head, and on a store its record's version for
847
    /// [`Repo::swap_head`]. On this disk the head is `.oxy/ops/head`; on
848
    /// any other store (a bucket, or memory in tests) it is the store's
849
    /// [`HEAD_RECORD`] reference record (oxygen#68).
850
    fn read_head(&self) -> Result<(ObjectRef, Option<crate::strata::Version>)> {
851
        if self.store.is_local() {
852
            let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
853
            let r = ObjectRef::from_hex(hex.trim())
854
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
855
            return Ok((r, None));
856
        }
857
        let backend = self.store.backend();
858
        match backend.read_ref(HEAD_RECORD) {
859
            Ok(Some((bytes, version))) => {
860
                let r = ObjectRef::from_hex(String::from_utf8_lossy(&bytes).trim()).ok_or_else(
861
                    || {
862
                        RepoError::Msg(format!(
863
                            "the operation head in {} is corrupt",
864
                            backend.describe()
865
                        ))
866
                    },
867
                )?;
868
                Ok((r, Some(version)))
869
            }
870
            Ok(None) => fail(format!(
871
                "{} holds no operation log (no {HEAD_RECORD} record)",
872
                backend.describe()
873
            )),
874
            Err(e) => fail(format!("read the operation head: {e}")),
875
        }
876
    }
877
878
    /// Move the operation head to `to` from the `expected` version
879
    /// [`Repo::read_head`] gave (`None`: there is no head yet). On this
880
    /// disk the caller holds the operations lock and the head always
881
    /// moves; on a store it moves only if the record is unchanged, and
882
    /// `false` says another process moved it first.
883
    fn swap_head(&self, to: &ObjectRef, expected: Option<&crate::strata::Version>) -> Result<bool> {
884
        if self.store.is_local() {
885
            write_atomic(&self.oxy.join("ops").join("head"), to.to_hex().as_bytes())?;
886
            return Ok(true);
887
        }
888
        match self
889
            .store
890
            .backend()
891
            .write_ref(HEAD_RECORD, to.to_hex().as_bytes(), expected)
892
        {
893
            Ok(_) => Ok(true),
894
            Err(crate::strata::Error::Conflict(_)) => Ok(false),
895
            Err(e) => fail(format!("move the operation head: {e}")),
896
        }
897
    }
898
899
    /// Three-way merge of two views that both started from `base` (spec
900
    /// §12.1). A reference only one side changed takes that side's value.
901
    /// When both changed it differently: a bookmark keeps both sides'
902
    /// heads (it may then have several), a change beats a deletion, a
903
    /// workspace changed by both is an error (only one of them matches the
904
    /// files on disk), and otherwise this process's value wins for remote
905
    /// references and the policy, the first value for a tag (tags never
906
    /// move).
907
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
908
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
909
            b: &BTreeMap<K, V>,
910
            o: &BTreeMap<K, V>,
911
            t: &BTreeMap<K, V>,
912
            mut both: impl FnMut(&V, &V) -> Result<V>,
913
        ) -> Result<BTreeMap<K, V>> {
914
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
915
            let mut out = BTreeMap::new();
916
            for k in keys {
917
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
918
                let v = if ov == tv || tv == bv {
919
                    ov.cloned()
920
                } else if ov == bv {
921
                    tv.cloned()
922
                } else {
923
                    match (ov, tv) {
924
                        (Some(x), Some(y)) => Some(both(x, y)?),
925
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
926
                        (None, None) => None,
927
                    }
928
                };
929
                if let Some(v) = v {
930
                    out.insert(k.clone(), v);
931
                }
932
            }
933
            Ok(out)
934
        }
935
        let bookmarks = pick(
936
            &base.bookmarks,
937
            &ours.bookmarks,
938
            &theirs.bookmarks,
939
            |x, y| {
940
                let mut heads = self.store.get_state(x)?.heads;
941
                heads.extend(self.store.get_state(y)?.heads);
942
                let heads = self.load_state(&heads)?.maximal(&heads);
943
                Ok(self.store.put_state(&StateObject::new(heads))?)
944
            },
945
        )?;
946
        // Two operations that both replaced one workspace's working copy
947
        // cannot both be right: the files on disk match only one of them.
948
        // The working-copy lock keeps this from happening; should it happen
949
        // anyway, this operation is not recorded.
950
        let workspaces = pick(
951
            &base.workspaces,
952
            &ours.workspaces,
953
            &theirs.workspaces,
954
            |_, _| {
955
                fail(
956
                    "another oxy process changed this working copy at the same time; \
957
                     this command was not recorded: check `oxy status` and run it again",
958
                )
959
            },
960
        )?;
961
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
962
        let empty = BTreeMap::new();
963
        let names: BTreeSet<&String> = base
964
            .remotes
965
            .keys()
966
            .chain(ours.remotes.keys())
967
            .chain(theirs.remotes.keys())
968
            .collect();
969
        let mut remotes = BTreeMap::new();
970
        for n in names {
971
            let m = pick(
972
                base.remotes.get(n).unwrap_or(&empty),
973
                ours.remotes.get(n).unwrap_or(&empty),
974
                theirs.remotes.get(n).unwrap_or(&empty),
975
                |x, _| Ok(*x),
976
            )?;
977
            if !m.is_empty() {
978
                remotes.insert(n.clone(), m);
979
            }
980
        }
981
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
982
            ours.policy
983
        } else if ours.policy == base.policy {
984
            theirs.policy
985
        } else {
986
            ours.policy.or(theirs.policy)
987
        };
988
        self.store.flush()?;
989
        Ok(View {
990
            bookmarks,
991
            workspaces,
992
            remotes,
993
            policy,
994
            tags,
995
        })
996
    }
997
998
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
999
        let mut out = Vec::new();
1000
        let (mut r, mut op) = self.head_op()?;
1001
        loop {
1002
            let next = op.parents.first().copied();
1003
            out.push((r, op));
1004
            match next {
1005
                Some(p) => {
1006
                    r = p;
1007
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
1008
                }
1009
                None => break,
1010
            }
1011
        }
1012
        Ok(out)
1013
    }
1014
1015
    /// Undo this workspace's last command (spec §12.1, oxygen#99).
1016
    ///
1017
    /// The command undone is the newest one this workspace ran: operations
1018
    /// that only recorded a working-copy snapshot are skipped (the files are
1019
    /// still on disk and the next snapshot recreates them), as are pushes
1020
    /// (the remote keeps what it was sent; see [`Undone::pushed`]), a command's own
1021
    /// checkout (`… (checkout)`) goes with the command, other workspaces'
1022
    /// operations are never undone, and a command an earlier undo already
1023
    /// reverted is passed over, so undoing again goes further back.
1024
    ///
1025
    /// When nothing newer came from another workspace, the operation head
1026
    /// moves back to before the command. Otherwise the command is reverted
1027
    /// in place: every reference it changed goes back to its value before
1028
    /// it, recorded as a new operation that names it, and anything another
1029
    /// workspace changed since is kept. A reference both the command and a
1030
    /// later operation of another workspace changed is not guessed at: the
1031
    /// undo is refused, naming it.
1032
    ///
1033
    /// When the working copy is clean and was clean after the command's
1034
    /// predecessor, its files follow too, since nothing on disk can be
1035
    /// lost; otherwise they stay as they are (an undone commit's edits come
1036
    /// back as uncommitted work).
1037
    pub fn undo(&self) -> Result<Undone> {
1038
        let _wc = self.lock_working_copy()?;
1039
        let clean_now =
1040
            self.clean_by_manifest()? || self.snapshot_status("oxy undo")?.statuses.is_empty();
1041
        let (head_ref, head) = self.head_op()?;
1042
        let wc_now = head.view.workspaces.get(&self.workspace).copied();
1043
        let load = |r: &ObjectRef| -> Result<Op> {
1044
            Ok(Op::decode(&self.store.get_typed(r, ObjectType::Op)?)?)
1045
        };
1046
        let mut skip: BTreeSet<ObjectRef> = BTreeSet::new();
1047
        let mut pending_checkout: Option<Op> = None;
1048
        let mut others = 0usize;
1049
        let (mut r, mut op) = (head_ref, head.clone());
1050
        let (target_ref, target, parent) = loop {
1051
            let parent = match op.parents.first() {
1052
                Some(p) => Some((*p, load(p)?)),
1053
                None => None,
1054
            };
1055
            if skip.contains(&r) {
1056
                pending_checkout = None;
1057
            } else if op.is_snapshot() || Self::is_push(&op, parent.as_ref().map(|(_, p)| p)) {
1058
                // A push cannot be taken back: undoing it would only make
1059
                // this repository forget what the remote holds.
1060
            } else if !self.op_is_ours(&op, parent.as_ref().map(|(_, p)| p)) {
1061
                others += 1;
1062
            } else if let Some(u) = op.undoes {
1063
                skip.insert(u);
1064
                pending_checkout = None;
1065
            } else if op.command.ends_with(" (checkout)") {
1066
                pending_checkout = Some(op.clone());
1067
            } else {
1068
                match parent {
1069
                    Some((_, p)) => break (r, op, p),
1070
                    None => return fail("nothing to undo in this workspace"),
1071
                }
1072
            }
1073
            match parent {
1074
                Some((pr, p)) => (r, op) = (pr, p),
1075
                None => return fail("nothing to undo in this workspace"),
1076
            }
1077
        };
1078
        let before = parent.view;
1079
        let after = pending_checkout
1080
            .map(|o| o.view)
1081
            .unwrap_or_else(|| target.view.clone());
1082
        let changes = self.view_changes(&before, &after)?;
1083
        let pushed = self.pushed_by(&before, &after, &head.view)?;
1084
        let restored_wc = before.workspaces.get(&self.workspace).copied();
1085
        if others == 0 {
1086
            // Only this workspace's operations since: move the head back.
1087
            let _lock = if self.store.is_local() {
1088
                Some(self.lock_ops()?)
1089
            } else {
1090
                None
1091
            };
1092
            let parent_ref = *target.parents.first().expect("the target has a parent");
1093
            let (now, version) = self.read_head()?;
1094
            if now != head_ref || !self.swap_head(&parent_ref, version.as_ref())? {
1095
                return fail("another oxy command ran while undoing; run undo again");
1096
            }
1097
        } else {
1098
            let view = self.revert_view(&head.view, &before, &after)?;
1099
            self.record_op_undoing(&[head_ref], "oxy undo", view, Some(target_ref))?;
1100
        }
1101
        self.drop_manifest();
1102
        if let Some(then) = restored_wc {
1103
            if clean_now && Some(then) != wc_now {
1104
                let wc = self.store.get_change(&then)?;
1105
                if wc.edits.is_empty() && wc.tree_ops.is_empty() {
1106
                    let base = self.load_state_history(&wc.deps)?.maximal(&wc.deps);
1107
                    // The files differ from the restored working copy by
1108
                    // exactly what the undone command did: nothing else is
1109
                    // on disk, as the working copy was clean.
1110
                    self.checkout(&base, true, "oxy undo (checkout)")?;
1111
                }
1112
            }
1113
        }
1114
        Ok(Undone {
1115
            command: target.command,
1116
            changes,
1117
            others_kept: others,
1118
            pushed,
1119
        })
1120
    }
1121
1122
    /// Whether operation `op` was a push: it changed only what this
1123
    /// repository knows of remotes.
1124
    fn is_push(op: &Op, parent: Option<&Op>) -> bool {
1125
        let Some(p) = parent else {
1126
            return false;
1127
        };
1128
        op.command.starts_with("oxy push")
1129
            && op.view.bookmarks == p.view.bookmarks
1130
            && op.view.tags == p.view.tags
1131
            && op.view.workspaces == p.view.workspaces
1132
            && op.view.policy == p.view.policy
1133
    }
1134
1135
    /// Whether operation `op` (whose predecessor is `parent`) was this
1136
    /// workspace's. Operations record their workspace (oxygen#99); for older
1137
    /// ones it is read from the view: one that changed only other
1138
    /// workspaces' working copies was theirs, anything else counts as ours.
1139
    fn op_is_ours(&self, op: &Op, parent: Option<&Op>) -> bool {
1140
        if let Some(w) = op.workspace {
1141
            return w == self.workspace;
1142
        }
1143
        let Some(p) = parent else {
1144
            return true;
1145
        };
1146
        let ids: BTreeSet<&WorkspaceId> = op
1147
            .view
1148
            .workspaces
1149
            .keys()
1150
            .chain(p.view.workspaces.keys())
1151
            .collect();
1152
        let moved: Vec<&WorkspaceId> = ids
1153
            .into_iter()
1154
            .filter(|id| op.view.workspaces.get(id) != p.view.workspaces.get(id))
1155
            .collect();
1156
        moved.is_empty() || moved.contains(&&self.workspace)
1157
    }
1158
1159
    /// `current` with what changed from `before` to `after` put back, this
1160
    /// workspace's working copy included; refused when a later operation
1161
    /// changed one of the same references again.
1162
    fn revert_view(&self, current: &View, before: &View, after: &View) -> Result<View> {
1163
        fn back<K: Ord + Clone, V: Clone + PartialEq>(
1164
            cur: &mut BTreeMap<K, V>,
1165
            before: &BTreeMap<K, V>,
1166
            after: &BTreeMap<K, V>,
1167
            name: impl Fn(&K) -> String,
1168
            clashes: &mut Vec<String>,
1169
        ) {
1170
            let keys: BTreeSet<&K> = before.keys().chain(after.keys()).collect();
1171
            for k in keys {
1172
                let (b, a) = (before.get(k), after.get(k));
1173
                if a == b {
1174
                    continue;
1175
                }
1176
                if cur.get(k) != a {
1177
                    clashes.push(name(k));
1178
                    continue;
1179
                }
1180
                match b {
1181
                    Some(v) => cur.insert(k.clone(), v.clone()),
1182
                    None => cur.remove(k),
1183
                };
1184
            }
1185
        }
1186
        let mut out = current.clone();
1187
        let mut clashes = Vec::new();
1188
        // A bookmark another workspace moved since is put back head by
1189
        // head: the heads the command added go, the heads it replaced
1190
        // return, and the other workspace's heads stay. Only when a later
1191
        // change was built on one the command added is that not possible.
1192
        let names: BTreeSet<&String> = before
1193
            .bookmarks
1194
            .keys()
1195
            .chain(after.bookmarks.keys())
1196
            .collect();
1197
        for name in names {
1198
            let (b, a) = (before.bookmarks.get(name), after.bookmarks.get(name));
1199
            let cur = current.bookmarks.get(name);
1200
            if a == b {
1201
                continue;
1202
            }
1203
            if cur == a {
1204
                match b {
1205
                    Some(st) => out.bookmarks.insert(name.clone(), *st),
1206
                    None => out.bookmarks.remove(name),
1207
                };
1208
                continue;
1209
            }
1210
            let (Some(b), Some(a), Some(cur)) = (b, a, cur) else {
1211
                clashes.push(format!("bookmark {name}"));
1212
                continue;
1213
            };
1214
            let was: BTreeSet<ChangeHash> = self.store.get_state(b)?.heads.into_iter().collect();
1215
            let became: BTreeSet<ChangeHash> = self.store.get_state(a)?.heads.into_iter().collect();
1216
            let now: BTreeSet<ChangeHash> = self.store.get_state(cur)?.heads.into_iter().collect();
1217
            let added: BTreeSet<&ChangeHash> = became.difference(&was).collect();
1218
            if !added.iter().all(|h| now.contains(h)) {
1219
                clashes.push(format!(
1220
                    "bookmark {name} (a later change builds on this one)"
1221
                ));
1222
                continue;
1223
            }
1224
            let mut heads: Vec<ChangeHash> = now
1225
                .iter()
1226
                .filter(|h| !added.contains(h))
1227
                .chain(was.difference(&became))
1228
                .copied()
1229
                .collect();
1230
            heads.sort();
1231
            heads.dedup();
1232
            let heads = self.load_state(&heads)?.maximal(&heads);
1233
            out.bookmarks.insert(
1234
                name.clone(),
1235
                self.store.put_state(&StateObject::new(heads))?,
1236
            );
1237
        }
1238
1239
        back(
1240
            &mut out.tags,
1241
            &before.tags,
1242
            &after.tags,
1243
            |k| format!("tag {k}"),
1244
            &mut clashes,
1245
        );
1246
        let mine = self.workspace;
1247
        let others = |v: &View| -> BTreeMap<WorkspaceId, ChangeHash> {
1248
            v.workspaces
1249
                .iter()
1250
                .filter(|(k, _)| **k != mine)
1251
                .map(|(k, v)| (*k, *v))
1252
                .collect()
1253
        };
1254
        let mut theirs = others(&out);
1255
        let workspace_name = |id: &WorkspaceId| match self.workspace_path(id) {
1256
            Some(p) => format!("the workspace at {}", p.display()),
1257
            None => format!("workspace {}", id.to_hex()),
1258
        };
1259
        back(
1260
            &mut theirs,
1261
            &others(before),
1262
            &others(after),
1263
            workspace_name,
1264
            &mut clashes,
1265
        );
1266
        let empty = BTreeMap::new();
1267
        let names: BTreeSet<&String> = before.remotes.keys().chain(after.remotes.keys()).collect();
1268
        for n in names {
1269
            let mut cur = out.remotes.get(n).cloned().unwrap_or_default();
1270
            back(
1271
                &mut cur,
1272
                before.remotes.get(n).unwrap_or(&empty),
1273
                after.remotes.get(n).unwrap_or(&empty),
1274
                |k| format!("{n}/{k}"),
1275
                &mut clashes,
1276
            );
1277
            if cur.is_empty() {
1278
                out.remotes.remove(n);
1279
            } else {
1280
                out.remotes.insert(n.clone(), cur);
1281
            }
1282
        }
1283
        if before.policy != after.policy {
1284
            if out.policy == after.policy {
1285
                out.policy = before.policy;
1286
            } else {
1287
                clashes.push("the policy".into());
1288
            }
1289
        }
1290
        if !clashes.is_empty() {
1291
            return fail(format!(
1292
                "undo would also take back what another workspace has done since to {}; \
1293
                 see `oxy op log`, and restore a whole earlier state with `oxy op restore OP` if that is what you want",
1294
                clashes.join(", ")
1295
            ));
1296
        }
1297
        out.workspaces = theirs;
1298
        match before.workspaces.get(&mine) {
1299
            Some(wc) => out.workspaces.insert(mine, *wc),
1300
            None => out.workspaces.remove(&mine),
1301
        };
1302
        Ok(out)
1303
    }
1304
1305
    /// Bookmarks whose heads, added between `before` and `after`, a remote
1306
    /// in `now` already holds: undoing them locally leaves them there.
1307
    fn pushed_by(&self, before: &View, after: &View, now: &View) -> Result<Vec<(String, String)>> {
1308
        let mut out = Vec::new();
1309
        for (name, st) in &after.bookmarks {
1310
            if before.bookmarks.get(name) == Some(st) {
1311
                continue;
1312
            }
1313
            let had: BTreeSet<ChangeHash> = match before.bookmarks.get(name) {
1314
                Some(b) => self.store.get_state(b)?.heads.into_iter().collect(),
1315
                None => BTreeSet::new(),
1316
            };
1317
            let added: Vec<ChangeHash> = self
1318
                .store
1319
                .get_state(st)?
1320
                .heads
1321
                .into_iter()
1322
                .filter(|h| !had.contains(h))
1323
                .collect();
1324
            if added.is_empty() {
1325
                continue;
1326
            }
1327
            for (remote, bookmarks) in &now.remotes {
1328
                if let Some(rs) = bookmarks.get(name) {
1329
                    let theirs = self.store.get_state(rs)?.heads;
1330
                    if added.iter().any(|h| theirs.contains(h)) {
1331
                        out.push((name.clone(), remote.clone()));
1332
                    }
1333
                }
1334
            }
1335
        }
1336
        Ok(out)
1337
    }
1338
1339
    /// The last operation that was not a snapshot.
1340
    pub fn last_command(&self) -> Result<Op> {
1341
        let (_, mut op) = self.head_op()?;
1342
        while op.is_snapshot() {
1343
            let Some(parent) = op.parents.first() else {
1344
                break;
1345
            };
1346
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
1347
        }
1348
        Ok(op)
1349
    }
1350
1351
    // ------------------------------------------------------------ states
1352
1353
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
1354
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
1355
        if let Some(st) = self.load_state_checkpointed(heads)? {
1356
            return Ok(st);
1357
        }
1358
        self.load_state_full(heads)
1359
    }
1360
1361
    /// The state of `heads` for its history (changes, tree, metadata) with
1362
    /// no file graph built: much cheaper than [`Repo::load_state`] for log
1363
    /// and friends. Build the graphs a command needs with
1364
    /// [`Repo::load_graphs_of`].
1365
    pub fn load_state_history(&self, heads: &[ChangeHash]) -> Result<State> {
1366
        if let Some(st) = self.load_state_checkpointed_as(heads, true)? {
1367
            return Ok(st);
1368
        }
1369
        self.load_state_replayed(heads, State::new_history_only())
1370
    }
1371
1372
    /// Build these file graphs in a history-only state.
1373
    pub fn load_graphs_of(&self, state: &mut State, nodes: &[crate::ids::NodeId]) -> Result<()> {
1374
        state
1375
            .load_graphs(
1376
                nodes,
1377
                |refs| {
1378
                    self.read_blobs(refs).map_err(|e| {
1379
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
1380
                    })
1381
                },
1382
                |h| self.change_bytes(h),
1383
            )
1384
            .map_err(|e| self.index_damage(e))
1385
    }
1386
1387
    /// An error building graphs, and when it is a state index found
1388
    /// damaged (a file's history that does not match its hash), the
1389
    /// workspace's state indexes removed: they are rebuilt from history by
1390
    /// the next command.
1391
    fn index_damage(&self, e: crate::objects::ObjectError) -> RepoError {
1392
        let crate::objects::ObjectError::DamagedIndex(why) = &e else {
1393
            return e.into();
1394
        };
1395
        for path in self.state_indexes() {
1396
            let _ = fs::remove_file(path);
1397
        }
1398
        RepoError::Msg(format!(
1399
            "this workspace's state index was damaged ({why}) and has been removed; run the command again to rebuild it"
1400
        ))
1401
    }
1402
1403
    /// The graphs of `nodes` of a history-only state, built beside it (see
1404
    /// [`State::build_graphs_detached`]).
1405
    pub fn build_graphs_detached(
1406
        &self,
1407
        state: &State,
1408
        nodes: &[crate::ids::NodeId],
1409
    ) -> Result<HashMap<crate::ids::NodeId, crate::graph::FileGraph>> {
1410
        Ok(state
1411
            .build_graphs_detached(
1412
                nodes,
1413
                |refs| {
1414
                    self.read_blobs(refs).map_err(|e| {
1415
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
1416
                    })
1417
                },
1418
                |h| self.change_bytes(h),
1419
            )
1420
            .map_err(|e| self.index_damage(e))?
1421
            .into_iter()
1422
            .collect())
1423
    }
1424
1425
    /// The contents of texts [`State::single_text`] gave: blobs read in
1426
    /// one go, inline ones from their changes.
1427
    pub(crate) fn single_texts(&self, texts: &[crate::objects::TextRef]) -> Result<Vec<Vec<u8>>> {
1428
        use crate::objects::TextRef;
1429
        let refs: Vec<ObjectRef> = texts
1430
            .iter()
1431
            .filter_map(|t| match t {
1432
                TextRef::Blob(r, _, _) => Some(*r),
1433
                TextRef::Inline { .. } => None,
1434
            })
1435
            .collect();
1436
        let mut blobs = self.read_blobs(&refs)?.into_iter();
1437
        let mut out = Vec::with_capacity(texts.len());
1438
        for t in texts {
1439
            let lines = match t {
1440
                TextRef::Blob(_, count, form) => {
1441
                    let content = blobs
1442
                        .next()
1443
                        .ok_or_else(|| RepoError::Msg("text blobs: wrong count".into()))?;
1444
                    crate::objects::text_lines(&content, *count, *form)?
1445
                }
1446
                TextRef::Inline { change, start, end } => {
1447
                    let bytes = self.change_bytes(change)?;
1448
                    let range = bytes.get(*start as usize..*end as usize).ok_or_else(|| {
1449
                        RepoError::Msg("an inline insert lies outside its change".into())
1450
                    })?;
1451
                    crate::objects::inline_lines(range)?
1452
                }
1453
            };
1454
            out.push(lines.bytes().to_vec());
1455
        }
1456
        Ok(out)
1457
    }
1458
1459
    /// Build every graph a history-only state still lacks, making it full.
1460
    pub fn load_all_graphs(&self, state: &mut State) -> Result<()> {
1461
        state
1462
            .load_all_graphs(
1463
                |refs| {
1464
                    self.read_blobs(refs).map_err(|e| {
1465
                        crate::objects::ObjectError::Schema(format!("graph and text blobs: {e}"))
1466
                    })
1467
                },
1468
                |h| self.change_bytes(h),
1469
            )
1470
            .map_err(|e| self.index_damage(e))
1471
    }
1472
1473
    /// A change's encoding, for building graphs of its inline inserts. The
1474
    /// last few read are kept: a checkout building graphs a batch at a
1475
    /// time reads the same large changes for every batch, often in turn.
1476
    fn change_bytes(
1477
        &self,
1478
        h: &ChangeHash,
1479
    ) -> std::result::Result<std::sync::Arc<Vec<u8>>, crate::objects::ObjectError> {
1480
        let mut cache = self.last_change.borrow_mut();
1481
        if let Some(i) = cache.iter().position(|(k, _)| k == h) {
1482
            let hit = cache.remove(i);
1483
            let b = hit.1.clone();
1484
            cache.push(hit);
1485
            return Ok(b);
1486
        }
1487
        let b = std::sync::Arc::new(self.store.get_typed(h, ObjectType::Change).map_err(|e| {
1488
            crate::objects::ObjectError::Schema(format!("change {}: {e}", h.short(12)))
1489
        })?);
1490
        cache.push((*h, b.clone()));
1491
        // The last few, within a memory budget; the newest always stays.
1492
        while cache.len() > CHANGE_CACHE_COUNT
1493
            || (cache.len() > 1
1494
                && cache.iter().map(|(_, b)| b.len()).sum::<usize>() > CHANGE_CACHE_BYTES)
1495
        {
1496
            cache.remove(0);
1497
        }
1498
        Ok(b)
1499
    }
1500
1501
    /// Load the dependency closure of `heads` change by change.
1502
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
1503
        self.load_state_replayed(heads, State::new())
1504
    }
1505
1506
    fn load_state_replayed(&self, heads: &[ChangeHash], mut state: State) -> Result<State> {
1507
        let history = state.is_history_only();
1508
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1509
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1510
        {
1511
            let _t = crate::timing::phase("load: read and add changes");
1512
            let (mut read, mut add, mut fetch) = (
1513
                std::time::Duration::ZERO,
1514
                std::time::Duration::ZERO,
1515
                std::time::Duration::ZERO,
1516
            );
1517
            while let Some(h) = stack.pop() {
1518
                // A change the state holds brings its history with it.
1519
                if !seen.insert(h) || state.contains(&h) {
1520
                    continue;
1521
                }
1522
                let t0 = std::time::Instant::now();
1523
                // A history-only state reads text only for the graphs it
1524
                // builds; either way the hash is the one asked for.
1525
                let (c, texts) = if history {
1526
                    let bytes = self.store.get_typed(&h, ObjectType::Change)?;
1527
                    fetch += t0.elapsed();
1528
                    Change::decode_skeleton(&bytes, h)
1529
                        .map_err(|e| crate::store::StoreError::Corrupt(h, e.to_string()))?
1530
                } else {
1531
                    (self.store.get_change(&h)?, Vec::new())
1532
                };
1533
                read += t0.elapsed();
1534
                stack.extend(c.deps.iter().copied());
1535
                let t1 = std::time::Instant::now();
1536
                state.add_known(h, c, texts);
1537
                add += t1.elapsed();
1538
            }
1539
            crate::timing::record("load:   of which reading", read);
1540
            crate::timing::record("load:     of which fetching", fetch);
1541
            crate::timing::record("load:   of which applying", add);
1542
        }
1543
        let _t = crate::timing::phase("load: validate");
1544
        state.validate()?;
1545
        Ok(state)
1546
    }
1547
1548
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
1549
        if self.bare {
1550
            return fail("this is a bare repository: it has no working copy");
1551
        }
1552
        let view = self.view()?;
1553
        let h = *view
1554
            .workspaces
1555
            .get(&self.workspace)
1556
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
1557
        Ok((h, self.store.get_change(&h)?))
1558
    }
1559
1560
    /// Heads of a bookmark's state (spec §10.1).
1561
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
1562
        match view.bookmarks.get(bookmark) {
1563
            Some(st) => Ok(self.store.get_state(st)?.heads),
1564
            None => Ok(vec![]),
1565
        }
1566
    }
1567
1568
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
1569
        self.heads_of(&self.view()?, &self.config.bookmark)
1570
    }
1571
1572
    // ------------------------------------------------------------ blobs
1573
1574
    fn blob_for(content: &[u8]) -> Blob {
1575
        Blob::of(content)
1576
    }
1577
1578
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
1579
        Self::blob_for(content).hash()
1580
    }
1581
1582
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
1583
        for c in crate::chunk::chunks(content) {
1584
            self.store.put_chunk(c)?;
1585
        }
1586
        Ok(self
1587
            .store
1588
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1589
    }
1590
1591
    /// Read many blobs at once (checkpoint graphs): the blob objects, then
1592
    /// all their chunks, are read in parallel; a blob the store lacks goes
1593
    /// through [`Repo::read_blob`], which may fetch it lazily.
1594
    pub fn read_blobs(&self, refs: &[ObjectRef]) -> Result<Vec<Vec<u8>>> {
1595
        let mut blobs: Vec<Option<Blob>> = Vec::with_capacity(refs.len());
1596
        for (r, got) in refs.iter().zip(self.store.get_many(refs)) {
1597
            blobs.push(match got {
1598
                Ok((ObjectType::Blob, body)) => Some(Blob::decode(&body)?),
1599
                Ok((ty, _)) => return fail(format!("{} is a {ty:?}, not a blob", r.short(12))),
1600
                Err(crate::store::StoreError::NotFound(_)) => None,
1601
                Err(e) => return Err(e.into()),
1602
            });
1603
        }
1604
        let chunk_refs: Vec<ObjectRef> = blobs
1605
            .iter()
1606
            .flatten()
1607
            .flat_map(|b| b.chunks.iter().copied())
1608
            .collect();
1609
        let mut chunks = self.store.get_many(&chunk_refs).into_iter();
1610
        let mut out = Vec::with_capacity(refs.len());
1611
        for (r, blob) in refs.iter().zip(blobs) {
1612
            match blob {
1613
                None => out.push(self.read_blob(r)?),
1614
                Some(b) => {
1615
                    let mut content = Vec::with_capacity(b.length as usize);
1616
                    for c in &b.chunks {
1617
                        match chunks.next() {
1618
                            Some(Ok((ObjectType::Chunk, body))) => content.extend(body),
1619
                            Some(Ok(_)) => return fail(format!("{} is not a chunk", c.short(12))),
1620
                            Some(Err(e)) => return Err(e.into()),
1621
                            None => return fail("chunk list ended early"),
1622
                        }
1623
                    }
1624
                    out.push(content);
1625
                }
1626
            }
1627
        }
1628
        Ok(out)
1629
    }
1630
1631
    /// Read a blob's content, fetching it from the remote that withheld it
1632
    /// when it is lazily absent (spec §13.5).
1633
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
1634
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
1635
            self.fetch_lazy_blob(r)?;
1636
        }
1637
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
1638
        let mut out = Vec::with_capacity(blob.length as usize);
1639
        for c in &blob.chunks {
1640
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
1641
        }
1642
        Ok(out)
1643
    }
1644
1645
    // ------------------------------------------------------------ working copy
1646
1647
    /// Attributes from the `.oxyattributes` files in the working directory.
1648
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
1649
        // Nested repositories and ignored paths are left out, as in a walk.
1650
        let listing = walk::list(&self.root, &|p: &str| is_attributes(p)).unwrap_or_default();
1651
        let files: Vec<(String, Vec<u8>)> = listing
1652
            .files
1653
            .into_iter()
1654
            .filter_map(|(rel, path, _)| Some((rel, fs::read(path).ok()?)))
1655
            .collect();
1656
        crate::attributes::Attributes::from_files(
1657
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
1658
        )
1659
    }
1660
1661
    /// Folders holding a repository of their own that the last look at the
1662
    /// working copy left out, not being subrepos (oxygen#43).
1663
    pub fn untracked_nested(&self) -> Vec<String> {
1664
        self.untracked_nested.borrow().clone()
1665
    }
1666
1667
    /// Attributes from a materialized state's `.oxyattributes` files.
1668
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
1669
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
1670
            match &f.content {
1671
                FileContent::Text { bytes, .. }
1672
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
1673
                {
1674
                    Some((p.as_str(), bytes.as_slice()))
1675
                }
1676
                _ => None,
1677
            }
1678
        }))
1679
    }
1680
1681
    /// Store a blob, raw when the path is `nocompress`.
1682
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
1683
        if !nocompress {
1684
            return self.store_blob(content);
1685
        }
1686
        for c in crate::chunk::chunks(content) {
1687
            self.store.put_chunk_nocompress(c)?;
1688
        }
1689
        Ok(self
1690
            .store
1691
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
1692
    }
1693
1694
    /// This workspace's state index (oxygen#41): its working copy's base,
1695
    /// saved so a snapshot reads it rather than replaying history.
1696
    /// The state index of the state with these heads: this workspace keeps
1697
    /// the last few it used, named by their heads, so moving between two
1698
    /// states finds both.
1699
    fn state_index_path(&self, heads: &[ChangeHash]) -> PathBuf {
1700
        let mut heads = heads.to_vec();
1701
        heads.sort();
1702
        let mut h = blake3::Hasher::new();
1703
        for c in &heads {
1704
            h.update(&c.0);
1705
        }
1706
        self.oxy.join("index").join(format!(
1707
            "{}{}",
1708
            self.state_index_prefix(),
1709
            &h.finalize().to_hex()[..16]
1710
        ))
1711
    }
1712
1713
    fn state_index_prefix(&self) -> String {
1714
        format!("state-{}-", self.workspace.to_hex())
1715
    }
1716
1717
    /// This workspace's state indexes, newest first.
1718
    fn state_indexes(&self) -> Vec<PathBuf> {
1719
        let prefix = self.state_index_prefix();
1720
        let mut found: Vec<(std::time::SystemTime, PathBuf)> = fs::read_dir(self.oxy.join("index"))
1721
            .into_iter()
1722
            .flatten()
1723
            .flatten()
1724
            .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
1725
            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
1726
            .collect();
1727
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
1728
        found.into_iter().map(|(_, p)| p).collect()
1729
    }
1730
1731
    /// The history-only state of `deps` (as [`Repo::load_state_history`]),
1732
    /// from this workspace's state index when it holds that history: every
1733
    /// one of `deps` is in it and their heads are its heads. Otherwise it
1734
    /// is loaded from history and indexed for next time.
1735
    pub fn load_state_indexed(&self, deps: &[ChangeHash]) -> Result<State> {
1736
        if let Some((st, heads)) = self.read_state_index(deps) {
1737
            let mut have = st.maximal(deps);
1738
            have.sort();
1739
            if deps.iter().all(|d| st.contains(d)) && have == heads {
1740
                // Re-encoding reads every history: one found damaged is
1741
                // left to the build that reads it, which reports it.
1742
                #[cfg(test)]
1743
                if let Some(mine) = st.write_index() {
1744
                    assert_eq!(
1745
                        Some(mine),
1746
                        self.load_state_history(deps)?.write_index(),
1747
                        "a state index holds the state history gives"
1748
                    );
1749
                }
1750
                return Ok(st);
1751
            }
1752
            // An index a few changes behind (a commit, a pull since): add
1753
            // what it lacks, as long as all it holds is history of `deps`.
1754
            // Anything amiss (a change beyond a shallow boundary) takes the
1755
            // long way instead.
1756
            let (indexed, started) = (st.len(), std::time::Instant::now());
1757
            if let Ok(st) = self.load_state_replayed(deps, st) {
1758
                let mut all = deps.to_vec();
1759
                all.extend(heads.iter().copied());
1760
                let (mut within, mut want) = (st.maximal(&all), st.maximal(deps));
1761
                within.sort();
1762
                want.sort();
1763
                if within == want {
1764
                    #[cfg(test)]
1765
                    self.assert_same_state(&st, &self.load_state_history(deps)?);
1766
                    // Writing the index costs far more than replaying a
1767
                    // few small changes: it is rewritten once it falls
1768
                    // behind, or when replaying took long (large changes).
1769
                    if st.len() - indexed > INDEX_REPLAY_LIMIT
1770
                        || started.elapsed() > INDEX_REPLAY_TIME
1771
                    {
1772
                        self.write_state_index(deps, &st);
1773
                    }
1774
                    return Ok(st);
1775
                }
1776
            }
1777
        }
1778
        let st = self.load_state_history(deps)?;
1779
        self.write_state_index(deps, &st);
1780
        Ok(st)
1781
    }
1782
1783
    /// Two history-only states hold the same changes and render the same
1784
    /// files. Their indexes may differ: one loaded from a checkpoint keeps
1785
    /// the checkpoint's graphs as the bases of its files' histories.
1786
    #[cfg(test)]
1787
    fn assert_same_state(&self, a: &State, b: &State) {
1788
        let ids = |s: &State| s.changes().map(|(h, _)| *h).collect::<BTreeSet<_>>();
1789
        assert_eq!(ids(a), ids(b), "the same changes");
1790
        let files = |s: &State| {
1791
            let mut s = s.clone();
1792
            self.load_all_graphs(&mut s).unwrap();
1793
            s.materialize().files
1794
        };
1795
        assert_eq!(files(a), files(b), "the same files");
1796
    }
1797
1798
    /// The state index file: its heads, a hash of its changes block and one
1799
    /// of the rest, then the body [`State::write_index`] gives, whose first
1800
    /// block is the changes. Hashed in two parts so the log can read and
1801
    /// check the changes alone.
1802
    /// The index of `deps` if there is one, else the newest, which the
1803
    /// caller may bring up to date.
1804
    fn read_state_index(&self, deps: &[ChangeHash]) -> Option<(State, Vec<ChangeHash>)> {
1805
        use std::io::Read;
1806
        let _t = crate::timing::phase("load: state index");
1807
        let exact = self.state_index_path(deps);
1808
        let reading = crate::timing::phase("load:   of which reading the file");
1809
        let mut f = match fs::File::open(&exact) {
1810
            Ok(f) => {
1811
                // Used now: the newest, so the last to be dropped.
1812
                let _ = fs::File::options()
1813
                    .write(true)
1814
                    .open(&exact)
1815
                    .and_then(|f| f.set_modified(std::time::SystemTime::now()));
1816
                f
1817
            }
1818
            Err(_) => fs::File::open(self.state_indexes().first()?).ok()?,
1819
        };
1820
        let total = f.metadata().ok()?.len();
1821
        let mut word = [0u8; 4];
1822
        f.read_exact(&mut word).ok()?;
1823
        let n = u32::from_le_bytes(word) as usize;
1824
        let mut head = vec![0u8; 32 * n + 64 + 8];
1825
        f.read_exact(&mut head).ok()?;
1826
        let heads: Vec<ChangeHash> = head[..32 * n]
1827
            .chunks_exact(32)
1828
            .map(|c| ObjectRef(c.try_into().unwrap()))
1829
            .collect();
1830
        let (changes_sum, rest_sum) = (&head[32 * n..32 * n + 32], &head[32 * n + 32..32 * n + 64]);
1831
        let front_len = u64::from_le_bytes(head[32 * n + 64..].try_into().unwrap());
1832
        let at = (4 + head.len()) as u64;
1833
        if at.checked_add(front_len).is_none_or(|end| end > total) {
1834
            return None;
1835
        }
1836
        // The front only: the files' histories after it are read, each
1837
        // checked by its own hash, when a command builds that file.
1838
        let mut front = vec![0u8; front_len as usize];
1839
        f.read_exact(&mut front).ok()?;
1840
        drop(reading);
1841
        let checking = crate::timing::phase("load:   of which checking the file");
1842
        let split = 4 + u32::from_le_bytes(front.get(..4)?.try_into().unwrap()) as usize;
1843
        let (changes, rest) = (front.get(..split)?, front.get(split..)?);
1844
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1845
        if sum(changes) != changes_sum || sum(rest) != rest_sum {
1846
            return None;
1847
        }
1848
        drop(checking);
1849
        let histories = crate::state::Histories::File(
1850
            std::sync::Arc::new(f),
1851
            at + front_len,
1852
            total - at - front_len,
1853
        );
1854
        Some((State::read_index_front(&front, histories).ok()?, heads))
1855
    }
1856
1857
    /// The changes of this workspace's state index (the closure of its
1858
    /// heads), read without the rest of the index.
1859
    pub(crate) fn read_state_index_changes(
1860
        &self,
1861
    ) -> Option<std::collections::HashMap<ChangeHash, std::sync::Arc<crate::state::ChangeMeta>>>
1862
    {
1863
        use std::io::Read;
1864
        let _t = crate::timing::phase("load: state index changes");
1865
        let mut f = fs::File::open(self.state_indexes().first()?).ok()?;
1866
        let mut word = [0u8; 4];
1867
        f.read_exact(&mut word).ok()?;
1868
        let n = u32::from_le_bytes(word) as usize;
1869
        // Heads, the two sums, the front's length, then the changes block.
1870
        let mut head = vec![0u8; 32 * n + 64 + 8 + 4];
1871
        f.read_exact(&mut head).ok()?;
1872
        let sum = &head[32 * n..32 * n + 32];
1873
        let len = u32::from_le_bytes(head[32 * n + 72..].try_into().unwrap()) as usize;
1874
        let mut changes = vec![0u8; 4 + len];
1875
        changes[..4].copy_from_slice(&head[32 * n + 72..]);
1876
        f.read_exact(&mut changes[4..]).ok()?;
1877
        let checking = crate::timing::phase("load:   of which checking");
1878
        let mut h = blake3::Hasher::new();
1879
        h.update_rayon(&changes);
1880
        if h.finalize().as_bytes() != sum {
1881
            return None;
1882
        }
1883
        drop(checking);
1884
        let _decoding = crate::timing::phase("load:   of which decoding");
1885
        State::read_index_changes(&changes[4..]).ok()
1886
    }
1887
1888
    /// Save `st`, the history-only state of `deps`, as this workspace's
1889
    /// state index; quietly nothing when it cannot be (it is only a cache).
1890
    pub(crate) fn write_state_index(&self, deps: &[ChangeHash], st: &State) {
1891
        let _t = crate::timing::phase("write: state index");
1892
        let encoding = crate::timing::phase("write:   of which encoding");
1893
        let Some(body) = st.write_index() else {
1894
            return;
1895
        };
1896
        drop(encoding);
1897
        #[cfg(test)]
1898
        assert_eq!(
1899
            State::read_index(&body).ok().and_then(|s| s.write_index()),
1900
            Some(body.clone()),
1901
            "a state index reads back as written"
1902
        );
1903
        let mut heads = st.maximal(deps);
1904
        heads.sort();
1905
        let mut w = crate::flat::Writer::default();
1906
        w.count(heads.len());
1907
        for h in &heads {
1908
            w.object(h);
1909
        }
1910
        // The body is the front's length, the front, then the files'
1911
        // histories, which carry their own hashes: the sums cover the
1912
        // front's changes block and the rest of the front.
1913
        let front_len = u64::from_le_bytes(body[..8].try_into().unwrap()) as usize;
1914
        let front = &body[8..8 + front_len];
1915
        let split = 4 + u32::from_le_bytes(front[..4].try_into().unwrap()) as usize;
1916
        let sum = |b: &[u8]| *blake3::Hasher::new().update_rayon(b).finalize().as_bytes();
1917
        w.fixed(&sum(&front[..split]));
1918
        w.fixed(&sum(&front[split..]));
1919
        w.fixed(&body);
1920
        let path = self.state_index_path(&heads);
1921
        let _ = fs::create_dir_all(self.oxy.join("index"));
1922
        let _ = write_cache(&path, &w.0);
1923
        // The last two used: the index of a state moved away from stays for
1924
        // a move back. Older ones (and the unnamed one of before) go.
1925
        for old in self.state_indexes().iter().skip(STATE_INDEXES_KEPT) {
1926
            let _ = fs::remove_file(old);
1927
        }
1928
        let _ = fs::remove_file(
1929
            self.oxy
1930
                .join("index")
1931
                .join(format!("state-{}", self.workspace.to_hex())),
1932
        );
1933
    }
1934
1935
    fn locks_dir(&self) -> PathBuf {
1936
        self.oxy.join("locks")
1937
    }
1938
1939
    /// Whether `path` is locked locally for editing (spec §18, advisory).
1940
    pub fn is_locked(&self, path: &str) -> bool {
1941
        self.locks_dir().join(path.replace('/', "%2F")).exists()
1942
    }
1943
1944
    /// Take the advisory local lock on a `lockable` file and make it writable.
1945
    pub fn lock_path(&self, path: &str) -> Result<()> {
1946
        let attrs = self.disk_attributes();
1947
        if !attrs.lookup(path).lockable {
1948
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
1949
        }
1950
        fs::create_dir_all(self.locks_dir())?;
1951
        write_atomic(
1952
            &self.locks_dir().join(path.replace('/', "%2F")),
1953
            std::process::id().to_string().as_bytes(),
1954
        )?;
1955
        set_readonly(&self.root.join(path), false)?;
1956
        Ok(())
1957
    }
1958
1959
    /// Release the local lock and make the file read-only again.
1960
    pub fn unlock_path(&self, path: &str) -> Result<()> {
1961
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
1962
        if self.root.join(path).exists() {
1963
            set_readonly(&self.root.join(path), true)?;
1964
        }
1965
        Ok(())
1966
    }
1967
1968
    /// Whether a repository path is inside the sparse filter (spec §17).
1969
    pub fn in_scope(&self, path: &str) -> bool {
1970
        self.config.sparse_paths.is_empty()
1971
            || self
1972
                .config
1973
                .sparse_paths
1974
                .iter()
1975
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
1976
    }
1977
1978
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
1979
        self.walk_working_copy_with(None, &BTreeMap::new(), None)
1980
    }
1981
1982
    /// Walk the working copy; with a manifest, a file whose size and mtime
1983
    /// match it is not read: an opaque file yields its known blob, and a
1984
    /// text file whose recorded graph key equals its base graph's key in
1985
    /// `keys` (path → key) is marked unchanged; other text files are read
1986
    /// but keep their known hash. Files modified within two seconds of the
1987
    /// manifest are never trusted (a racy stat).
1988
    ///
1989
    /// `.oxyattributes` files are always read, since their content is
1990
    /// needed; and when any of them is not known unchanged (added, removed,
1991
    /// edited, or changed in the base), no text file is taken as unchanged,
1992
    /// because attributes decide how a file compares with the base.
1993
    ///
1994
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
1995
    /// (the base state's files) that exists on disk is included even when
1996
    /// an ignore rule matches it, as in Git.
1997
    fn walk_working_copy_with(
1998
        &self,
1999
        cache: Option<&prompt::Manifest>,
2000
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
2001
        keys: Option<&KeyOf>,
2002
    ) -> Result<BTreeMap<String, FsEntry>> {
2003
        let mut out: BTreeMap<String, FsEntry>;
2004
        let sparse = &self.config.sparse_paths;
2005
        let in_scope = |p: &str| {
2006
            sparse.is_empty()
2007
                || sparse
2008
                    .iter()
2009
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
2010
        };
2011
        let walk_phase = crate::timing::phase("walk:   of which listing");
2012
        let walk::Listing {
2013
            files,
2014
            symlinks,
2015
            nested,
2016
            dirs,
2017
        } = match self.listing_cache.take() {
2018
            Some(l) => l,
2019
            // Ignore rules apply to untracked paths only, so the base's
2020
            // files are not matched against them (an added file is: a rule
2021
            // written after it was snapshotted leaves it out again).
2022
            None => walk::list_knowing(&self.root, &in_scope, &|p: &str| tracked.contains_key(p))?,
2023
        };
2024
        let keys = keys.filter(|k| {
2025
            let on_disk: HashSet<&str> = files.iter().map(|(r, _, _)| r.as_str()).collect();
2026
            let attrs_unchanged =
2027
                files
2028
                    .iter()
2029
                    .filter(|(r, _, _)| is_attributes(r))
2030
                    .all(|(rel, _, meta)| {
2031
                        stat_cached(rel, meta, cache)
2032
                            .is_some_and(|e| e.graph.is_some() && e.graph == k(rel))
2033
                    });
2034
            let none_removed = tracked
2035
                .keys()
2036
                .filter(|r| is_attributes(r))
2037
                .all(|r| on_disk.contains(r.as_str()));
2038
            attrs_unchanged && none_removed
2039
        });
2040
        *self.walked_dirs.borrow_mut() =
2041
            Some((dirs, nested.iter().map(|d| self.rel_path(d)).collect()));
2042
        drop(walk_phase);
2043
        let _read_phase = crate::timing::phase("walk:   of which stat and compare");
2044
        // Reading files is most of a walk's cost; do it in parallel.
2045
        {
2046
            use rayon::prelude::*;
2047
            let mut read: Vec<(String, FsEntry)> = files
2048
                .par_iter()
2049
                .map(|(rel, path, meta)| {
2050
                    // A key is worked out only for a file the manifest
2051
                    // knows with the same stat and a key of its own.
2052
                    let key = keys
2053
                        .filter(|_| !is_attributes(rel))
2054
                        .filter(|_| {
2055
                            stat_cached(rel, meta, cache).is_some_and(|e| e.graph.is_some())
2056
                        })
2057
                        .and_then(|k| k(rel));
2058
                    Ok((rel.clone(), read_file_entry(rel, path, meta, cache, key)?))
2059
                })
2060
                .collect::<Result<Vec<_>>>()?;
2061
            for (rel, e) in read.iter_mut() {
2062
                // A cached blob the store lost (gc, a partial clone): read the file after all.
2063
                if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
2064
                    e.content = std::sync::Arc::new(fs::read(self.root.join(rel.as_str()))?);
2065
                    e.blob = None;
2066
                }
2067
            }
2068
            // The listing is in path order, so the map is built without
2069
            // searching.
2070
            out = read.into_iter().collect();
2071
            for (rel, target) in symlinks {
2072
                out.insert(rel, FsEntry::new(NodeKind::Symlink, false, target));
2073
            }
2074
        }
2075
        drop(_read_phase);
2076
        let _rest = crate::timing::phase("walk:   of which subrepos and hidden");
2077
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
2078
        // already tracked as subrepo nodes, they contribute their pin;
2079
        // unregistered ones are left alone.
2080
        let modules = self.modules_on_disk();
2081
        let removed = self.removed_subrepos();
2082
        for rel in &removed {
2083
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
2084
                self.clear_removed_subrepo(rel);
2085
            }
2086
        }
2087
        let mut untracked_nested = Vec::new();
2088
        for dir in nested {
2089
            let rel = self.rel_path(&dir);
2090
            if !self.in_scope(&rel) || removed.contains(&rel) {
2091
                continue;
2092
            }
2093
            let registered = modules.entries.get(&rel);
2094
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
2095
            {
2096
                untracked_nested.push(rel);
2097
                continue;
2098
            }
2099
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
2100
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
2101
        }
2102
        untracked_nested.sort();
2103
        *self.untracked_nested.borrow_mut() = untracked_nested;
2104
        // Tracked paths the ignore rules hid.
2105
        for (rel, (kind, blob)) in tracked {
2106
            if out.contains_key(rel) || !self.in_scope(rel) {
2107
                continue;
2108
            }
2109
            let path = self.root.join(rel);
2110
            if *kind == NodeKind::Subrepo {
2111
                if removed.contains(rel) {
2112
                    continue;
2113
                }
2114
                let present =
2115
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
2116
                if present {
2117
                    let pin = subrepos::read_pin(
2118
                        &path,
2119
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
2120
                    )?;
2121
                    out.insert(
2122
                        rel.clone(),
2123
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
2124
                    );
2125
                } else if let Some(b) = blob {
2126
                    // Not cloned (or emptied): the pin stays as recorded, as a
2127
                    // Git gitlink does when its directory is absent.
2128
                    out.insert(
2129
                        rel.clone(),
2130
                        FsEntry {
2131
                            blob: Some(*b),
2132
                            ..FsEntry::new(NodeKind::Subrepo, false, vec![])
2133
                        },
2134
                    );
2135
                }
2136
                continue;
2137
            }
2138
            let Ok(meta) = fs::symlink_metadata(&path) else {
2139
                continue;
2140
            };
2141
            let ft = meta.file_type();
2142
            if ft.is_symlink() {
2143
                let target = fs::read_link(&path)?;
2144
                out.insert(
2145
                    rel.clone(),
2146
                    FsEntry::new(
2147
                        NodeKind::Symlink,
2148
                        false,
2149
                        target.to_string_lossy().as_bytes().to_vec(),
2150
                    ),
2151
                );
2152
            } else if ft.is_file() {
2153
                let e = self.file_entry(rel, &path, &walk::Stat::of(&meta), cache)?;
2154
                out.insert(rel.clone(), e);
2155
            }
2156
        }
2157
        Ok(out)
2158
    }
2159
2160
    /// The entry for one regular file, read or served from the stat cache.
2161
    fn file_entry(
2162
        &self,
2163
        rel: &str,
2164
        path: &Path,
2165
        meta: &walk::Stat,
2166
        cache: Option<&prompt::Manifest>,
2167
    ) -> Result<FsEntry> {
2168
        let mut e = read_file_entry(rel, path, meta, cache, None)?;
2169
        if e.content.is_empty() && e.blob.is_some_and(|b| !self.store.has(&b)) {
2170
            e.content = std::sync::Arc::new(fs::read(path)?);
2171
            e.blob = None;
2172
        }
2173
        Ok(e)
2174
    }
2175
2176
    /// The non-directory paths of a snapshot with their kinds, for the
2177
    /// walker's `tracked` set.
2178
    pub(crate) fn tracked_kinds(
2179
        snapshot: &Snapshot,
2180
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
2181
        snapshot
2182
            .files
2183
            .iter()
2184
            .filter(|(_, f)| f.kind != NodeKind::Dir)
2185
            .map(|(p, f)| {
2186
                let blob = match &f.content {
2187
                    FileContent::Opaque { blobs } => blobs.first().copied(),
2188
                    _ => None,
2189
                };
2190
                (p.clone(), (f.kind, blob))
2191
            })
2192
            .collect()
2193
    }
2194
2195
    /// A path under the root as a `/`-separated relative string.
2196
    pub(crate) fn rel_path(&self, path: &Path) -> String {
2197
        path.strip_prefix(&self.root)
2198
            .unwrap_or(path)
2199
            .components()
2200
            .map(|c| c.as_os_str().to_string_lossy().to_string())
2201
            .collect::<Vec<_>>()
2202
            .join("/")
2203
    }
2204
}
2205
2206
impl Repo {
2207
    /// Changes reachable from the bookmark and the working copy, newest first.
2208
    pub fn log(&self) -> Result<Vec<LogEntry>> {
2209
        let heads = self.bookmark_heads()?;
2210
        if self.bare {
2211
            return self.log_state(&heads);
2212
        }
2213
        let (wc_hash, wc) = self.working_copy()?;
2214
        let mut all = heads.clone();
2215
        all.push(wc_hash);
2216
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
2217
        let mut entries: Vec<LogEntry> = Vec::new();
2218
        // A shallow clone knows changes beyond its boundary from a
2219
        // checkpoint's metadata only: its log comes from the state.
2220
        let metas = if self.is_shallow() {
2221
            self.load_state_history(&all)?
2222
                .changes()
2223
                .map(|(h, m)| (*h, m.clone()))
2224
                .collect()
2225
        } else {
2226
            // The working copy's change is in hand, and is never in the
2227
            // state index: its metadata is not looked up again.
2228
            let mut below: Vec<ChangeHash> = head_set.iter().copied().collect();
2229
            below.extend(wc.deps.iter().copied());
2230
            let _t = crate::timing::phase("log: metadata");
2231
            let mut metas = self.metas_of(&below)?;
2232
            if !metas.iter().any(|(h, _)| *h == wc_hash) {
2233
                metas.push((wc_hash, crate::state::ChangeMeta::of(&wc)));
2234
            }
2235
            metas
2236
        };
2237
        for (h, meta) in metas {
2238
            entries.push(LogEntry {
2239
                hash: h,
2240
                change: meta,
2241
                is_working_copy: h == wc_hash,
2242
                is_head: head_set.contains(&h),
2243
            });
2244
        }
2245
        let _sorting = crate::timing::phase("log: sort");
2246
        // The hash makes the order total, so an unstable sort gives the same.
2247
        entries.sort_unstable_by(|a, b| {
2248
            b.is_working_copy
2249
                .cmp(&a.is_working_copy)
2250
                .then(b.change.hlc.cmp(&a.change.hlc))
2251
                .then(b.hash.cmp(&a.hash))
2252
        });
2253
        Ok(entries)
2254
    }
2255
2256
    /// A window of `log_state`: entries `offset..offset+limit` and the total
2257
    /// count, for paginated views.
2258
    pub fn log_window(
2259
        &self,
2260
        heads: &[ChangeHash],
2261
        offset: usize,
2262
        limit: usize,
2263
    ) -> Result<(Vec<LogEntry>, usize)> {
2264
        let all = self.log_state(heads)?;
2265
        let total = all.len();
2266
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
2267
    }
2268
2269
    /// The log of the state with these heads, newest first, with no working
2270
    /// copy involved (for hosted repositories and any explicit state).
2271
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
2272
        // The log needs change metadata only: neither graphs nor the tree.
2273
        if self.is_shallow() {
2274
            return Ok(self.log_of(&self.load_state_history(heads)?));
2275
        }
2276
        let metas = self.metas_of(heads)?;
2277
        let depended: BTreeSet<ChangeHash> = metas
2278
            .iter()
2279
            .flat_map(|(_, m)| m.deps.iter().copied())
2280
            .collect();
2281
        let mut entries: Vec<LogEntry> = metas
2282
            .into_iter()
2283
            .map(|(h, meta)| LogEntry {
2284
                hash: h,
2285
                is_head: !depended.contains(&h),
2286
                change: meta,
2287
                is_working_copy: false,
2288
            })
2289
            .collect();
2290
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
2291
        Ok(entries)
2292
    }
2293
2294
    /// Every change of the state with these heads and its metadata, read
2295
    /// without its operations ([`Store::get_change_meta`]). A change beyond
2296
    /// a shallow clone's boundary is left out.
2297
    pub fn metas_of(
2298
        &self,
2299
        heads: &[ChangeHash],
2300
    ) -> Result<Vec<(ChangeHash, crate::state::ChangeMeta)>> {
2301
        let boundary = self.boundary();
2302
        // The state index holds the metadata of its heads' closure: a
2303
        // change found there is not read from the store (a change object
2304
        // can be as large as the tree it adds).
2305
        let mut indexed = self.read_state_index_changes();
2306
        let _walk = crate::timing::phase("metadata: walk");
2307
        let (mut stored, mut from_store) = (0usize, std::time::Duration::ZERO);
2308
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2309
        let mut stack: Vec<ChangeHash> = heads.to_vec();
2310
        let mut out = Vec::with_capacity(indexed.as_ref().map_or(0, |m| m.len()));
2311
        while let Some(h) = stack.pop() {
2312
            if !seen.insert(h) {
2313
                continue;
2314
            }
2315
            // Taken out of the index's map, each once: not copied.
2316
            if let Some(meta) = indexed.as_mut().and_then(|m| m.remove(&h)) {
2317
                #[cfg(test)]
2318
                assert_eq!(
2319
                    *meta,
2320
                    self.store.get_change_meta(&h)?,
2321
                    "the state index holds a change's metadata"
2322
                );
2323
                let meta = std::sync::Arc::unwrap_or_clone(meta);
2324
                stack.extend(meta.deps.iter().copied());
2325
                out.push((h, meta));
2326
                continue;
2327
            }
2328
            let started = std::time::Instant::now();
2329
            let meta = match self.store.get_change_meta(&h) {
2330
                Ok(m) => m,
2331
                Err(crate::store::StoreError::NotFound(_)) if boundary.contains(&h) => continue,
2332
                Err(e) => return Err(e.into()),
2333
            };
2334
            stored += 1;
2335
            from_store += started.elapsed();
2336
            stack.extend(meta.deps.iter().copied());
2337
            out.push((h, meta));
2338
        }
2339
        if stored > 0 && crate::timing::enabled() {
2340
            eprintln!("timing metadata: {stored} changes read whole, {from_store:.2?}");
2341
        }
2342
        Ok(out)
2343
    }
2344
2345
    /// The log of a state already loaded, newest first.
2346
    /// The history of lines `first..=last` (1-based) of `path` in the
2347
    /// state `heads` make (spec §27): every change that inserted or
2348
    /// deleted one of their atoms, or an atom deleted from between them,
2349
    /// newest first. Exact, as atoms keep their identity across edits.
2350
    pub fn line_history(
2351
        &self,
2352
        heads: &[ChangeHash],
2353
        path: &str,
2354
        first: usize,
2355
        last: usize,
2356
    ) -> Result<Vec<LogEntry>> {
2357
        if first == 0 || last < first {
2358
            return fail(format!(
2359
                "lines {first},{last}: expected FIRST,LAST from 1 with FIRST ≤ LAST"
2360
            ));
2361
        }
2362
        let mut state = self.load_state_history(heads)?;
2363
        let Some(node) = state.tree().view().entries.get(path).map(|e| e.node) else {
2364
            return fail(format!("{path} is not in that state"));
2365
        };
2366
        self.load_graphs_of(&mut state, &[node])?;
2367
        let live = state.live_lines(&node);
2368
        if last > live.len() {
2369
            return fail(format!(
2370
                "{path} has {} lines; asked for {first},{last}",
2371
                live.len()
2372
            ));
2373
        }
2374
        let Some(g) = state.file(&node) else {
2375
            return fail(format!("{path} is not a text file"));
2376
        };
2377
        let atoms = g.between(&live[first - 1].0, &live[last - 1].0);
2378
        let touched = g.touching(&atoms);
2379
        Ok(self
2380
            .log_of(&state)
2381
            .into_iter()
2382
            .filter(|e| touched.contains(&e.hash))
2383
            .collect())
2384
    }
2385
2386
    pub fn log_of(&self, state: &crate::state::State) -> Vec<LogEntry> {
2387
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
2388
        let mut entries: Vec<LogEntry> = state
2389
            .changes()
2390
            .map(|(h, meta)| LogEntry {
2391
                hash: *h,
2392
                change: meta.clone(),
2393
                is_working_copy: false,
2394
                is_head: head_set.contains(h),
2395
            })
2396
            .collect();
2397
        entries.sort_unstable_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
2398
        entries
2399
    }
2400
2401
    /// Resolve a spec to a set of heads: a bookmark's name, a remote's
2402
    /// bookmark as `REMOTE/NAME`, a tag name, or a single change
2403
    /// (`resolve_change`).
2404
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
2405
        let view = self.view()?;
2406
        if let Some(st) = view.bookmarks.get(spec) {
2407
            return Ok(self.store.get_state(st)?.heads);
2408
        }
2409
        if let Some((_, _, st)) = remote_bookmark(&view, spec) {
2410
            return Ok(self.store.get_state(&st)?.heads);
2411
        }
2412
        if let Some(heads) = self.tag_heads(spec)? {
2413
            return Ok(heads);
2414
        }
2415
        Ok(vec![self.resolve_change(spec)?])
2416
    }
2417
2418
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working
2419
    /// copy), bookmark, `REMOTE/NAME` or tag (the one head of its state).
2420
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
2421
        if spec == "@" {
2422
            return Ok(self.working_copy()?.0);
2423
        }
2424
        let view = self.view()?;
2425
        let named = match view.bookmarks.get(spec) {
2426
            Some(st) => Some(("bookmark", self.store.get_state(st)?.heads)),
2427
            None => match remote_bookmark(&view, spec) {
2428
                Some((_, _, st)) => Some(("bookmark", self.store.get_state(&st)?.heads)),
2429
                None => self.tag_heads(spec)?.map(|h| ("tag", h)),
2430
            },
2431
        };
2432
        if let Some((kind, heads)) = named {
2433
            return match heads.len() {
2434
                1 => Ok(heads[0]),
2435
                n => fail(format!("{kind} {spec} has {n} heads; name a change, or use it where a state is expected")),
2436
            };
2437
        }
2438
        if spec.is_empty() || spec == "#" {
2439
            return fail("empty change specifier");
2440
        }
2441
        let entries = self.log()?;
2442
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
2443
            entries
2444
                .iter()
2445
                .filter(|e| e.hash.starts_with_hex(hp))
2446
                .collect()
2447
        } else {
2448
            entries
2449
                .iter()
2450
                .filter(|e| e.change.change_id.starts_with_hex(spec))
2451
                .collect()
2452
        };
2453
        match matches.len() {
2454
            1 => Ok(matches[0].hash),
2455
            0 => match self.resolve_in_remotes(spec)? {
2456
                Some(h) => Ok(h),
2457
                None => fail(format!("no change matches {spec:?}")),
2458
            },
2459
            _ => {
2460
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
2461
                if ids.len() == 1 {
2462
                    fail(format!(
2463
                        "change {spec} is divergent: {} variants",
2464
                        matches.len()
2465
                    ))
2466
                } else {
2467
                    fail(format!("{spec:?} is ambiguous"))
2468
                }
2469
            }
2470
        }
2471
    }
2472
2473
    /// A change no local bookmark holds, found by id or `#hash` prefix in
2474
    /// the remote bookmarks' states: fetched but not yet pulled (oxygen#56).
2475
    /// `None` when none matches, or more than one.
2476
    fn resolve_in_remotes(&self, spec: &str) -> Result<Option<ChangeHash>> {
2477
        let view = self.view()?;
2478
        let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
2479
        for bookmarks in view.remotes.values() {
2480
            for st in bookmarks.values() {
2481
                let heads = self.store.get_state(st)?.heads;
2482
                for e in self.log_state(&heads)? {
2483
                    let hit = match spec.strip_prefix('#') {
2484
                        Some(hp) => e.hash.starts_with_hex(hp),
2485
                        None => e.change.change_id.starts_with_hex(spec),
2486
                    };
2487
                    if hit {
2488
                        found.insert(e.hash);
2489
                    }
2490
                }
2491
            }
2492
        }
2493
        Ok((found.len() == 1).then(|| *found.first().unwrap()))
2494
    }
2495
2496
    /// Where a change is when no local bookmark or the working copy holds
2497
    /// it: the first remote bookmark that does (`origin/main`). `None` when
2498
    /// it is held locally, or nowhere.
2499
    pub fn remote_only_location(&self, hash: &ChangeHash) -> Result<Option<String>> {
2500
        if self.log()?.iter().any(|e| e.hash == *hash) {
2501
            return Ok(None);
2502
        }
2503
        let view = self.view()?;
2504
        for (remote, bookmarks) in &view.remotes {
2505
            for (name, st) in bookmarks {
2506
                let heads = self.store.get_state(st)?.heads;
2507
                if self.log_state(&heads)?.iter().any(|e| e.hash == *hash) {
2508
                    return Ok(Some(format!("{remote}/{name}")));
2509
                }
2510
            }
2511
        }
2512
        Ok(None)
2513
    }
2514
2515
    /// Human-readable description of what a change does, with line content.
2516
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
2517
        let change = self.store.get_change(hash)?;
2518
        let (base, base_snapshot) = self.change_base(&change)?;
2519
        Ok(render_change(&change, &base, &base_snapshot))
2520
    }
2521
2522
    /// The base state of `change` (its dependencies) and its rendering, as
2523
    /// much as showing the change needs: the whole tree, and the graphs and
2524
    /// contents of the files the change edits. Other text files are left
2525
    /// unrendered ([`Snapshot::unrendered`]).
2526
    pub fn change_base(&self, change: &Change) -> Result<(State, Snapshot)> {
2527
        let base = self.load_state_history(&change.deps)?;
2528
        self.render_base_for(change, base)
2529
    }
2530
2531
    /// [`Repo::change_base`] with the base already loaded (the working
2532
    /// copy's comes from the state index).
2533
    pub(crate) fn render_base_for(
2534
        &self,
2535
        change: &Change,
2536
        mut base: State,
2537
    ) -> Result<(State, Snapshot)> {
2538
        let _t = crate::timing::phase("diff: render the base");
2539
        let edited: std::collections::HashSet<NodeId> =
2540
            change.edits.iter().map(|e| e.node()).collect();
2541
        let nodes: Vec<NodeId> = edited.iter().copied().collect();
2542
        self.load_graphs_of(&mut base, &nodes)?;
2543
        let snapshot = {
2544
            let _t = crate::timing::phase("diff:   of which materialize");
2545
            base.materialize_nodes(&edited)
2546
        };
2547
        Ok((base, snapshot))
2548
    }
2549
}
2550
2551
fn remove_any(path: &Path) -> std::io::Result<()> {
2552
    let m = fs::symlink_metadata(path)?;
2553
    if m.is_dir() {
2554
        fs::remove_dir_all(path)
2555
    } else {
2556
        fs::remove_file(path)
2557
    }
2558
}
2559
2560
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
2561
    let mut perms = fs::metadata(path)?.permissions();
2562
    perms.set_readonly(readonly);
2563
    fs::set_permissions(path, perms)
2564
}
2565
2566
#[cfg(unix)]
2567
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
2568
    use std::os::unix::fs::PermissionsExt;
2569
    let mut perms = fs::metadata(path)?.permissions();
2570
    let mode = perms.mode();
2571
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
2572
    if want != mode {
2573
        perms.set_mode(want);
2574
        fs::set_permissions(path, perms)?;
2575
    }
2576
    Ok(())
2577
}
2578
#[cfg(not(unix))]
2579
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
2580
    Ok(())
2581
}
2582
2583
#[cfg(unix)]
2584
pub(crate) fn is_executable(m: &fs::Metadata) -> bool {
2585
    use std::os::unix::fs::PermissionsExt;
2586
    m.permissions().mode() & 0o111 != 0
2587
}
2588
#[cfg(not(unix))]
2589
pub(crate) fn is_executable(_m: &fs::Metadata) -> bool {
2590
    false
2591
}
2592
2593
fn op_ref(k: OpKey) -> OpRef {
2594
    OpRef {
2595
        change: k.0,
2596
        index: k.1,
2597
    }
2598
}
2599
2600
fn split_path(path: &str) -> (&str, &str) {
2601
    match path.rfind('/') {
2602
        Some(i) => (&path[..i], &path[i + 1..]),
2603
        None => ("", path),
2604
    }
2605
}
2606
2607
/// Whether `rel` is an attributes file (spec §7.6).
2608
fn is_attributes(rel: &str) -> bool {
2609
    rel == ".oxyattributes" || rel.ends_with("/.oxyattributes")
2610
}
2611
2612
/// The manifest entry for `rel` when its size and mtime match it outside
2613
/// the racy window.
2614
fn stat_cached<'m>(
2615
    rel: &str,
2616
    meta: &walk::Stat,
2617
    cache: Option<&'m prompt::Manifest>,
2618
) -> Option<&'m prompt::ManifestEntry> {
2619
    let m = cache?;
2620
    let e = m.entries.get(rel)?;
2621
    let racy = meta.mtime_ns + 2_000_000_000 >= m.written_ns;
2622
    (e.size == meta.size && e.mtime_ns == meta.mtime_ns && !racy).then_some(e)
2623
}
2624
2625
/// Read one working-copy file, or serve it from the stat cache (spec
2626
/// §12.3). With a manifest whose stat for it is unchanged (and not racy),
2627
/// an opaque file is not read at all (its stored blob stands in), and a
2628
/// text file the manifest recorded equal to a base graph whose key is
2629
/// `key`, the key the base has now, is not read either: equal keys mean
2630
/// equal renderings, so it still equals the base. Touches no repository
2631
/// state, so the walk runs it in parallel; the caller checks that a cached
2632
/// blob is still in the store.
2633
fn read_file_entry(
2634
    rel: &str,
2635
    path: &Path,
2636
    meta: &walk::Stat,
2637
    cache: Option<&prompt::Manifest>,
2638
    key: Option<[u8; 32]>,
2639
) -> Result<FsEntry> {
2640
    let exec = meta.exec;
2641
    let stat = Some((meta.size, meta.mtime_ns));
2642
    let mut e = match stat_cached(rel, meta, cache) {
2643
        Some(e) if e.blob.is_some() => FsEntry {
2644
            blob: e.blob,
2645
            content_hash: Some(e.hash),
2646
            ..FsEntry::new(NodeKind::File, exec, vec![])
2647
        },
2648
        Some(e) if key.is_some() && e.graph == key => FsEntry {
2649
            content_hash: Some(e.hash),
2650
            unchanged: true,
2651
            graph_key: e.graph,
2652
            ..FsEntry::new(NodeKind::File, exec, vec![])
2653
        },
2654
        Some(e) => FsEntry {
2655
            content_hash: Some(e.hash),
2656
            ..FsEntry::new(NodeKind::File, exec, fs::read(path)?)
2657
        },
2658
        None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
2659
    };
2660
    // The stat the manifest records: taken before the read, so a file that
2661
    // changes meanwhile is read again next time.
2662
    e.stat = stat;
2663
    Ok(e)
2664
}