OXYGENHUB
# 62794ecc7f74 oxygen / crates / oxy-core / src / repo / mod.rs
48.8 KiB · Rust · last changed Git import verified commit by commit; two dependency bugs fixed 1 month ago source blame history raw
1
//! A repository on disk: the `.oxy` directory, one workspace, the operation
2
//! log, and the working-copy change (spec §12, §13.1).
3
//!
4
//! Not yet implemented from the spec: packs, checkpoints, multiple
5
//! workspaces, multi-signer policy updates, and the `objects`/`checkpoint`
6
//! endpoints. A repository without a policy is unverified and accepts
7
//! unsigned pushes; with one, everything received is checked (spec §14.5). Changes are signed individually when `core.sign` is
8
//! `change`; the default `seal` leaves them unsigned until push exists.
9
10
use crate::attest::{Attest, AttestBody};
11
use crate::diff::{ranges, split_lines, text_edits};
12
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
13
use crate::identity::{verify as verify_signature, Domain, Identity, SecretKey, Signature};
14
use crate::ids::{ChangeId, NodeId, WorkspaceId};
15
use crate::objects::{
16
    Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp,
17
};
18
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
19
use crate::protocol::{
20
    open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef,
21
    SignedAttest, SignedPolicy,
22
};
23
use crate::state::{FileContent, Snapshot, State};
24
use crate::store::{Store, StoreError};
25
#[allow(unused_imports)]
26
use crate::subrepo::Pin;
27
use crate::tree::OpKey;
28
use rand::RngCore;
29
use std::collections::{BTreeMap, BTreeSet, HashMap};
30
use std::fs;
31
use std::io::Write;
32
use std::path::{Path, PathBuf};
33
34
pub const OXY_DIR: &str = ".oxy";
35
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
36
const FORMAT1_LINE: &str = "oxy repository format 1\n";
37
const BINARY_SNIFF: usize = 8 * 1024;
38
/// Loose objects tolerated before a commit packs them (spec §13.4).
39
pub const AUTOPACK_THRESHOLD: usize = 4096;
40
41
#[derive(Debug, thiserror::Error)]
42
pub enum RepoError {
43
    #[error("io: {0}")]
44
    Io(#[from] std::io::Error),
45
    #[error(transparent)]
46
    Store(#[from] StoreError),
47
    #[error(transparent)]
48
    Object(#[from] crate::objects::ObjectError),
49
    #[error(transparent)]
50
    State(#[from] crate::state::StateError),
51
    #[error("{0}")]
52
    Msg(String),
53
}
54
55
pub type Result<T> = std::result::Result<T, RepoError>;
56
57
fn fail<T>(s: impl Into<String>) -> Result<T> {
58
    Err(RepoError::Msg(s.into()))
59
}
60
61
mod bookmarks;
62
mod checkout;
63
mod checkpoint;
64
mod config;
65
mod doctor;
66
mod fsck;
67
mod gc;
68
mod git;
69
mod history;
70
mod hooks;
71
mod hosted;
72
mod identity;
73
mod inspect;
74
mod policy;
75
mod prompt;
76
mod snapshot;
77
mod subrepos;
78
mod sync;
79
mod tags;
80
#[cfg(test)]
81
mod tests;
82
mod workspace;
83
84
pub use bookmarks::{BookmarkInfo, MergeReport};
85
pub use checkout::CheckoutReport;
86
pub use config::{parse_size, read_config_file, Config};
87
pub use doctor::{Check, DoctorReport, Health};
88
pub use fsck::{FsckReport, Problem, Severity};
89
pub use gc::GcReport;
90
pub use git::{GitExportReport, GitImportReport, GitVerifyReport};
91
pub use hooks::{json_array, json_str, HookOutcome};
92
pub use hosted::FileEdit;
93
pub use identity::{Rotation, SignatureStatus};
94
pub use inspect::{BisectStep, BlameLine};
95
pub use policy::PolicyUpdate;
96
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT, GLYPH_PROMPT_FORMAT};
97
pub use snapshot::{
98
    added_node_paths, diff_files_of, has_conflict_markers, is_binary, referenced_changes,
99
    render_change, render_hunks, similarity, ChangeStatus, DiffHunk, FileDiff, Hunk, PathStatus,
100
    Selection, SnapshotResult,
101
};
102
pub use subrepos::{SubrepoInfo, SubrepoSync};
103
pub use sync::{FetchReport, PullReport, PushReport, RefUpdated};
104
pub use tags::TagInfo;
105
pub use workspace::{FileLock, SnapshotLock, WorkspaceInfo};
106
107
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
108
    Ok(crate::durable::write_atomic(path, data)?)
109
}
110
111
pub struct LogEntry {
112
    pub hash: ChangeHash,
113
    /// Metadata from the state; the full change may be absent in a shallow repository.
114
    pub change: crate::state::ChangeMeta,
115
    pub is_working_copy: bool,
116
    pub is_head: bool,
117
}
118
119
/// A file as found on disk or in an imported tree.
120
pub(crate) struct FsEntry {
121
    pub kind: NodeKind,
122
    pub exec: bool,
123
    /// File content, or a symlink's target. Empty when `blob` is set.
124
    pub content: Vec<u8>,
125
    /// The stored blob of an opaque file whose size and mtime are unchanged
126
    /// since the last manifest (spec §12.3 stat cache); the content was not
127
    /// read.
128
    pub blob: Option<ObjectRef>,
129
    /// BLAKE3 of the content, carried over from the manifest when the stat
130
    /// is unchanged, so the manifest can be rewritten without rehashing.
131
    pub content_hash: Option<String>,
132
}
133
134
impl FsEntry {
135
    pub(crate) fn new(kind: NodeKind, exec: bool, content: Vec<u8>) -> FsEntry {
136
        FsEntry {
137
            kind,
138
            exec,
139
            content,
140
            blob: None,
141
            content_hash: None,
142
        }
143
    }
144
}
145
146
pub struct Repo {
147
    /// Oxygen-pinned subrepos skipped by the running Git export.
148
    pub(crate) git_export_skipped: std::cell::Cell<usize>,
149
    root: PathBuf,
150
    oxy: PathBuf,
151
    store: Store,
152
    workspace: WorkspaceId,
153
    /// A hosted repository with no working copy (spec §12.2, hub spec §4.1).
154
    bare: bool,
155
    keys_dir: PathBuf,
156
    user_config: PathBuf,
157
    pub config: Config,
158
}
159
160
/// Marker file of a bare repository, inside `.oxy/`.
161
const BARE_MARKER: &str = "bare";
162
/// Marker of a hosted repository that has no id yet: the first push binds
163
/// it to the pusher's id (spec §16.1).
164
const UNBOUND_MARKER: &str = "unbound";
165
166
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
167
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
168
pub fn default_home() -> PathBuf {
169
    if let Ok(h) = std::env::var("OXY_HOME") {
170
        return PathBuf::from(h);
171
    }
172
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
173
        return PathBuf::from(x).join("oxy");
174
    }
175
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
176
    PathBuf::from(home).join(".config").join("oxy")
177
}
178
179
pub fn default_keys_dir() -> PathBuf {
180
    default_home().join("keys")
181
}
182
183
pub fn default_user_config() -> PathBuf {
184
    default_home().join("config.toml")
185
}
186
187
/// Where `create_identity` records the author.
188
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189
pub enum IdentityScope {
190
    /// The user file: every repository of this user signs with it.
191
    User,
192
    /// This repository only.
193
    Repo,
194
}
195
196
impl Repo {
197
    // ------------------------------------------------------------ lifecycle
198
199
    pub fn init(root: &Path) -> Result<Repo> {
200
        let mut id = [0u8; 16];
201
        rand::rngs::OsRng.fill_bytes(&mut id);
202
        Self::init_with_id(root, id)
203
    }
204
205
    /// Initialize a repository with a given repository ID (clones share the
206
    /// ID of their origin, spec §14.4).
207
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
208
        fs::create_dir_all(root)?;
209
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
210
        let oxy = root.join(OXY_DIR);
211
        if oxy.exists() {
212
            return fail(format!("{} is already an oxy repository", root.display()));
213
        }
214
        fs::create_dir_all(oxy.join("ops"))?;
215
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
216
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
217
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
218
        config.save(&oxy.join("config"))?;
219
        let workspace = WorkspaceId::random();
220
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
221
        let store = Store::open(oxy.join("objects"))?;
222
        let repo = Repo {
223
            git_export_skipped: Default::default(),
224
            root,
225
            oxy,
226
            store,
227
            workspace,
228
            bare: false,
229
            keys_dir: default_keys_dir(),
230
            user_config: default_user_config(),
231
            config,
232
        };
233
        repo.register_workspace(&workspace, &repo.root)?;
234
235
        let wc = repo.new_working_copy(vec![], "");
236
        let wc_hash = repo.store.put_change(&wc)?;
237
        let mut view = View::default();
238
        view.bookmarks.insert(
239
            repo.config.bookmark.clone(),
240
            repo.store.put_state(&StateObject::new(vec![]))?,
241
        );
242
        view.workspaces.insert(workspace, wc_hash);
243
        repo.record_op(&[], "oxy init", view)?;
244
        Ok(repo)
245
    }
246
247
    /// Create a bare repository: an object store, operation log and
248
    /// references with no workspace and no working copy, for hosting
249
    /// (hub spec §4.1). `root` holds `.oxy/` and nothing else.
250
    pub fn init_bare(root: &Path) -> Result<Repo> {
251
        let mut id = [0u8; 16];
252
        rand::rngs::OsRng.fill_bytes(&mut id);
253
        Self::init_bare_with_id(root, id)
254
    }
255
256
    pub fn init_bare_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
257
        fs::create_dir_all(root)?;
258
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
259
        let oxy = root.join(OXY_DIR);
260
        if oxy.exists() {
261
            return fail(format!("{} is already an oxy repository", root.display()));
262
        }
263
        fs::create_dir_all(oxy.join("ops"))?;
264
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
265
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
266
        write_atomic(&oxy.join(BARE_MARKER), b"")?;
267
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
268
        config.save(&oxy.join("config"))?;
269
        let store = Store::open(oxy.join("objects"))?;
270
        let repo = Repo {
271
            git_export_skipped: Default::default(),
272
            root,
273
            oxy,
274
            store,
275
            workspace: WorkspaceId::ZERO,
276
            bare: true,
277
            keys_dir: default_keys_dir(),
278
            user_config: default_user_config(),
279
            config,
280
        };
281
        let mut view = View::default();
282
        view.bookmarks.insert(
283
            repo.config.bookmark.clone(),
284
            repo.store.put_state(&StateObject::new(vec![]))?,
285
        );
286
        repo.record_op(&[], "oxy init --bare", view)?;
287
        Ok(repo)
288
    }
