OXYGENHUB
# 5259a3af8ee6 oxygen / crates / oxy-core / src / repo / snapshot.rs
25.9 KiB · Rust · last changed Sparse checkout: filter.paths, clone --sparse (implies lazy blobs), oxy sparse, scope-aware snapshot/checkout/prompt (spec 0.6f) 1 month ago source blame history raw
1
//! Working-copy snapshots, commits, and the change builder (spec §12.3).
2
3
use super::*;
4
5
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6
pub enum ChangeStatus {
7
    Added,
8
    Modified,
9
    Removed,
10
    ModeChanged,
11
    /// The file is conflicted in the base state and still contains conflict markers.
12
    ConflictEdited,
13
    /// The file was conflicted in the base state and the working copy resolves it.
14
    Resolved,
15
}
16
17
/// Lines that mark a conflict region in a materialized file (spec §9.5).
18
pub fn has_conflict_markers(content: &[u8]) -> bool {
19
    split_lines(content).iter().any(|l| {
20
        l.starts_with(b"<<<<<<< oxy conflict") || l.starts_with(b"======= oxy conflict") || l.starts_with(b">>>>>>> oxy conflict")
21
    })
22
}
23
24
#[derive(Clone, Debug, PartialEq, Eq)]
25
pub struct PathStatus {
26
    pub path: String,
27
    pub status: ChangeStatus,
28
}
29
30
/// Operations of a change built from the working directory against a base.
31
pub(crate) struct BuiltChange {
32
    pub tree_ops: Vec<TreeOp>,
33
    pub edits: Vec<Edit>,
34
    pub contributors: Vec<ChangeHash>,
35
    pub resolves: bool,
36
    pub statuses: Vec<PathStatus>,
37
}
38
39
/// Result of snapshotting the working copy.
40
pub struct SnapshotResult {
41
    pub wc_hash: ChangeHash,
42
    pub wc: Change,
43
    /// The base state (closure of the working-copy change's dependencies).
44
    pub base: State,
45
    pub base_snapshot: Snapshot,
46
    pub statuses: Vec<PathStatus>,
47
    /// Whether the snapshot rewrote the working-copy change.
48
    pub changed: bool,
49
    /// Whether the working copy resolves conflicts of its base (spec §9.6).
50
    pub resolves: bool,
51
    /// Changes that contributed to the conflicts being resolved.
52
    pub contributors: Vec<ChangeHash>,
53
}
54
55
pub fn is_binary(content: &[u8]) -> bool {
56
    content[..content.len().min(BINARY_SNIFF)].contains(&0)
57
}
58
59
impl Repo {
60
    /// Diff the files on disk against `base` and build the operations of a
61
    /// change from `base` to the working directory. `reuse` maps paths to the
62
    /// NodeIds an earlier version of the same change assigned to new paths.
63
    pub(crate) fn build_against(&self, base: &State, base_snapshot: &Snapshot, reuse: HashMap<String, (NodeId, NodeKind)>) -> Result<BuiltChange> {
64
        let fs_entries = self.walk_working_copy()?;
65
        self.build_from_entries(base, base_snapshot, reuse, &fs_entries)
66
    }
67
68
    /// Like `build_against`, for files given in memory (imports).
69
    pub(crate) fn build_from_entries(&self, base: &State, base_snapshot: &Snapshot, reuse: HashMap<String, (NodeId, NodeKind)>, fs_entries: &BTreeMap<String, FsEntry>) -> Result<BuiltChange> {
70
        let mut b = ChangeBuilder::new(base, base_snapshot, reuse);
71
        for (path, fs_entry) in fs_entries {
72
            match base_snapshot.files.get(path) {
73
                None => b.add_path(self, path, fs_entry)?,
74
                Some(expected) => b.update_path(self, path, fs_entry, expected)?,
75
            }
76
        }
77
        for (path, expected) in &base_snapshot.files {
78
            if fs_entries.contains_key(path) || !self.in_scope(path) {
79
                continue;
80
            }
81
            // A directory stays while anything under it exists or is out of scope.
82
            let still_needed = expected.kind == NodeKind::Dir
83
                && (fs_entries.keys().any(|p| p.starts_with(&format!("{path}/")))
84
                    || base_snapshot.files.keys().any(|p| p.starts_with(&format!("{path}/")) && !self.in_scope(p)));
85
            if !still_needed {
86
                b.remove_path(path, expected);
87
            }
88
        }
89
        let mut statuses = b.statuses;
90
        statuses.sort_by(|a, b| a.path.cmp(&b.path));
91
        Ok(BuiltChange { tree_ops: b.tree_ops, edits: b.edits, contributors: b.contributors.into_iter().collect(), resolves: b.resolves, statuses })
92
    }
93
94
    /// Store a change and, when `core.sign = change` and we are its author,
95
    /// sign it. A rewritten change by another author is stored unsigned: only
96
    /// its author (or a delegate) can vouch for it.
97
    pub(crate) fn store_signed(&self, change: &Change) -> Result<ChangeHash> {
98
        let ours = change.author == self.author();
99
        if self.config.sign_changes && ours && self.secret_key()?.is_none() {
100
            return fail("core.sign is \"change\" but no secret key is available for author.key");
101
        }
102
        let hash = self.store.put_change(change)?;
103
        if self.config.sign_changes && ours {
104
            self.sign_change(&hash)?;
105
        }
106
        Ok(hash)
107
    }
108
109
    /// Snapshot the working copy into the working-copy change (spec §12.3).
110
    pub fn snapshot(&self, command: &str) -> Result<SnapshotResult> {
111
        let (op_ref, op) = self.head_op()?;
112
        let (old_hash, old_wc) = self.working_copy()?;
113
        let base = self.load_state(&old_wc.deps)?;
114
        let base_snapshot = base.materialize();
115
116
        // Reuse the NodeIds the previous working-copy version assigned to new
117
        // paths, so an unchanged working copy hashes identically (spec §12.3).
118
        let reuse = added_node_paths(&old_wc, &base_snapshot);
119
        let built = self.build_against(&base, &base_snapshot, reuse)?;
120
121
        let mut wc = Change {
122
            change_id: old_wc.change_id,
123
            deps: vec![],
124
            author: self.author(),
125
            hlc: old_wc.hlc,
126
            message: old_wc.message.clone(),
127
            tree_ops: built.tree_ops,
128
            edits: built.edits,
129
            kind: ChangeKind::WorkingCopy,
130
        };
131
        let base_heads = base.maximal(&old_wc.deps);
132
        let mut deps: BTreeSet<ChangeHash> = base_heads.into_iter().collect();
133
        deps.extend(referenced_changes(&wc, &base));
134
        deps.extend(built.contributors.iter().copied());
135
        wc.deps = deps.into_iter().collect();
136
        wc.normalize();
137
        let resolves = built.resolves;
138
        let contributors = built.contributors;
139
        let statuses = built.statuses;
140
        // Empty snapshot: hash the candidate before storing; only record an op on change.
141
        let new_hash = wc.hash();
142
        let changed = new_hash != old_hash;
143
        if changed {
144
            self.store.put_change(&wc)?;
145
            let mut view = op.view.clone();
146
            view.workspaces.insert(self.workspace, new_hash);
147
            self.record_op(&[op_ref], &format!("{command}{SNAPSHOT_SUFFIX}"), view)?;
148
        }
149
        // The prompt compares against this without recording anything.
150
        self.write_manifest(base_snapshot.is_conflicted(), !wc.tree_ops.is_empty() || !wc.edits.is_empty())?;
151
        Ok(SnapshotResult { wc_hash: new_hash, wc, base, base_snapshot, statuses, changed, resolves, contributors })
152
    }
153
154
    /// Turn the working-copy change into a normal change on the bookmark (spec §12.3).
155
    pub fn commit(&self, message: &str, extra_deps: &[ChangeHash]) -> Result<ChangeHash> {
156
        let snap = self.snapshot("oxy commit")?;
157
        if snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty() {
158
            return fail("nothing to commit: the working copy matches its base");
159
        }
160
        if let Some(s) = snap.statuses.iter().find(|s| s.status == ChangeStatus::ConflictEdited) {
161
            return fail(format!("{} still contains conflict markers", s.path));
162
        }
163
        if message.trim().is_empty() {
164
            return fail("a commit message is required");
165
        }
166
        let (op_ref, op) = self.head_op()?;
167
        let mut deps: BTreeSet<ChangeHash> = referenced_changes(&snap.wc, &snap.base);
168
        // A resolution depends on every change that contributed to the
169
        // conflict (spec §8.1). Tree and opaque conflicts are resolved through
170
        // ordinary operations whose references already cover the contributors.
171
        deps.extend(snap.contributors.iter().copied());
172
        for d in extra_deps {
173
            if !snap.base.contains(d) {
174
                return fail(format!("--depends-on {d}: not in the working copy's base state"));
175
            }
176
            deps.insert(*d);
177
        }
178
        let mut change = Change {
179
            change_id: snap.wc.change_id,
180
            deps: deps.into_iter().collect(),
181
            author: self.author(),
182
            hlc: Hlc::now(),
183
            message: message.trim_end().to_string(),
184
            tree_ops: snap.wc.tree_ops.clone(),
185
            edits: snap.wc.edits.clone(),
186
            kind: if snap.resolves { ChangeKind::Resolution } else { ChangeKind::Normal },
187
        };
188
        change.normalize();
189
        let hash = self.store_signed(&change)?;
190
191
        // New bookmark heads: maximal elements of old heads plus the new change.
192
        // The working copy continues on its own base plus the new change, which
193
        // is exactly what the files on disk contain; the bookmark may hold
194
        // other heads (and conflicts) the working copy has not checked out.
195
        let old_heads = self.heads_of(&op.view, &self.config.bookmark)?;
196
        let old_base = snap.base.maximal(&snap.wc.deps);
197
        let mut all: Vec<ChangeHash> = old_heads.clone();
198
        all.extend(old_base.iter().copied());
199
        all.push(hash);
200
        let mut st = self.load_state(&all)?;
201
        st.add(change)?;
202
        let mut with_new = old_heads.clone();
203
        with_new.push(hash);
204
        let new_heads = st.maximal(&with_new);
205
        // Automatic checkpoint once enough changes accumulated (spec §11).
206
        let since = self.latest_checkpoint(&self.config.bookmark)?.map(|(_, cp)| cp.count).unwrap_or(0);
207
        if self.config.checkpoint_interval > 0 && (st.len() as u64).saturating_sub(since) >= self.config.checkpoint_interval {
208
            let cp_state = self.load_state_full(&new_heads)?;
209
            self.write_checkpoint(&self.config.bookmark, &cp_state, &new_heads)?;
210
        }
211
        let mut wc_base = old_base.clone();
212
        wc_base.push(hash);
213
        let wc_base = st.maximal(&wc_base);
214
215
        let wc = self.new_working_copy(wc_base, "");
216
        let wc_hash = self.store.put_change(&wc)?;
217
        let mut view = op.view.clone();
218
        view.bookmarks.insert(self.config.bookmark.clone(), self.store.put_state(&StateObject::new(new_heads))?);
219
        view.workspaces.insert(self.workspace, wc_hash);
220
        self.record_op(&[op_ref], &format!("oxy commit -m {message:?}"), view)?;
221
        self.write_manifest(snap.base_snapshot.is_conflicted() && !snap.resolves, false)?;
222
        self.maybe_autopack()?;
223
        Ok(hash)
224
    }
225
}
226
227
/// Builds the tree ops and edits of a working-copy change against a base.
228
struct ChangeBuilder<'a> {
229
    base: &'a State,
