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