289
290
    /// A bare repository with no id yet. Its `id()` is all zero until the
291
    /// first push binds it (`bind_id`), so an existing repository can be
292
    /// pushed to a freshly created hosted one and keep its identity.
293
    pub fn init_bare_unbound(root: &Path) -> Result<Repo> {
294
        let repo = Self::init_bare_with_id(root, [0; 16])?;
295
        fs::remove_file(repo.oxy.join("id"))?;
296
        write_atomic(&repo.oxy.join(UNBOUND_MARKER), b"")?;
297
        Ok(repo)
298
    }
299
300
    pub fn is_unbound(&self) -> bool {
301
        self.oxy.join(UNBOUND_MARKER).is_file()
302
    }
303
304
    /// Give an unbound repository its id.
305
    pub fn bind_id(&self, id: [u8; 16]) -> Result<()> {
306
        if !self.is_unbound() {
307
            return fail("this repository already has an id");
308
        }
309
        if id == [0; 16] {
310
            return fail("a repository id cannot be all zero");
311
        }
312
        write_atomic(&self.oxy.join("id"), hex::encode(id).as_bytes())?;
313
        fs::remove_file(self.oxy.join(UNBOUND_MARKER))?;
314
        Ok(())
315
    }
316
317
    /// Whether this repository has no working copy (`init_bare`).
318
    pub fn is_bare(&self) -> bool {
319
        self.bare
320
    }
321
322
    /// Open the repository containing `start` (searching upwards).