230
    base_snapshot: &'a Snapshot,
231
    tree_ops: Vec<TreeOp>,
232
    edits: Vec<Edit>,
233
    statuses: Vec<PathStatus>,
234
    dir_nodes: HashMap<String, NodeId>,
235
    reuse: HashMap<String, (NodeId, NodeKind)>,
236
    /// Changes that contributed to conflicts this working copy resolves.
237
    contributors: BTreeSet<ChangeHash>,
238
    resolves: bool,
239
}
240
241
impl<'a> ChangeBuilder<'a> {
242
    fn new(base: &'a State, base_snapshot: &'a Snapshot, reuse: HashMap<String, (NodeId, NodeKind)>) -> Self {
243
        let mut dir_nodes: HashMap<String, NodeId> = HashMap::new();
244
        dir_nodes.insert(String::new(), NodeId::ROOT);
245
        for (p, f) in &base_snapshot.files {
246
            if f.kind == NodeKind::Dir {
247
                dir_nodes.insert(p.clone(), f.node);
248
            }
249
        }
250
        ChangeBuilder { base, base_snapshot, tree_ops: vec![], edits: vec![], statuses: vec![], dir_nodes, reuse, contributors: BTreeSet::new(), resolves: false }
251
    }
252
253
    fn reused_node(&self, path: &str, kind: NodeKind) -> Option<NodeId> {
254
        self.reuse.get(path).filter(|(_, k)| *k == kind).map(|(n, _)| *n)
255
    }
256
257
    fn ensure_dir(&mut self, path: &str) -> NodeId {
258
        if let Some(n) = self.dir_nodes.get(path) {
259
            return *n;
260
        }
261
        let mut parent = NodeId::ROOT;
262
        let mut prefix = String::new();
263
        for comp in path.split('/') {
264
            if !prefix.is_empty() {
265
                prefix.push('/');
266
            }
267
            prefix.push_str(comp);
268
            parent = match self.dir_nodes.get(&prefix) {
269
                Some(n) => *n,
270
                None => {
271
                    let node = self.reused_node(&prefix, NodeKind::Dir).unwrap_or_else(NodeId::random);
272
                    self.tree_ops.push(TreeOp::AddNode { node, kind: NodeKind::Dir, mode: Mode::default(), parent, name: comp.to_string() });
273
                    self.dir_nodes.insert(prefix.clone(), node);
274
                    node
275
                }
276
            };
277
        }
278
        parent
279
    }
280
281
    fn add_path(&mut self, repo: &Repo, path: &str, e: &FsEntry) -> Result<()> {
282
        let (dir, name) = split_path(path);
283
        let parent = self.ensure_dir(dir);
284
        let node = self.reused_node(path, e.kind).unwrap_or_else(NodeId::random);
285
        let opaque = e.kind == NodeKind::Symlink || is_binary(&e.content);
286
        self.tree_ops.push(TreeOp::AddNode { node, kind: e.kind, mode: Mode { exec: e.exec, opaque }, parent, name: name.to_string() });
287
        if opaque {
288
            let blob = repo.store_blob(&e.content)?;
289
            self.edits.push(Edit::Replace { node, old: None, new: Some(blob) });
290
        } else if !e.content.is_empty() {
291
            self.edits.push(Edit::Insert {
292
                node,
293
                after: crate::objects::AtomRef::Start,
294
                before: crate::objects::AtomRef::End,
295
                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
296
            });
297
        }
298
        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Added });
