OXYGENHUB
# b2ef93bb2366 oxygen / crates / oxy-core / src / repo / mod.rs
22.6 KiB · Rust · last changed Lazy blobs: clone --max-blob / filter.max-blob, absent-blob registry fetched on first read, objects endpoint (spec 0.6e) 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::protocol::{open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef, SignedAttest, SignedPolicy};
13
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
14
use crate::identity::{verify as verify_signature, Domain, Identity, SecretKey, Signature};
15
use crate::ids::{ChangeId, NodeId, WorkspaceId};
16
use crate::objects::{Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp};
17
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX};
18
use crate::state::{FileContent, Snapshot, State};
19
use crate::store::{Store, StoreError};
20
use crate::tree::OpKey;
21
use rand::RngCore;
22
use std::collections::{BTreeMap, BTreeSet, HashMap};
23
use std::fs;
24
use std::io::Write;
25
use std::path::{Path, PathBuf};
26
27
pub const OXY_DIR: &str = ".oxy";
28
pub const FORMAT_LINE: &str = "oxy repository format 2\n";
29
const FORMAT1_LINE: &str = "oxy repository format 1\n";
30
const BINARY_SNIFF: usize = 8 * 1024;
31
/// Loose objects tolerated before a commit packs them (spec §13.4).
32
pub const AUTOPACK_THRESHOLD: usize = 4096;
33
34
#[derive(Debug, thiserror::Error)]
35
pub enum RepoError {
36
    #[error("io: {0}")]
37
    Io(#[from] std::io::Error),
38
    #[error(transparent)]
39
    Store(#[from] StoreError),
40
    #[error(transparent)]
41
    Object(#[from] crate::objects::ObjectError),
42
    #[error(transparent)]
43
    State(#[from] crate::state::StateError),
44
    #[error("{0}")]
45
    Msg(String),
46
}
47
48
pub type Result<T> = std::result::Result<T, RepoError>;
49
50
fn fail<T>(s: impl Into<String>) -> Result<T> {
51
    Err(RepoError::Msg(s.into()))
52
}
53
54
mod checkout;
55
mod checkpoint;
56
mod config;
57
mod gc;
58
mod git;
59
mod history;
60
mod identity;
61
mod policy;
62
mod prompt;
63
mod snapshot;
64
mod sync;
65
mod tags;
66
#[cfg(test)]
67
mod tests;
68
69
pub use checkout::CheckoutReport;
70
pub use config::{parse_size, read_config_file, Config};
71
pub use gc::GcReport;
72
pub use prompt::{PromptInfo, DEFAULT_PROMPT_FORMAT};
73
pub use git::{GitExportReport, GitImportReport};
74
pub use identity::SignatureStatus;
75
pub use snapshot::{added_node_paths, has_conflict_markers, is_binary, referenced_changes, render_change, ChangeStatus, PathStatus, SnapshotResult};
76
pub use sync::{FetchReport, PullReport};
77
pub use tags::TagInfo;
78
79
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
80
    let tmp = path.with_extension("tmp");
81
    {
82
        let mut f = fs::File::create(&tmp)?;
83
        f.write_all(data)?;
84
        f.sync_all()?;
85
    }
86
    fs::rename(&tmp, path)?;
87
    Ok(())
88
}
89
90
pub struct LogEntry {
91
    pub hash: ChangeHash,
92
    /// Metadata from the state; the full change may be absent in a shallow repository.
93
    pub change: crate::state::ChangeMeta,
94
    pub is_working_copy: bool,
95
    pub is_head: bool,
96
}
97
98
/// A file as found on disk or in an imported tree.
99
pub(crate) struct FsEntry {
100
    pub kind: NodeKind,
101
    pub exec: bool,
102
    /// File content, or a symlink's target.
103
    pub content: Vec<u8>,
104
}
105
106
pub struct Repo {
107
    root: PathBuf,
108
    oxy: PathBuf,
109
    store: Store,
110
    workspace: WorkspaceId,
111
    keys_dir: PathBuf,
112
    user_config: PathBuf,
113
    pub config: Config,
114
}
115
116
/// The user's oxy directory: `$OXY_HOME`, else `$XDG_CONFIG_HOME/oxy`, else
117
/// `~/.config/oxy`. It holds `config.toml` (spec §19) and `keys/`.
118
pub fn default_home() -> PathBuf {
119
    if let Ok(h) = std::env::var("OXY_HOME") {
120
        return PathBuf::from(h);
121
    }
122
    if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
123
        return PathBuf::from(x).join("oxy");
124
    }
125
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
126
    PathBuf::from(home).join(".config").join("oxy")
127
}
128
129
pub fn default_keys_dir() -> PathBuf {
130
    default_home().join("keys")
131
}
132
133
pub fn default_user_config() -> PathBuf {
134
    default_home().join("config.toml")
135
}
136
137
/// Where `create_identity` records the author.
138
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139
pub enum IdentityScope {
140
    /// The user file: every repository of this user signs with it.
141
    User,
142
    /// This repository only.
143
    Repo,
144
}
145
146
impl Repo {
147
    // ------------------------------------------------------------ lifecycle
148
149
    pub fn init(root: &Path) -> Result<Repo> {
150
        let mut id = [0u8; 16];
151
        rand::rngs::OsRng.fill_bytes(&mut id);
152
        Self::init_with_id(root, id)
153
    }
154
155
    /// Initialize a repository with a given repository ID (clones share the
156
    /// ID of their origin, spec §14.4).
157
    pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> {
158
        fs::create_dir_all(root)?;
159
        let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
160
        let oxy = root.join(OXY_DIR);
161
        if oxy.exists() {
162
            return fail(format!("{} is already an oxy repository", root.display()));
163
        }
164
        fs::create_dir_all(oxy.join("ops"))?;
165
        write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?;
166
        write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?;
167
        let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
168
        config.save(&oxy.join("config"))?;
169
        let workspace = WorkspaceId::random();
170
        write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?;
171
        let store = Store::open(oxy.join("objects"))?;
172
        let repo = Repo { root, oxy, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config };
173
174
        let wc = repo.new_working_copy(vec![], "");
175
        let wc_hash = repo.store.put_change(&wc)?;
176
        let mut view = View::default();
177
        view.bookmarks.insert(repo.config.bookmark.clone(), repo.store.put_state(&StateObject::new(vec![]))?);
178
        view.workspaces.insert(workspace, wc_hash);
179
        repo.record_op(&[], "oxy init", view)?;
180
        Ok(repo)
181
    }
182
183
    /// Open the repository containing `start` (searching upwards).
184
    pub fn open(start: &Path) -> Result<Repo> {
185
        let start = start.canonicalize()?;
186
        let mut dir: Option<&Path> = Some(&start);
187
        while let Some(d) = dir {
188
            let oxy = d.join(OXY_DIR);
189
            if oxy.is_dir() {
190
                let format = fs::read_to_string(oxy.join("format"))?;
191
                let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?;
192
                let workspace = WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim())
193
                    .ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?;
194
                let store = Store::open(oxy.join("objects"))?;
195
                let repo = Repo { root: d.to_path_buf(), oxy, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config };
196
                if format == FORMAT1_LINE {
197
                    repo.migrate_format1()?;
198
                } else if format != FORMAT_LINE {
199
                    return fail(format!("unsupported repository format: {}", format.trim()));
200
                }
201
                return Ok(repo);
202
            }
203
            dir = d.parent();
204
        }
205
        fail(format!("no oxy repository found at or above {}", start.display()))
206
    }
207
208
    /// Rewrite a format-1 operation log, whose bookmarks were head lists,
209
    /// into format 2, where each bookmark names a `state` object.
210
    fn migrate_format1(&self) -> Result<()> {
211
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
212
        let head = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
213
        // Collect the chain root-first.
214
        let mut chain: Vec<Format1Op> = Vec::new();
215
        let mut cur = Some(head);
216
        while let Some(r) = cur {
217
            let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?;
218
            cur = op.parents.first().copied();
219
            chain.push(op);
220
        }
221
        chain.reverse();
222
        let mut new_parent: Option<ObjectRef> = None;
223
        for old in chain {
224
            let mut view = View::default();
225
            for (name, heads) in &old.view.bookmarks {
226
                view.bookmarks.insert(name.clone(), self.store.put_state(&StateObject::new(heads.clone()))?);
227
            }
228
            view.workspaces = old.view.workspaces.clone();
229
            let op = Op { parents: new_parent.into_iter().collect(), hlc: old.hlc, command: old.command, view };
230
            new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?);
231
        }
232
        write_atomic(&self.oxy.join("ops").join("head"), new_parent.unwrap().to_hex().as_bytes())?;
233
        write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?;
234
        Ok(())
235
    }
236
237
    /// Pack automatically once many loose objects have accumulated.
238
    pub(crate) fn maybe_autopack(&self) -> Result<()> {
239
        if self.store.loose_count()? > AUTOPACK_THRESHOLD {
240
            self.store.pack_loose()?;
241
            self.store.merge_packs()?;
242
        }
243
        Ok(())
244
    }
245
246
    /// The repository ID (spec §14.4). Repositories made before IDs existed get one on first use.
247
    pub fn id(&self) -> Result<[u8; 16]> {
248
        let path = self.oxy.join("id");
249
        match fs::read_to_string(&path) {
250
            Ok(h) => hex::decode(h.trim()).ok().and_then(|v| v.try_into().ok()).ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())),
251
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
252
                let mut id = [0u8; 16];
253
                rand::rngs::OsRng.fill_bytes(&mut id);
254
                write_atomic(&path, hex::encode(id).as_bytes())?;
255
                Ok(id)
256
            }