323
    pub fn open(start: &Path) -> Result<Repo> {
324
        let start = start.canonicalize()?;
325
        let mut dir: Option<&Path> = Some(&start);
326
        while let Some(d) = dir {
327
            let oxy = d.join(OXY_DIR);
328
            if oxy.is_file() {
329
                // A secondary workspace (spec §12.2): the file points at the repository.
330
                let text = fs::read_to_string(&oxy)?;
331
                let Some((shared, workspace)) = workspace::parse_workspace_file(&text) else {
332
                    return fail(format!("{} is not a valid workspace file", oxy.display()));
333
                };
334
                let format = fs::read_to_string(shared.join("format"))?;
335
                if format != FORMAT_LINE {
336
                    return fail(format!("unsupported repository format: {}", format.trim()));
337
                }
338
                let config = Config::load(Some(&default_user_config()), &shared.join("config"))?;
339
                let store = Store::open(shared.join("objects"))?;
340
                let mut repo = Repo {
341
                    git_export_skipped: Default::default(),
342
                    root: d.to_path_buf(),
343
                    oxy: shared,
344
                    store,
345
                    workspace,
346
                    bare: false,
347
                    keys_dir: default_keys_dir(),
348
                    user_config: default_user_config(),
349
                    config,
350
                };
351
                repo.apply_workspace_bookmark();
352
                return Ok(repo);
353
            }
354
            if oxy.is_dir() {
355
                let format = fs::read_to_string(oxy.join("format"))?;
356
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
357
                let bare = oxy.join(BARE_MARKER).is_file();
358
                let workspace = if bare {
359
                    WorkspaceId::ZERO
360
                } else {
361
                    WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
362
                        .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?
363
                };
364
                let store = Store::open(oxy.join("objects"))?;
365
                let mut repo = Repo {
366
                    git_export_skipped: Default::default(),
367
                    root: d.to_path_buf(),
368
                    oxy,
369
                    store,
370
                    workspace,
371
                    bare,
372
                    keys_dir: default_keys_dir(),
373
                    user_config: default_user_config(),
374
                    config,
375
                };
376
                if !bare {
377
                    repo.apply_workspace_bookmark();
378
                }
379
                if format == FORMAT1_LINE {
380
                    repo.migrate_format1()?;
381
                } else if format != FORMAT_LINE {
382
                    return fail(format!("unsupported repository format: {}", format.trim()));
383
                }
384
                return Ok(repo);
385
            }
386
            dir = d.parent();
387
        }
388
        fail(format!(
389
            "no oxy repository found at or above {}; start one with `oxy init` or `oxy clone URL`",
390
            start.display()
391
        ))
392
    }
393
394
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
395
    /// into format 2, where each bookmark names a `state` object.
396
    fn migrate_format1(&self) -> Result<()> {
397
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
398
        let head = ObjectRef::from_hex(hex.trim())
399
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
400
        // Collect the chain root-first.
401
        let mut chain: Vec<Format1Op> = Vec::new();
402
        let mut cur = Some(head);
403
        while let Some(r) = cur {
404
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
405
            cur = op.parents.first().copied();
406
            chain.push(op);
407
        }
408
        chain.reverse();
409
        let mut new_parent: Option<ObjectRef> = None;
410
        for old in chain {
411
            let mut view = View::default();
412
            for (name, heads) in &old.view.bookmarks {
413
                view.bookmarks.insert(
414
                    name.clone(),
415
                    self.store.put_state(&StateObject::new(heads.clone()))?,
416
                );
417
            }
418
            view.workspaces = old.view.workspaces.clone();
419
            let op = Op {
420
                parents: new_parent.into_iter().collect(),
421
                hlc: old.hlc,
422
                command: old.command,
423
                view,
424
            };
425
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
426
        }
427
        write_atomic(
428
            &self.oxy.join("ops").join("head"),
429
            new_parent.unwrap().to_hex().as_bytes(),
430
        )?;
431
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
432
        Ok(())
433
    }
434
435
    /// Pack automatically once many loose objects have accumulated.
436
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
437
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
438
            self.store.pack_loose()?;
439
            self.store.merge_packs()?;
440
        }
441
        Ok(())
442
    }
443
444
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
445
    pub fn id(&self) -> Result<[u8; 16]> {
446
        if self.is_unbound() {
447
            return Ok([0; 16]);
448
        }
449
        let path = self.oxy.join("id");
450
        match fs::read_to_string(&path) {
451
            Ok(h) => hex::decode(h.trim())
452
                .ok()
453
                .and_then(|v| v.try_into().ok())
454
                .ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
455
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
456
                let mut id = [0u8; 16];
457
                rand::rngs::OsRng.fill_bytes(&mut id);
458
                write_atomic(&path, hex::encode(id).as_bytes())?;
459
                Ok(id)
460
            }
461
            Err(e) => Err(e.into()),
462
        }
463
    }
464
465
    pub fn root(&self) -> &Path {
466
        &self.root
467
    }
468
    pub fn store(&self) -> &Store {
469
        &self.store
470
    }
471
    pub fn workspace(&self) -> WorkspaceId {
472
        self.workspace
473
    }
474
475
    /// Use a different user directory for keys and the user config file
476
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
477
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
478
        let dir = dir.into();
479
        self.keys_dir = dir.join("keys");
480
        self.user_config = dir.join("config.toml");
481
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
482
            self.config = c;
483
        }
484
        self.apply_workspace_bookmark();
485
        self
486
    }
487
488
    /// The workspace's current bookmark (spec §10.1) overrides the
489
    /// configured default when `oxy bookmark switch` has recorded one.
490
    fn apply_workspace_bookmark(&mut self) {
491
        if let Ok(b) = fs::read_to_string(
492
            self.oxy
493
                .join("workspaces")
494
                .join(self.workspace.to_hex())
495
                .join("bookmark"),
496
        ) {
497
            let b = b.trim();
498
            if !b.is_empty() {
499
                self.config.bookmark = b.to_string();
500
            }
501
        }
502
    }
503
504
    pub fn user_config_path(&self) -> &Path {
505
        &self.user_config
506
    }
507
508
    /// Set a key in the user file and refresh the effective configuration.
509
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
510
        Config::set_user(&self.user_config, key, value)?;
511
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
512
        Ok(())
513
    }
514
515
    pub fn save_config(&self) -> Result<()> {
516
        self.config.save(&self.oxy.join("config"))
517
    }
