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