257
            Err(e) => Err(e.into()),
258
        }
259
    }
260
261
    pub fn root(&self) -> &Path {
262
        &self.root
263
    }
264
    pub fn store(&self) -> &Store {
265
        &self.store
266
    }
267
    pub fn workspace(&self) -> WorkspaceId {
268
        self.workspace
269
    }
270
271
    /// Use a different user directory for keys and the user config file
272
    /// (tests, or `$OXY_HOME`). Reloads the effective configuration.
273
    pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo {
274
        let dir = dir.into();
275
        self.keys_dir = dir.join("keys");
276
        self.user_config = dir.join("config.toml");
277
        if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) {
278
            self.config = c;
279
        }
280
        self
281
    }
282
283
    pub fn user_config_path(&self) -> &Path {
284
        &self.user_config
285
    }
286
287
    /// Set a key in the user file and refresh the effective configuration.
288
    pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> {
289
        Config::set_user(&self.user_config, key, value)?;
290
        self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
291
        Ok(())
292
    }
293
294
    pub fn save_config(&self) -> Result<()> {
295
        self.config.save(&self.oxy.join("config"))
296
    }
297
298
    fn author(&self) -> KeyId {
299
        self.config.author_key.unwrap_or(ObjectRef::ZERO)
300
    }
301
}
302
303
impl Repo {
304
    fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change {
305
        let mut c = Change {
306
            change_id: ChangeId::random(),
307
            deps,
308
            author: self.author(),
309
            hlc: Hlc::now(),
310
            message: message.into(),
311
            tree_ops: vec![],
312
            edits: vec![],
313
            kind: ChangeKind::WorkingCopy,
314
        };
315
        c.normalize();
316
        c
317
    }
318
319
    // ------------------------------------------------------------ operation log
320
321
    pub fn head_op(&self) -> Result<(ObjectRef, Op)> {
322
        let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?;
323
        let r = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?;
324
        let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
325
        Ok((r, op))
326
    }
327
328
    pub fn view(&self) -> Result<View> {
329
        Ok(self.head_op()?.1.view)
330
    }
331
332
    fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> {
333
        let op = Op { parents: parents.to_vec(), hlc: Hlc::now(), command: command.into(), view };
334
        let r = self.store.put(ObjectType::Op, &op.encode())?;
335
        write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?;
336
        Ok(r)
337
    }
338
339
    pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> {
340
        let mut out = Vec::new();
341
        let (mut r, mut op) = self.head_op()?;
342
        loop {
343
            let next = op.parents.first().copied();
344
            out.push((r, op));
345
            match next {
346
                Some(p) => {
347
                    r = p;
348
                    op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?;
349
                }
350
                None => break,
351
            }
352
        }
353
        Ok(out)
354
    }
355
356
    /// Undo the last user command (spec §12.1). Operations that only recorded
357
    /// a working-copy snapshot are skipped, since the files are still on disk
358
    /// and the next snapshot recreates them.
359
    pub fn undo(&self) -> Result<Op> {
360
        let (_, mut op) = self.head_op()?;
361
        while op.is_snapshot() {
362
            let Some(parent) = op.parents.first() else { break };
363
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
364
        }
365
        let Some(parent) = op.parents.first() else {
366
            return fail("nothing to undo");
367
        };
368
        let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
369
        write_atomic(&self.oxy.join("ops").join("head"), parent.to_hex().as_bytes())?;
370
        self.drop_manifest();
371
        Ok(parent_op)
372
    }
373
374
    /// The last operation that was not a snapshot.
375
    pub fn last_command(&self) -> Result<Op> {
376
        let (_, mut op) = self.head_op()?;
377
        while op.is_snapshot() {
378
            let Some(parent) = op.parents.first() else { break };
379
            op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?;
380
        }
381
        Ok(op)
382
    }
383
384
    // ------------------------------------------------------------ states
385
386
    /// Load the dependency closure of `heads`, through a checkpoint when one applies.
387
    pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> {
388
        if let Some(st) = self.load_state_checkpointed(heads)? {
389
            return Ok(st);
390
        }
391
        self.load_state_full(heads)
392
    }
393
394
    /// Load the dependency closure of `heads` change by change.
395
    pub fn load_state_full(&self, heads: &[ChangeHash]) -> Result<State> {
396
        let mut state = State::new();
397
        let mut stack: Vec<ChangeHash> = heads.to_vec();
398
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
399
        while let Some(h) = stack.pop() {
400
            if !seen.insert(h) {
401
                continue;
402
            }
403
            let c = self.store.get_change(&h)?;
404
            stack.extend(c.deps.iter().copied());
405
            state.add_unchecked(c);
406
        }
407
        state.validate()?;
408
        Ok(state)
409
    }
410
411
    pub fn working_copy(&self) -> Result<(ChangeHash, Change)> {
412
        let view = self.view()?;
413
        let h = *view
414
            .workspaces
415
            .get(&self.workspace)
416
            .ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?;
417
        Ok((h, self.store.get_change(&h)?))
418
    }
419
420
    /// Heads of a bookmark's state (spec §10.1).
421
    pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> {
422
        match view.bookmarks.get(bookmark) {
423
            Some(st) => Ok(self.store.get_state(st)?.heads),
424
            None => Ok(vec![]),
425
        }
426
    }
427
428
    pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> {
429
        self.heads_of(&self.view()?, &self.config.bookmark)
430
    }
431
432
    // ------------------------------------------------------------ blobs
433
434
    fn blob_for(content: &[u8]) -> Blob {
435
        Blob {
436
            length: content.len() as u64,
437
            chunks: crate::chunk::chunks(content).into_iter().map(|c| hash_object(ObjectType::Chunk, c)).collect(),
438
        }
439
    }
440
441
    pub fn blob_ref(content: &[u8]) -> ObjectRef {
442
        Self::blob_for(content).hash()
443
    }
444
445
    pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> {
446
        for c in crate::chunk::chunks(content) {
447
            self.store.put_chunk(c)?;
448
        }
449
        Ok(self.store.put(ObjectType::Blob, &Self::blob_for(content).encode())?)
450
    }
451
452
    /// Read a blob's content, fetching it from the remote that withheld it
453
    /// when it is lazily absent (spec §13.5).
454
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
455
        if !self.store.has(r) && self.lazy_remote(r).is_some() {
456
            self.fetch_lazy_blob(r)?;
457
        }
458
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
459
        let mut out = Vec::with_capacity(blob.length as usize);
460
        for c in &blob.chunks {
461
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
462
        }
463
        Ok(out)
464
    }