518
519
    fn author(&self) -> KeyId {
520
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
521
    }
522
}
523
524
impl Repo {
525
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
526
        let mut c = Change {
527
            change_id: ChangeId::random(),
528
            deps,
529
            author: self.author(),
530
            hlc: Hlc::now(),
531
            message: message.into(),
532
            tree_ops: vec![],
533
            edits: vec![],
534
            kind: ChangeKind::WorkingCopy,
535
        };
536
        c.normalize();
537
        c
538
    }
539
540
    // ------------------------------------------------------------ operation log
541
542
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
543
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
544
        let r = ObjectRef::from_hex(hex.trim())
545
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
546
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
547
        Ok((r, op))
548
    }
549
550
    pub fn view(&self) -> Result<View> {
551
        Ok(self.head_op()?.1.view)
552
    }
553
554
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
555
        let op = Op {
556
            parents: parents.to_vec(),
557
            hlc: Hlc::now(),
558
            command: command.into(),
559
            view,
560
        };
561
        let r = self.store.put(ObjectType::Op, &op.encode())?;
562
        // The head is the commit point: everything it names must be on disk first.
563
        self.store.flush()?;
564
        // Compare and swap under a short lock (spec §12.1): when another
565
        // process recorded an operation since this one read the head, the
566
        // two are merged instead of one overwriting the other.
567
        let _lock = self.lock_ops()?;
568
        let current = match parents.first() {
569
            // The first operation (init): there is no head yet.
570
            None => None,
571
            Some(_) => Some(self.head_ref()?),
572
        };
573
        let Some(current) = current.filter(|c| Some(c) != parents.first()) else {
574
            write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?;
575
            return Ok(r);
576
        };
577
        let base = match parents.first() {
578
            Some(p) => Op::decode(&self.store.get_typed(p, ObjectType::Op)?)?.view,
579
            None => View::default(),
580
        };
581
        let theirs = Op::decode(&self.store.get_typed(&current, ObjectType::Op)?)?.view;
582
        let merged = Op {
583
            parents: vec![current, r],
584
            hlc: Hlc::now(),
585
            command: format!("{command} (merged with a concurrent operation)"),
586
            view: self.merge_views(&base, &op.view, &theirs)?,
587
        };
588
        let m = self.store.put(ObjectType::Op, &merged.encode())?;
589
        self.store.flush()?;
590
        write_atomic(&self.oxy.join("ops").join("head"), m.to_hex().as_bytes())?;
591
        Ok(m)
592
    }
593
594
    /// The operation head's lock, held only while the head pointer moves.
595
    fn lock_ops(&self) -> Result<FileLock> {
596
        fs::create_dir_all(self.oxy.join("ops"))?;
597
        FileLock::acquire(
598
            self.oxy.join("ops").join("lock"),
599
            "another oxy process holds the operation log",
600
        )
601
    }
602
603
    fn head_ref(&self) -> Result<ObjectRef> {
604
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
605
        ObjectRef::from_hex(hex.trim())
606
            .ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))
607
    }
608
609
    /// Three-way merge of two views that both started from `base` (spec
610
    /// §12.1). A reference only one side changed takes that side's value.
611
    /// When both changed it differently: a bookmark keeps both sides'
612
    /// heads (it may then have several), a change beats a deletion, and
613
    /// otherwise this process's value wins for workspaces, remote
614
    /// references and the policy, the first value for a tag (tags never
615
    /// move).
616
    fn merge_views(&self, base: &View, ours: &View, theirs: &View) -> Result<View> {
617
        fn pick<K: Ord + Clone, V: Clone + PartialEq>(
618
            b: &BTreeMap<K, V>,
619
            o: &BTreeMap<K, V>,
620
            t: &BTreeMap<K, V>,
621
            mut both: impl FnMut(&V, &V) -> Result<V>,
622
        ) -> Result<BTreeMap<K, V>> {
623
            let keys: BTreeSet<&K> = b.keys().chain(o.keys()).chain(t.keys()).collect();
624
            let mut out = BTreeMap::new();
625
            for k in keys {
626
                let (bv, ov, tv) = (b.get(k), o.get(k), t.get(k));
627
                let v = if ov == tv || tv == bv {
628
                    ov.cloned()
629
                } else if ov == bv {
630
                    tv.cloned()
631
                } else {
632
                    match (ov, tv) {
633
                        (Some(x), Some(y)) => Some(both(x, y)?),
634
                        (Some(x), None) | (None, Some(x)) => Some(x.clone()),
635
                        (None, None) => None,
636
                    }
637
                };
638
                if let Some(v) = v {
639
                    out.insert(k.clone(), v);
640
                }
641
            }
642
            Ok(out)
643
        }
644
        let bookmarks = pick(
645
            &base.bookmarks,
646
            &ours.bookmarks,
647
            &theirs.bookmarks,
648
            |x, y| {
649
                let mut heads = self.store.get_state(x)?.heads;
650
                heads.extend(self.store.get_state(y)?.heads);
651
                let heads = self.load_state(&heads)?.maximal(&heads);
652
                Ok(self.store.put_state(&StateObject::new(heads))?)
653
            },
654
        )?;
655
        let workspaces = pick(
656
            &base.workspaces,
657
            &ours.workspaces,
658
            &theirs.workspaces,
659
            |x, _| Ok(*x),
660
        )?;
661
        let tags = pick(&base.tags, &ours.tags, &theirs.tags, |_, y| Ok(*y))?;
662
        let empty = BTreeMap::new();
663
        let names: BTreeSet<&String> = base
664
            .remotes
665
            .keys()
666
            .chain(ours.remotes.keys())
667
            .chain(theirs.remotes.keys())
668
            .collect();
669
        let mut remotes = BTreeMap::new();
670
        for n in names {
671
            let m = pick(
672
                base.remotes.get(n).unwrap_or(&empty),
673
                ours.remotes.get(n).unwrap_or(&empty),
674
                theirs.remotes.get(n).unwrap_or(&empty),
675
                |x, _| Ok(*x),
676
            )?;
677
            if !m.is_empty() {
678
                remotes.insert(n.clone(), m);
679
            }
680
        }
681
        let policy = if ours.policy == theirs.policy || theirs.policy == base.policy {
682
            ours.policy
683
        } else if ours.policy == base.policy {
684
            theirs.policy
685
        } else {
686
            ours.policy.or(theirs.policy)
687
        };
688
        self.store.flush()?;
689
        Ok(View {
690
            bookmarks,
691
            workspaces,
692
            remotes,
693
            policy,
694
            tags,
695
        })
696
    }
