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