465
466
    // ------------------------------------------------------------ working copy
467
468
    /// Whether a repository path is inside the sparse filter (spec §17).
469
    pub fn in_scope(&self, path: &str) -> bool {
470
        self.config.sparse_paths.is_empty() || self.config.sparse_paths.iter().any(|p| path == p || path.starts_with(&format!("{p}/")))
471
    }
472
473
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
474
        let mut wb = ignore::WalkBuilder::new(&self.root);
475
        wb.hidden(false)
476
            .git_ignore(false)
477
            .git_global(false)
478
            .git_exclude(false)
479
            .require_git(false)
480
            .follow_links(false)
481
            .add_custom_ignore_filename(".oxyignore");
482
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
483
        let mut out = BTreeMap::new();
484
        for entry in wb.build() {
485
            let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?;
486
            let path = entry.path();
487
            if path == self.root {
488
                continue;
489
            }
490
            let rel = path.strip_prefix(&self.root).unwrap();
491
            let rel: String = rel.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/");
492
            let Some(ft) = entry.file_type() else { continue };
493
            if ft.is_dir() || !self.in_scope(&rel) {
494
                continue;
495
            }
496
            if ft.is_symlink() {
497
                let target = fs::read_link(path)?;
498
                out.insert(rel, FsEntry { kind: NodeKind::Symlink, exec: false, content: target.to_string_lossy().as_bytes().to_vec() });
499
            } else if ft.is_file() {
500
                let exec = is_executable(&entry.metadata().map_err(|e| RepoError::Msg(e.to_string()))?);
501
                out.insert(rel, FsEntry { kind: NodeKind::File, exec, content: fs::read(path)? });
502
            }
503
        }