697
698
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
699
        let mut out = Vec::new();
700
        let (mut r, mut op) = self.head_op()?;
701
        loop {
702
            let next = op.parents.first().copied();
703
            out.push((r, op));
704
            match next {
705
                Some(p) => {
706
                    r = p;
707
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
708
                }
709
                None => break,
710
            }
711
        }
712
        Ok(out)
713
    }
714
715
    /// Undo the last user command (spec §12.1). Operations that only recorded
716
    /// a working-copy snapshot are skipped, since the files are still on disk
717
    /// and the next snapshot recreates them.
718
    pub fn undo(&self) -> Result<Op> {
719
        let (read_head, mut op) = self.head_op()?;
720
        while op.is_snapshot() {
721
            let Some(parent) = op.parents.first() else {
722
                break;
723
            };
724
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
725
        }
726
        let Some(parent) = op.parents.first() else {
727
            return fail("nothing to undo");
728
        };
729
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
730
        let _lock = self.lock_ops()?;
731
        if self.head_ref()? != read_head {
732
            return fail("another oxy command ran while undoing; run undo again");
733
        }
734
        write_atomic(
735
            &self.oxy.join("ops").join("head"),
736
            parent.to_hex().as_bytes(),
737
        )?;
738
        self.drop_manifest();
739
        Ok(parent_op)
740
    }
741
742
    /// The last operation that was not a snapshot.
743
    pub fn last_command(&self) -> Result<Op> {
744
        let (_, mut op) = self.head_op()?;
745
        while op.is_snapshot() {
746
            let Some(parent) = op.parents.first() else {
747
                break;
748
            };
749
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
750
        }
751
        Ok(op)
752
    }
753
754
    // ------------------------------------------------------------ states
755
756
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
757
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
758
        if let Some(st) = self.load_state_checkpointed(heads)? {
759
            return Ok(st);
760
        }
761
        self.load_state_full(heads)
762
    }
763
764
    /// Load the dependency closure of `heads` change by change.
765
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
766
        let mut state = State::new();
767
        let mut stack: Vec<ChangeHash> = heads.to_vec();
768
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
769
        while let Some(h) = stack.pop() {
770
            if !seen.insert(h) {
771
                continue;
772
            }
773
            let c = self.store.get_change(&h)?;
774
            stack.extend(c.deps.iter().copied());
775
            state.add_unchecked(c);
776
        }
777
        state.validate()?;
778
        Ok(state)
779
    }
780
781
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
782
        if self.bare {
783
            return fail("this is a bare repository: it has no working copy");
784
        }
785
        let view = self.view()?;
786
        let h = *view
787
            .workspaces
788
            .get(&self.workspace)
789
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
790
        Ok((h, self.store.get_change(&h)?))
791
    }
792
793
    /// Heads of a bookmark's state (spec §10.1).
794
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
795
        match view.bookmarks.get(bookmark) {
796
            Some(st) => Ok(self.store.get_state(st)?.heads),
797
            None => Ok(vec![]),
798
        }
799
    }
800
801
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
802
        self.heads_of(&self.view()?, &self.config.bookmark)
803
    }
804
805
    // ------------------------------------------------------------ blobs
806
807
    fn blob_for(content: &[u8]) -> Blob {
808
        Blob {
809
            length: content.len() as u64,
810
            chunks: crate::chunk::chunks(content)
811
                .into_iter()
812
                .map(|c| hash_object(ObjectType::Chunk, c))
813
                .collect(),
814
        }
815
    }
816
817
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
818
        Self::blob_for(content).hash()
819
    }
820
821
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
822
        for c in crate::chunk::chunks(content) {
823
            self.store.put_chunk(c)?;
824
        }
825
        Ok(self
826
            .store
827
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
828
    }
829
830
    /// Read a blob's content, fetching it from the remote that withheld it
831
    /// when it is lazily absent (spec §13.5).
832
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
833
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
834
            self.fetch_lazy_blob(r)?;
835
        }
836
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
837
        let mut out = Vec::with_capacity(blob.length as usize);
838
        for c in &blob.chunks {
839
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
840
        }
841
        Ok(out)
842
    }
843
844
    // ------------------------------------------------------------ working copy
845
846
    /// Attributes from the `.oxyattributes` files in the working directory.
847
    pub fn disk_attributes(&self) -> crate::attributes::Attributes {
848
        let mut files: Vec<(String, Vec<u8>)> = Vec::new();
849
        if let Ok(b) = fs::read(self.root.join(".oxyattributes")) {
850
            files.push((".oxyattributes".into(), b));
851
        }
852
        let mut wb = ignore::WalkBuilder::new(&self.root);
853
        wb.hidden(false)
854
            .git_ignore(false)
855
            .git_global(false)
856
            .git_exclude(false)
857
            .require_git(false)
858
            .follow_links(false)
859
            .add_custom_ignore_filename(".oxyignore");
860
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
861
        for entry in wb.build().flatten() {
862
            if entry.file_name() == ".oxyattributes"
863
                && entry.path() != self.root.join(".oxyattributes")
864
            {
865
                if let Ok(b) = fs::read(entry.path()) {
866
                    let rel: String = entry
867
                        .path()
868
                        .strip_prefix(&self.root)
869
                        .unwrap()
870
                        .components()
871
                        .map(|c| c.as_os_str().to_string_lossy().to_string())
872
                        .collect::<Vec<_>>()
873
                        .join("/");
874
                    files.push((rel, b));
875
                }
876
            }
877
        }
878
        crate::attributes::Attributes::from_files(
879
            files.iter().map(|(p, c)| (p.as_str(), c.as_slice())),
880
        )
881
    }
882
883
    /// Attributes from a materialized state's `.oxyattributes` files.
