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