504
        Ok(out)
505
    }
506
}
507
508
impl Repo {
509
    /// Changes reachable from the bookmark and the working copy, newest first.
510
    pub fn log(&self) -> Result<Vec<LogEntry>> {
511
        let (wc_hash, _) = self.working_copy()?;
512
        let mut heads = self.bookmark_heads()?;
513
        heads.push(wc_hash);
514
        let state = self.load_state(&heads)?;
515
        let head_set: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
516
        let mut entries: Vec<LogEntry> = Vec::new();
517
        for (h, meta) in state.changes() {
518
            entries.push(LogEntry { hash: *h, change: meta.clone(), is_working_copy: *h == wc_hash, is_head: head_set.contains(h) });
519
        }
520
        entries.sort_by(|a, b| b.is_working_copy.cmp(&a.is_working_copy).then(b.change.hlc.cmp(&a.change.hlc)).then(b.hash.cmp(&a.hash)));
521
        Ok(entries)
522
    }
523
524
    /// Resolve a spec to a set of heads: a tag name, the current bookmark's
525
    /// name, or a single change (`resolve_change`).
526
    pub fn resolve_heads(&self, spec: &str) -> Result<Vec<ChangeHash>> {
527
        if spec == self.config.bookmark {
528
            return self.bookmark_heads();
529
        }
530
        if let Some(heads) = self.tag_heads(spec)? {
531
            return Ok(heads);
532
        }
533
        Ok(vec![self.resolve_change(spec)?])
534
    }
535
536
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working copy), or bookmark.
537
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
538
        if spec == "@" {
539
            return Ok(self.working_copy()?.0);
540
        }
