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