299
        Ok(())
300
    }
301
302
    fn remove_path(&mut self, path: &str, expected: &crate::state::FileState) {
303
        let entry = &self.base_snapshot.tree.entries[path];
304
        self.tree_ops.push(TreeOp::RemoveNode { node: expected.node, placement: op_ref(entry.placement) });
305
        if path.contains(".oxy-conflict-") || expected.is_conflicted() {
306
            self.resolves = true;
307
        }
308
        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Removed });
309
    }
310
311
    fn update_path(&mut self, repo: &Repo, path: &str, e: &FsEntry, expected: &crate::state::FileState) -> Result<()> {
312
        if expected.kind != e.kind {
313
            self.remove_path(path, expected);
314
            self.statuses.pop();
315
            self.add_path(repo, path, e)?;
316
            self.statuses.pop();
317
            self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Modified });
318
            return Ok(());
319
        }
320
        let entry = &self.base_snapshot.tree.entries[path];
321
        let node = expected.node;
322
        let mode_atom = entry.mode_atom.map(op_ref);
323
        let mut status: Option<ChangeStatus> = None;
324
        match &expected.content {
325
            FileContent::Dir => {}
326
            FileContent::Text { bytes, materialized } => {
327
                if materialized.is_conflicted() {
328
                    if bytes == &e.content {
329
                        return Ok(());
330
                    }
331
                    if has_conflict_markers(&e.content) {
332
                        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::ConflictEdited });
333
                        return Ok(());
334
                    }
335
                    // Resolution (spec §9.6): diff against the unconflicted lines
336
                    // with each region as a gap, then retire every region atom.
337
                    // Whatever the author kept from a region is re-inserted as
338
                    // new atoms, which leaves the graph totally ordered.
339
                    let regions = self.base.conflict_regions(&node);
340
                    let mut edits = text_edits(node, &regions.plain, &e.content);
341
                    if !regions.region_atoms.is_empty() {
342
                        edits.insert(0, Edit::Delete { node, atoms: ranges(&regions.region_atoms) });
343
                    }
344
                    self.edits.extend(edits);
345
                    self.contributors.extend(regions.contributors);
346
                    self.resolves = true;
347
                    if e.exec != expected.mode.exec {
348
                        if let Some(old) = mode_atom {
349
                            self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: false } });
