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