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