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