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