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