OXYGENHUB
# ebef3715554c oxygen / crates / oxy-core / src / repo / mod.rs
21.5 KiB · Rust · last changed Pack merging above 16 packs; modern CLI presentation (colour, spinners, --plain, NO_COLOR); oxy prompt with manifest-based dirty check and docs/prompt.md 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::{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
    pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> {
450
        let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?;
451
        let mut out = Vec::with_capacity(blob.length as usize);
452
        for c in &blob.chunks {
453
            out.extend(self.store.get_typed(c, ObjectType::Chunk)?);
454
        }
455
        Ok(out)
456
    }
457
458
    // ------------------------------------------------------------ working copy
459
460
    fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> {
461
        let mut wb = ignore::WalkBuilder::new(&self.root);
462
        wb.hidden(false)
463
            .git_ignore(false)
464
            .git_global(false)
465
            .git_exclude(false)
466
            .require_git(false)
467
            .follow_links(false)
468
            .add_custom_ignore_filename(".oxyignore");
469
        wb.filter_entry(|e| e.file_name() != OXY_DIR);
470
        let mut out = BTreeMap::new();
471
        for entry in wb.build() {
472
            let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?;
473
            let path = entry.path();
474
            if path == self.root {
475
                continue;
476
            }
477
            let rel = path.strip_prefix(&self.root).unwrap();
478
            let rel: String = rel.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/");
479
            let Some(ft) = entry.file_type() else { continue };
480
            if ft.is_dir() {
481
                continue;
482
            }
483
            if ft.is_symlink() {
484
                let target = fs::read_link(path)?;
485
                out.insert(rel, FsEntry { kind: NodeKind::Symlink, exec: false, content: target.to_string_lossy().as_bytes().to_vec() });
486
            } else if ft.is_file() {
487
                let exec = is_executable(&entry.metadata().map_err(|e| RepoError::Msg(e.to_string()))?);
488
                out.insert(rel, FsEntry { kind: NodeKind::File, exec, content: fs::read(path)? });
489
            }
490
        }
491
        Ok(out)
492
    }
493
}
494
495
impl Repo {
496
    /// Changes reachable from the bookmark and the working copy, newest first.
497
    pub fn log(&self) -> Result<Vec<LogEntry>> {
498
        let (wc_hash, _) = self.working_copy()?;
499
        let mut heads = self.bookmark_heads()?;
500
        heads.push(wc_hash);
501
        let state = self.load_state(&heads)?;
502
        let head_set: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
503
        let mut entries: Vec<LogEntry> = Vec::new();
504
        for (h, _) in state.changes() {
505
            entries.push(LogEntry { hash: *h, change: self.store.get_change(h)?, is_working_copy: *h == wc_hash, is_head: head_set.contains(h) });
506
        }
507
        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)));
508
        Ok(entries)
509
    }
510
511
    /// Resolve a change by ChangeId prefix, `#hash` prefix, `@` (working copy), or bookmark.
512
    pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> {
513
        if spec == "@" {
514
            return Ok(self.working_copy()?.0);
515
        }
516
        if spec.is_empty() || spec == "#" {
517
            return fail("empty change specifier");
518
        }
519
        let entries = self.log()?;
520
        let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') {
521
            entries.iter().filter(|e| e.hash.starts_with_hex(hp)).collect()
522
        } else {
523
            entries.iter().filter(|e| e.change.change_id.starts_with_hex(spec)).collect()
524
        };
525
        match matches.len() {
526
            1 => Ok(matches[0].hash),
527
            0 => fail(format!("no change matches {spec:?}")),
528
            _ => {
529
                let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect();
530
                if ids.len() == 1 {
531
                    fail(format!("change {spec} is divergent: {} variants", matches.len()))
532
                } else {
533
                    fail(format!("{spec:?} is ambiguous"))
534
                }
535
            }
536
        }
537
    }
538
539
    /// Human-readable description of what a change does, with line content.
540
    pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> {
541
        let change = self.store.get_change(hash)?;
542
        let base = self.load_state(&change.deps)?;
543
        let base_snapshot = base.materialize();
544
        Ok(render_change(&change, &base, &base_snapshot))
545
    }
546
}
547
548
fn remove_any(path: &Path) -> std::io::Result<()> {
549
    let m = fs::symlink_metadata(path)?;
550
    if m.is_dir() { fs::remove_dir_all(path) } else { fs::remove_file(path) }
551
}
552
553
#[cfg(unix)]
554
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> {
555
    use std::os::unix::fs::PermissionsExt;
556
    let mut perms = fs::metadata(path)?.permissions();
557
    let mode = perms.mode();
558
    let want = if exec { mode | 0o111 } else { mode & !0o111 };
559
    if want != mode {
560
        perms.set_mode(want);
561
        fs::set_permissions(path, perms)?;
562
    }
563
    Ok(())
564
}
565
#[cfg(not(unix))]
566
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> {
567
    Ok(())
568
}
569
570
#[cfg(unix)]
571
fn is_executable(m: &fs::Metadata) -> bool {
572
    use std::os::unix::fs::PermissionsExt;
573
    m.permissions().mode() & 0o111 != 0
574
}
575
#[cfg(not(unix))]
576
fn is_executable(_m: &fs::Metadata) -> bool {
577
    false
578
}
579
580
fn op_ref(k: OpKey) -> OpRef {
581
    OpRef { change: k.0, index: k.1 }
582
}
583
584
fn split_path(path: &str) -> (&str, &str) {
585
    match path.rfind('/') {
586
        Some(i) => (&path[..i], &path[i + 1..]),
587
        None => ("", path),
588
    }
589
}