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