884
    pub fn state_attributes(snapshot: &Snapshot) -> crate::attributes::Attributes {
885
        crate::attributes::Attributes::from_files(snapshot.files.iter().filter_map(|(p, f)| {
886
            match &f.content {
887
                FileContent::Text { bytes, .. }
888
                    if p == ".oxyattributes" || p.ends_with("/.oxyattributes") =>
889
                {
890
                    Some((p.as_str(), bytes.as_slice()))
891
                }
892
                _ => None,
893
            }
894
        }))
895
    }
896
897
    /// Store a blob, raw when the path is `nocompress`.
898
    pub fn store_blob_for(&self, content: &[u8], nocompress: bool) -> Result<ObjectRef> {
899
        if !nocompress {
900
            return self.store_blob(content);
901
        }
902
        for c in crate::chunk::chunks(content) {
903
            self.store.put_chunk_nocompress(c)?;
904
        }
905
        Ok(self
906
            .store
907
            .put(ObjectType::Blob, &Self::blob_for(content).encode())?)
908
    }
909
910
    fn locks_dir(&self) -> PathBuf {
911
        self.oxy.join("locks")
912
    }
913
914
    /// Whether `path` is locked locally for editing (spec §18, advisory).
915
    pub fn is_locked(&self, path: &str) -> bool {
916
        self.locks_dir().join(path.replace('/', "%2F")).exists()
917
    }
918
919
    /// Take the advisory local lock on a `lockable` file and make it writable.
920
    pub fn lock_path(&self, path: &str) -> Result<()> {
921
        let attrs = self.disk_attributes();
922
        if !attrs.lookup(path).lockable {
923
            return fail(format!("{path} is not marked lockable in .oxyattributes"));
924
        }
925
        fs::create_dir_all(self.locks_dir())?;
926
        write_atomic(
927
            &self.locks_dir().join(path.replace('/', "%2F")),
928
            std::process::id().to_string().as_bytes(),
929
        )?;
930
        set_readonly(&self.root.join(path), false)?;
931
        Ok(())
932
    }
933
934
    /// Release the local lock and make the file read-only again.
935
    pub fn unlock_path(&self, path: &str) -> Result<()> {
936
        let _ = fs::remove_file(self.locks_dir().join(path.replace('/', "%2F")));
937
        if self.root.join(path).exists() {
938
            set_readonly(&self.root.join(path), true)?;
939
        }
940
        Ok(())
941
    }
942
943
    /// Whether a repository path is inside the sparse filter (spec §17).
944
    pub fn in_scope(&self, path: &str) -> bool {
945
        self.config.sparse_paths.is_empty()
946
            || self
947
                .config
948
                .sparse_paths
949
                .iter()
950
                .any(|p| path == p || path.starts_with(&format!("{p}/")))
951
    }
952
953
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
954
        self.walk_working_copy_with(None, &BTreeMap::new())
955
    }
956
957
    /// A walker over the working copy that never enters a nested repository
958
    /// (a directory below the root holding `.oxy` or `.git`); the directories
959
    /// it skipped are collected into `nested`.
960
    pub(crate) fn walker(
961
        &self,
962
        nested: &std::sync::Arc<std::sync::Mutex<Vec<PathBuf>>>,
963
    ) -> ignore::WalkBuilder {
964
        let mut wb = ignore::WalkBuilder::new(&self.root);
965
        wb.hidden(false)
966
            .git_ignore(false)
967
            .git_global(false)
968
            .git_exclude(false)
969
            .require_git(false)
970
            .follow_links(false)
971
            .add_custom_ignore_filename(".oxyignore");
972
        let nested = nested.clone();
973
        wb.filter_entry(move |e| {
974
            if e.file_name() == OXY_DIR {
975
                return false;
976
            }
977
            if e.depth() > 0
978
                && e.file_type().is_some_and(|t| t.is_dir())
979
                && (e.path().join(OXY_DIR).exists() || e.path().join(".git").exists())
980
            {
981
                nested.lock().unwrap().push(e.path().to_path_buf());
982
                return false;
983
            }
984
            true
985
        });
986
        wb
987
    }
988
989
    /// Walk the working copy; with a manifest, a file whose size and mtime
990
    /// match it is not read: an opaque file yields its known blob, a text
991
    /// file is read but keeps its known hash. Files modified within two
992
    /// seconds of the manifest are never trusted (a racy stat).
993
    ///
994
    /// `.oxyignore` applies to untracked paths only: every path in `tracked`
995
    /// (the base state's files) that exists on disk is included even when
996
    /// an ignore rule matches it, as in Git.