541
        if spec.is_empty() || spec == "#" {
542
            return fail("empty change specifier");
543
        }
544
        let entries = self.log()?;
545
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
546
            entries.iter().filter(|e| e.hash.starts_with_hex(hp)).collect()
547
        } else {
548
            entries.iter().filter(|e| e.change.change_id.starts_with_hex(spec)).collect()
549
        };
550
        match matches.len() {
551
            1 => Ok(matches[0].hash),
552
            0 => fail(format!("no change matches {spec:?}")),
553
            _ => {
554
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
555
                if ids.len() == 1 {
556
                    fail(format!("change {spec} is divergent: {} variants", matches.len()))
557
                } else {
558
                    fail(format!("{spec:?} is ambiguous"))
559
                }
560
            }
561
        }
562
    }
563
564
    /// Human-readable description of what a change does, with line content.
565
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
566
        let change = self.store.get_change(hash)?;
567
        let base = self.load_state(&change.deps)?;
568
        let base_snapshot = base.materialize();
569
        Ok(render_change(&change, &base, &base_snapshot))
570
    }
571
}
572
573
fn remove_any(path: &Path) -> std::io::Result<()> {
574
    let m = fs::symlink_metadata(path)?;
575
    if m.is_dir() { fs::remove_dir_all(path) } else { fs::remove_file(path) }
576
}
577
578
#[cfg(unix)]
579
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
580
    use std::os::unix::fs::PermissionsExt;
581
    let mut perms = fs::metadata(path)?.permissions();
582
    let mode = perms.mode();
583
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
584
    if want != mode {
585
        perms.set_mode(want);
586
        fs::set_permissions(path, perms)?;
587
    }
588
    Ok(())
589
}
590
#[cfg(not(unix))]
591
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
592
    Ok(())
593
}
594
595
#[cfg(unix)]
596
fn is_executable(m: &fs::Metadata) -> bool {
597
    use std::os::unix::fs::PermissionsExt;
598
    m.permissions().mode() & 0o111 != 0
599
}
600
#[cfg(not(unix))]
601
fn is_executable(_m: &fs::Metadata) -> bool {
602
    false
603
}
604
605
fn op_ref(k: OpKey) -> OpRef {
606
    OpRef { change: k.0, index: k.1 }
607
}
608
609
fn split_path(path: &str) -> (&str, &str) {
610
    match path.rfind('/') {
611
        Some(i) => (&path[..i], &path[i + 1..]),
612
        None => ("", path),
613
    }
614
}