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