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