997
    fn walk_working_copy_with(
998
        &self,
999
        cache: Option<&prompt::Manifest>,
1000
        tracked: &BTreeMap<String, (NodeKind, Option<ObjectRef>)>,
1001
    ) -> Result<BTreeMap<String, FsEntry>> {
1002
        let nested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1003
        let wb = self.walker(&nested);
1004
        let mut out = BTreeMap::new();
1005
        for entry in wb.build() {
1006
            let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?;
1007
            let path = entry.path();
1008
            if path == self.root {
1009
                continue;
1010
            }
1011
            let rel = path.strip_prefix(&self.root).unwrap();
1012
            let rel: String = rel
1013
                .components()
1014
                .map(|c| c.as_os_str().to_string_lossy().to_string())
1015
                .collect::<Vec<_>>()
1016
                .join("/");
1017
            let Some(ft) = entry.file_type() else {
1018
                continue;
1019
            };
1020
            if ft.is_dir() || !self.in_scope(&rel) {
1021
                continue;
1022
            }
1023
            if ft.is_symlink() {
1024
                let target = fs::read_link(path)?;
1025
                out.insert(
1026
                    rel,
1027
                    FsEntry::new(
1028
                        NodeKind::Symlink,
1029
                        false,
1030
                        target.to_string_lossy().as_bytes().to_vec(),
1031
                    ),
1032
                );
1033
            } else if ft.is_file() {
1034
                let meta = entry
1035
                    .metadata()
1036
                    .map_err(|e| RepoError::Msg(e.to_string()))?;
1037
                let e = self.file_entry(&rel, path, &meta, cache)?;
1038
                out.insert(rel, e);
1039
            }
1040
        }
1041
        // Nested repositories (spec §7.8): registered in `.oxymodules` or
1042
        // already tracked as subrepo nodes, they contribute their pin;
1043
        // unregistered ones are left alone.
1044
        let modules = self.modules_on_disk();
1045
        let removed = self.removed_subrepos();
1046
        for rel in &removed {
1047
            if tracked.get(rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo) {
1048
                self.clear_removed_subrepo(rel);
1049
            }
1050
        }
1051
        let nested_dirs = std::mem::take(&mut *nested.lock().unwrap());
1052
        for dir in nested_dirs {
1053
            let rel = self.rel_path(&dir);
1054
            if !self.in_scope(&rel) || removed.contains(&rel) {
1055
                continue;
1056
            }
1057
            let registered = modules.entries.get(&rel);
1058
            if registered.is_none() && tracked.get(&rel).map(|(k, _)| *k) != Some(NodeKind::Subrepo)
1059
            {
1060
                continue;
1061
            }
1062
            let pin = subrepos::read_pin(&dir, registered.and_then(|m| m.bookmark.as_deref()))?;
1063
            out.insert(rel, FsEntry::new(NodeKind::Subrepo, false, pin.encode()));
1064
        }
1065
        // Tracked paths the ignore rules hid.
1066
        for (rel, (kind, blob)) in tracked {
1067
            if out.contains_key(rel) || !self.in_scope(rel) {
1068
                continue;
1069
            }
1070
            let path = self.root.join(rel);
1071
            if *kind == NodeKind::Subrepo {
1072
                if removed.contains(rel) {
1073
                    continue;
1074
                }
1075
                let present =
1076
                    path.is_dir() && (path.join(OXY_DIR).exists() || path.join(".git").exists());
1077
                if present {
1078
                    let pin = subrepos::read_pin(
1079
                        &path,
1080
                        modules.entries.get(rel).and_then(|m| m.bookmark.as_deref()),
1081
                    )?;
1082
                    out.insert(
1083
                        rel.clone(),
1084
                        FsEntry::new(NodeKind::Subrepo, false, pin.encode()),
1085
                    );
1086
                } else if let Some(b) = blob {
1087
                    // Not cloned (or emptied): the pin stays as recorded, as a
1088
                    // Git gitlink does when its directory is absent.
1089
                    out.insert(
1090
                        rel.clone(),
1091
                        FsEntry {
1092
                            kind: NodeKind::Subrepo,
1093
                            exec: false,
1094
                            content: vec![],
1095
                            blob: Some(*b),
1096
                            content_hash: None,
1097
                        },
1098
                    );
1099
                }
1100
                continue;
1101
            }
1102
            let Ok(meta) = fs::symlink_metadata(&path) else {
1103
                continue;
1104
            };
1105
            let ft = meta.file_type();
1106
            if ft.is_symlink() {
1107
                let target = fs::read_link(&path)?;
1108
                out.insert(
1109
                    rel.clone(),
1110
                    FsEntry::new(
1111
                        NodeKind::Symlink,
1112
                        false,
1113
                        target.to_string_lossy().as_bytes().to_vec(),
1114
                    ),
1115
                );
1116
            } else if ft.is_file() {
1117
                let e = self.file_entry(rel, &path, &meta, cache)?;
1118
                out.insert(rel.clone(), e);
1119
            }
1120
        }
1121
        Ok(out)
1122
    }
1123
1124
    /// The entry for one regular file, read or served from the stat cache.
1125
    fn file_entry(
1126
        &self,
1127
        rel: &str,
1128
        path: &Path,
1129
        meta: &fs::Metadata,
1130
        cache: Option<&prompt::Manifest>,
1131
    ) -> Result<FsEntry> {
1132
        let exec = is_executable(meta);
1133
        let cached = cache.and_then(|m| {
1134
            let e = m.entries.get(rel)?;
1135
            let mtime_ns = prompt::mtime_ns(meta);
1136
            let racy = mtime_ns + 2_000_000_000 >= m.written_ns;
1137
            (e.size == meta.len() && e.mtime_ns == mtime_ns && !racy).then_some(e)
1138
        });
1139
        Ok(match cached {
1140
            Some(e) if e.blob.is_some_and(|b| self.store.has(&b)) => FsEntry {
1141
                kind: NodeKind::File,
1142
                exec,
1143
                content: vec![],
1144
                blob: e.blob,
1145
                content_hash: Some(e.hash.clone()),
1146
            },
1147
            Some(e) => FsEntry {
1148
                kind: NodeKind::File,
1149
                exec,
1150
                content: fs::read(path)?,
1151
                blob: None,
1152
                content_hash: Some(e.hash.clone()),
1153
            },
1154
            None => FsEntry::new(NodeKind::File, exec, fs::read(path)?),
1155
        })
1156
    }
1157
1158
    /// The non-directory paths of a snapshot with their kinds, for the
1159
    /// walker's `tracked` set.
1160
    pub(crate) fn tracked_kinds(
1161
        snapshot: &Snapshot,
1162
    ) -> BTreeMap<String, (NodeKind, Option<ObjectRef>)> {
1163
        snapshot
1164
            .files
1165
            .iter()
1166
            .filter(|(_, f)| f.kind != NodeKind::Dir)
1167
            .map(|(p, f)| {
1168
                let blob = match &f.content {
1169
                    FileContent::Opaque { blobs } => blobs.first().copied(),
1170
                    _ => None,
1171
                };
1172
                (p.clone(), (f.kind, blob))
1173
            })
1174
            .collect()
1175
    }
1176
1177
    /// A path under the root as a `/`-separated relative string.
1178
    pub(crate) fn rel_path(&self, path: &Path) -> String {
1179
        path.strip_prefix(&self.root)
1180
            .unwrap_or(path)
1181
            .components()
1182
            .map(|c| c.as_os_str().to_string_lossy().to_string())
1183
            .collect::<Vec<_>>()
1184
            .join("/")
1185
    }
