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