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