350
                        }
351
                    }
352
                    self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::Resolved });
353
                    return Ok(());
354
                }
355
                if bytes != &e.content {
356
                    if is_binary(&e.content) {
357
                        // Text → opaque (spec §7.5).
358
                        if let Some(old) = mode_atom {
359
                            self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: true } });
360
                        }
361
                        let live: Vec<_> = repo_live_keys(self.base, &node);
362
                        if !live.is_empty() {
363
                            self.edits.push(Edit::Delete { node, atoms: ranges(&live) });
364
                        }
365
                        let blob = repo.store_blob(&e.content)?;
366
                        self.edits.push(Edit::Replace { node, old: None, new: Some(blob) });
367
                        status = Some(ChangeStatus::Modified);
368
                    } else {
369
                        let old = self.base.live_lines(&node);
370
                        let edits = text_edits(node, &old, &e.content);
371
                        if !edits.is_empty() {
372
                            self.edits.extend(edits);
373
                            status = Some(ChangeStatus::Modified);
374
                        }
375
                    }
376
                }
377
                let switched_to_opaque = status == Some(ChangeStatus::Modified) && is_binary(&e.content);
378
                if !switched_to_opaque && e.exec != expected.mode.exec {
379
                    if let Some(old) = mode_atom {
380
                        self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: false } });