1186
}
1187
1188
impl Repo {
1189
    /// Changes reachable from the bookmark and the working copy, newest first.
1190
    pub fn log(&self) -> Result<Vec<LogEntry>> {
1191
        let heads = self.bookmark_heads()?;
1192
        if self.bare {
1193
            return self.log_state(&heads);
1194
        }
1195
        let (wc_hash, _) = self.working_copy()?;
1196
        let mut all = heads.clone();
1197
        all.push(wc_hash);
1198
        let state = self.load_state(&all)?;
1199
        let head_set: BTreeSet<ChangeHash> = heads.into_iter().collect();
1200
        let mut entries: Vec<LogEntry> = Vec::new();
1201
        for (h, meta) in state.changes() {
1202
            entries.push(LogEntry {
1203
                hash: *h,
1204
                change: meta.clone(),
1205
                is_working_copy: *h == wc_hash,
1206
                is_head: head_set.contains(h),
1207
            });
1208
        }
1209
        entries.sort_by(|a, b| {
1210
            b.is_working_copy
1211
                .cmp(&a.is_working_copy)
1212
                .then(b.change.hlc.cmp(&a.change.hlc))
1213
                .then(b.hash.cmp(&a.hash))
1214
        });
1215
        Ok(entries)
1216
    }
1217
1218
    /// A window of `log_state`: entries `offset..offset+limit` and the total
1219
    /// count, for paginated views.
1220
    pub fn log_window(
1221
        &self,
1222
        heads: &[ChangeHash],
1223
        offset: usize,
1224
        limit: usize,
1225
    ) -> Result<(Vec<LogEntry>, usize)> {
1226
        let all = self.log_state(heads)?;
1227
        let total = all.len();
1228
        Ok((all.into_iter().skip(offset).take(limit).collect(), total))
1229
    }
1230
1231
    /// The log of the state with these heads, newest first, with no working
1232
    /// copy involved (for hosted repositories and any explicit state).
1233
    pub fn log_state(&self, heads: &[ChangeHash]) -> Result<Vec<LogEntry>> {
1234
        let state = self.load_state(heads)?;
1235
        let head_set: BTreeSet<ChangeHash> = state.heads().into_iter().collect();
1236
        let mut entries: Vec<LogEntry> = state
1237
            .changes()
1238
            .map(|(h, meta)| LogEntry {
1239
                hash: *h,
1240
                change: meta.clone(),
1241
                is_working_copy: false,
1242
                is_head: head_set.contains(h),
1243
            })
1244
            .collect();
1245
        entries.sort_by(|a, b| b.change.hlc.cmp(&a.change.hlc).then(b.hash.cmp(&a.hash)));
1246
        Ok(entries)
1247
    }
1248
1249
    /// Resolve a spec to a set of heads: a tag name, the current bookmark's
1250
    /// name, or a single change (`resolve_change`).
1251
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
1252
        let view = self.view()?;
1253
        if let Some(st) = view.bookmarks.get(spec) {
1254
            return Ok(self.store.get_state(st)?.heads);
1255
        }
1256
        if let Some(heads) = self.tag_heads(spec)? {
1257
            return Ok(heads);
1258
        }
1259
        Ok(vec![self.resolve_change(spec)?])
1260
    }
1261
1262
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working copy), or bookmark.
1263
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
1264
        if spec == "@" {
1265
            return Ok(self.working_copy()?.0);
1266
        }
1267
        if let Some(st) = self.view()?.bookmarks.get(spec) {
1268
            let heads = self.store.get_state(st)?.heads;
1269
            return match heads.len() {
1270
                1 => Ok(heads[0]),
1271
                n => fail(format!("bookmark {spec} has {n} heads; name a change, or use it where a state is expected")),
1272
            };
1273
        }
1274
        if spec.is_empty() || spec == "#" {
1275
            return fail("empty change specifier");
1276
        }
1277
        let entries = self.log()?;
1278
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
1279
            entries
1280
                .iter()
1281
                .filter(|e| e.hash.starts_with_hex(hp))
1282
                .collect()
1283
        } else {
1284
            entries
1285
                .iter()
1286
                .filter(|e| e.change.change_id.starts_with_hex(spec))
1287
                .collect()
1288
        };
1289
        match matches.len() {
1290
            1 => Ok(matches[0].hash),
1291
            0 => fail(format!("no change matches {spec:?}")),
1292
            _ => {
1293
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
1294
                if ids.len() == 1 {
1295
                    fail(format!(
1296
                        "change {spec} is divergent: {} variants",
1297
                        matches.len()
1298
                    ))
1299
                } else {
1300
                    fail(format!("{spec:?} is ambiguous"))
1301
                }
1302
            }
1303
        }
1304
    }
1305
1306
    /// Human-readable description of what a change does, with line content.
1307
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
1308
        let change = self.store.get_change(hash)?;
1309
        let base = self.load_state(&change.deps)?;
1310
        let base_snapshot = base.materialize();
1311
        Ok(render_change(&change, &base, &base_snapshot))
1312
    }
1313
}
1314
1315
fn remove_any(path: &Path) -> std::io::Result<()> {
1316
    let m = fs::symlink_metadata(path)?;
1317
    if m.is_dir() {
1318
        fs::remove_dir_all(path)
1319
    } else {
1320
        fs::remove_file(path)
1321
    }
1322
}
1323
1324
fn set_readonly(path: &Path, readonly: bool) -> std::io::Result<()> {
1325
    let mut perms = fs::metadata(path)?.permissions();
1326
    perms.set_readonly(readonly);
1327
    fs::set_permissions(path, perms)
1328
}
1329
1330
#[cfg(unix)]
1331
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
1332
    use std::os::unix::fs::PermissionsExt;
1333
    let mut perms = fs::metadata(path)?.permissions();
1334
    let mode = perms.mode();
1335
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
1336
    if want != mode {
1337
        perms.set_mode(want);
1338
        fs::set_permissions(path, perms)?;
1339
    }
1340
    Ok(())
1341
}
1342
#[cfg(not(unix))]
1343
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
1344
    Ok(())
1345
}
1346
1347
#[cfg(unix)]
1348
fn is_executable(m: &fs::Metadata) -> bool {
1349
    use std::os::unix::fs::PermissionsExt;
1350
    m.permissions().mode() & 0o111 != 0
1351
}
1352
#[cfg(not(unix))]
1353
fn is_executable(_m: &fs::Metadata) -> bool {
1354
    false
1355
}
1356
1357
fn op_ref(k: OpKey) -> OpRef {
1358
    OpRef {
1359
        change: k.0,
1360
        index: k.1,
1361
    }
1362
}
1363
1364
fn split_path(path: &str) -> (&str, &str) {
1365
    match path.rfind('/') {
1366
        Some(i) => (&path[..i], &path[i + 1..]),
1367
        None => ("", path),
1368
    }
1369
}