381
                        status.get_or_insert(ChangeStatus::ModeChanged);
382
                    }
383
                }
384
            }
385
            FileContent::Opaque { blobs } => {
386
                let new_ref = Repo::blob_ref(&e.content);
387
                if blobs.len() > 1 {
388
                    if !blobs.contains(&new_ref) {
389
                        self.statuses.push(PathStatus { path: path.to_string(), status: ChangeStatus::ConflictEdited });
390
                    }
391
                    return Ok(());
392
                }
393
                let current = blobs.first().copied();
394
                if current != Some(new_ref) {
395
                    if e.kind == NodeKind::File && !is_binary(&e.content) {
396
                        // Opaque → text (spec §7.5).
397
                        if let Some(old) = mode_atom {
398
                            self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: false } });
399
                        }
400
                        self.edits.push(Edit::Replace { node, old: current, new: None });
401
                        if !e.content.is_empty() {
402
                            self.edits.push(Edit::Insert {
403
                                node,
404
                                after: crate::objects::AtomRef::Start,
405
                                before: crate::objects::AtomRef::End,
406
                                lines: split_lines(&e.content).iter().map(|l| l.to_vec()).collect(),
407
                            });
408
                        }
409
                    } else {
410
                        let blob = repo.store_blob(&e.content)?;
411
                        self.edits.push(Edit::Replace { node, old: current, new: Some(blob) });
412
                    }
413
                    status = Some(ChangeStatus::Modified);
414
                } else if e.kind == NodeKind::File && e.exec != expected.mode.exec {
415
                    if let Some(old) = mode_atom {
416
                        self.tree_ops.push(TreeOp::SetMode { node, old, mode: Mode { exec: e.exec, opaque: true } });
417
                        status = Some(ChangeStatus::ModeChanged);
418
                    }
419
                }
420
            }
421
        }
422
        if let Some(s) = status {
423
            self.statuses.push(PathStatus { path: path.to_string(), status: s });
424
        }
425
        Ok(())
426
    }
427
}
428
429
fn repo_live_keys(base: &State, node: &NodeId) -> Vec<crate::graph::AtomKey> {
430
    base.live_lines(node).into_iter().map(|(k, _)| k).collect()
431
}
432
433
/// The changes a change's scope references (spec §8.1): introducers of every
434
/// atom, placement, and mode it touches, and of every node it operates on.
435
pub fn referenced_changes(change: &Change, base: &State) -> BTreeSet<ChangeHash> {
436
    let mut out = BTreeSet::new();
437
    let opref = |r: &OpRef, out: &mut BTreeSet<ChangeHash>| {
438
        if !r.change.is_zero() {
439
            out.insert(r.change);
440
        }
441
    };
442
    let mut nodes: Vec<NodeId> = Vec::new();
443
    for op in &change.tree_ops {
444
        match op {
445
            TreeOp::AddNode { parent, .. } => nodes.push(*parent),
446
            TreeOp::RemoveNode { node, placement } => {
447
                nodes.push(*node);
448
                opref(placement, &mut out);
449
            }
450
            TreeOp::Move { node, old, parent, .. } => {
451
                nodes.push(*node);
452
                nodes.push(*parent);
453
                opref(old, &mut out);
454
            }
455
            TreeOp::SetMode { node, old, .. } => {
456
                nodes.push(*node);
457
                opref(old, &mut out);
458
            }
459
        }
460
    }
461
    for e in &change.edits {
462
        nodes.push(e.node());
463
        match e {
464
            Edit::Insert { after, before, .. } => {
465
                for r in [after, before] {
466
                    if let crate::objects::AtomRef::Atom { change, .. } = r {
467
                        if !change.is_zero() {
468
                            out.insert(*change);
469
                        }
470
                    }
471
                }
472
            }
473
            Edit::Delete { atoms, .. } => {
474
                for r in atoms {
475
                    if !r.change.is_zero() {
476
                        out.insert(r.change);
477
                    }
478
                }
479
            }
480
            Edit::Replace { .. } => {}
481
        }
482
    }
483
    for n in nodes {
484
        if let Some(h) = base.tree().introducer(&n) {
485
            out.insert(h);
486
        }
487
    }
488
    out
489
}
490
491
/// Paths of the nodes a change adds on top of `base_snapshot`.
492
pub fn added_node_paths(change: &Change, base_snapshot: &Snapshot) -> HashMap<String, (NodeId, NodeKind)> {
493
    let by_node = base_snapshot.tree.by_node();
494
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
495
    for op in &change.tree_ops {
496
        if let TreeOp::AddNode { node, parent, name, kind, .. } = op {
497
            new_names.insert(*node, (*parent, name.clone(), *kind));
498
        }
499
    }
500
    let mut out = HashMap::new();
501
    for (node, (_, _, kind)) in &new_names {
502
        if let Some(path) = path_of_node(node, &by_node, &new_names) {
503
            out.insert(path, (*node, *kind));
504
        }
505
    }
506
    out
507
}
508
509
fn path_of_node(
510
    n: &NodeId,
511
    by_node: &HashMap<NodeId, &crate::tree::TreeEntry>,
512
    new_names: &HashMap<NodeId, (NodeId, String, NodeKind)>,
513
) -> Option<String> {
514
    if let Some(e) = by_node.get(n) {
515
        return Some(e.path.clone());
516
    }
517
    let mut parts = Vec::new();
518
    let mut cur = *n;
519
    loop {
520
        if cur.is_root() {
521
            break;
522
        }
523
        if let Some(e) = by_node.get(&cur) {
524
            if !e.path.is_empty() {
525
                parts.push(e.path.clone());
526
            }
527
            break;
528
        }
529
        let (parent, name, _) = new_names.get(&cur)?;
530
        parts.push(name.clone());
531
        cur = *parent;
532
    }
533
    parts.reverse();
534
    Some(parts.join("/"))
535
}
536
537
/// Render a change's operations with line content, using `base` for deleted lines.
538
pub fn render_change(change: &Change, base: &State, base_snapshot: &Snapshot) -> String {
539
    let by_node = base_snapshot.tree.by_node();
540
    let mut new_names: HashMap<NodeId, (NodeId, String, NodeKind)> = HashMap::new();
541
    for op in &change.tree_ops {
542
        if let TreeOp::AddNode { node, parent, name, kind, .. } = op {
543
            new_names.insert(*node, (*parent, name.clone(), *kind));
544
        }
545
    }
546
    let path_of = |n: &NodeId| -> String { path_of_node(n, &by_node, &new_names).unwrap_or_else(|| format!("<node {}>", n.short(8))) };
547
548
    let mut out = String::new();
549
    for op in &change.tree_ops {
550
        match op {
551
            TreeOp::AddNode { node, kind, mode, .. } => {
552
                out.push_str(&format!("A {} ({:?}{}{})\n", path_of(node), kind, if mode.exec { ", exec" } else { "" }, if mode.opaque { ", opaque" } else { "" }));
553
            }
554
            TreeOp::RemoveNode { node, .. } => out.push_str(&format!("D {}\n", path_of(node))),
555
            TreeOp::Move { node, name, .. } => out.push_str(&format!("R {} -> {}\n", path_of(node), name)),
556
            TreeOp::SetMode { node, mode, .. } => {
557
                out.push_str(&format!("M {} mode: exec={} opaque={}\n", path_of(node), mode.exec, mode.opaque));
558
            }
559
        }
560
    }
561
    let mut last_node: Option<NodeId> = None;
562
    for e in &change.edits {
563
        let n = e.node();
564
        if last_node != Some(n) {
565
            out.push_str(&format!("--- {}\n", path_of(&n)));
566
            last_node = Some(n);
567
        }
568
        match e {
569
            Edit::Insert { lines, .. } => {
570
                for l in lines {
571
                    out.push('+');
572
                    out.push_str(&String::from_utf8_lossy(l));
573
                    if !l.ends_with(b"\n") {
574
                        out.push('\n');
575
                    }
576
                }
577
            }
578
            Edit::Delete { atoms, .. } => {
579
                for r in atoms {
580
                    for i in r.from..r.to {
581
                        let content = base.file(&n).and_then(|g| g.content(&(r.change, i))).unwrap_or(b"<unknown>\n");
582
                        out.push('-');
583
                        out.push_str(&String::from_utf8_lossy(content));
584
                        if !content.ends_with(b"\n") {
585
                            out.push('\n');
586
                        }
587
                    }
588
                }
589
            }
590
            Edit::Replace { old, new, .. } => {
591
                out.push_str(&format!(
592
                    "  opaque content {} -> {}\n",
593
                    old.map(|o| o.short(12)).unwrap_or_else(|| "none".into()),
594
                    new.map(|o| o.short(12)).unwrap_or_else(|| "none".into())
595
                ));
596
            }
597
        }
598
    }
599
    out
600
}