Skip to main content

vault_core/
textdiff.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! A small line diff for rendered config files (Phase 35).
4//!
5//! Exists once, in Rust: the CLI, the server and the app all ask for a diff
6//! instead of each carrying one, so the three cannot disagree about what changed.
7//!
8//! Strategy: strip the common head and tail, then a longest-common-subsequence
9//! table over what is left. Rendered configs are tens to a few thousand lines
10//! and differ in a few places, so the middle is small. When it is not
11//! (`MAX_CELLS`), the middle is reported as one deletion and one insertion
12//! rather than spending quadratic memory; the output stays correct, only less
13//! minimal. // ponytail: LCS table, switch to Myers O(ND) if a real config ever
14//! hits the cell ceiling.
15
16/// Largest `n * m` the LCS table may reach (16 MB of `u32`).
17pub const MAX_CELLS: usize = 4_000_000;
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum Op<'a> {
21    Equal(&'a str),
22    Delete(&'a str),
23    Insert(&'a str),
24}
25
26/// The edit script turning `a` into `b`, line by line.
27pub fn diff_ops<'a>(a: &'a str, b: &'a str) -> Vec<Op<'a>> {
28    let av: Vec<&str> = a.lines().collect();
29    let bv: Vec<&str> = b.lines().collect();
30    let head = av.iter().zip(&bv).take_while(|(x, y)| x == y).count();
31    let tail = av[head..]
32        .iter()
33        .rev()
34        .zip(bv[head..].iter().rev())
35        .take_while(|(x, y)| x == y)
36        .count();
37    let am = &av[head..av.len() - tail];
38    let bm = &bv[head..bv.len() - tail];
39
40    let mut ops: Vec<Op> = av[..head].iter().map(|l| Op::Equal(l)).collect();
41    if am.len().saturating_mul(bm.len()) > MAX_CELLS {
42        ops.extend(am.iter().map(|l| Op::Delete(l)));
43        ops.extend(bm.iter().map(|l| Op::Insert(l)));
44    } else {
45        let (n, m) = (am.len(), bm.len());
46        // lcs[i][j] = length of the LCS of am[i..] and bm[j..]
47        let mut lcs = vec![0u32; (n + 1) * (m + 1)];
48        let at = |i: usize, j: usize| i * (m + 1) + j;
49        for i in (0..n).rev() {
50            for j in (0..m).rev() {
51                lcs[at(i, j)] = if am[i] == bm[j] {
52                    lcs[at(i + 1, j + 1)] + 1
53                } else {
54                    lcs[at(i + 1, j)].max(lcs[at(i, j + 1)])
55                };
56            }
57        }
58        let (mut i, mut j) = (0, 0);
59        while i < n && j < m {
60            if am[i] == bm[j] {
61                ops.push(Op::Equal(am[i]));
62                i += 1;
63                j += 1;
64            } else if lcs[at(i + 1, j)] >= lcs[at(i, j + 1)] {
65                ops.push(Op::Delete(am[i]));
66                i += 1;
67            } else {
68                ops.push(Op::Insert(bm[j]));
69                j += 1;
70            }
71        }
72        ops.extend(am[i..].iter().map(|l| Op::Delete(l)));
73        ops.extend(bm[j..].iter().map(|l| Op::Insert(l)));
74    }
75    ops.extend(av[av.len() - tail..].iter().map(|l| Op::Equal(l)));
76    ops
77}
78
79/// Counts of changed lines: `(added, removed)`.
80pub fn stat(ops: &[Op]) -> (usize, usize) {
81    ops.iter().fold((0, 0), |(a, r), o| match o {
82        Op::Insert(_) => (a + 1, r),
83        Op::Delete(_) => (a, r + 1),
84        Op::Equal(_) => (a, r),
85    })
86}
87
88/// A unified diff with `context` lines around each change. Empty string when
89/// the two sides are identical.
90pub fn unified(a_label: &str, b_label: &str, a: &str, b: &str, context: usize) -> String {
91    let ops = diff_ops(a, b);
92    if stat(&ops) == (0, 0) {
93        return String::new();
94    }
95    // Index of each op's line in a and b (1-based), to head the hunks.
96    let mut pos = Vec::with_capacity(ops.len());
97    let (mut la, mut lb) = (1usize, 1usize);
98    for o in &ops {
99        pos.push((la, lb));
100        match o {
101            Op::Equal(_) => {
102                la += 1;
103                lb += 1;
104            }
105            Op::Delete(_) => la += 1,
106            Op::Insert(_) => lb += 1,
107        }
108    }
109    let changed: Vec<usize> = ops
110        .iter()
111        .enumerate()
112        .filter(|(_, o)| !matches!(o, Op::Equal(_)))
113        .map(|(i, _)| i)
114        .collect();
115
116    // Merge changes whose context windows touch into one hunk.
117    let mut hunks: Vec<(usize, usize)> = Vec::new();
118    for &c in &changed {
119        let lo = c.saturating_sub(context);
120        let hi = (c + context + 1).min(ops.len());
121        match hunks.last_mut() {
122            Some(last) if lo <= last.1 => last.1 = last.1.max(hi),
123            _ => hunks.push((lo, hi)),
124        }
125    }
126
127    let mut out = format!("--- {a_label}\n+++ {b_label}\n");
128    for (lo, hi) in hunks {
129        let slice = &ops[lo..hi];
130        let a_len = slice.iter().filter(|o| !matches!(o, Op::Insert(_))).count();
131        let b_len = slice.iter().filter(|o| !matches!(o, Op::Delete(_))).count();
132        let (sa, sb) = pos[lo];
133        out.push_str(&format!(
134            "@@ -{},{} +{},{} @@\n",
135            if a_len == 0 { sa - 1 } else { sa },
136            a_len,
137            if b_len == 0 { sb - 1 } else { sb },
138            b_len
139        ));
140        for o in slice {
141            let (p, l) = match o {
142                Op::Equal(l) => (' ', l),
143                Op::Delete(l) => ('-', l),
144                Op::Insert(l) => ('+', l),
145            };
146            out.push(p);
147            out.push_str(l);
148            out.push('\n');
149        }
150    }
151    out
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    fn rebuild(ops: &[Op], side_a: bool) -> String {
159        let mut v = Vec::new();
160        for o in ops {
161            match (o, side_a) {
162                (Op::Equal(l), _) | (Op::Delete(l), true) | (Op::Insert(l), false) => v.push(*l),
163                _ => {}
164            }
165        }
166        v.join("\n")
167    }
168
169    #[test]
170    fn identical_text_has_no_diff() {
171        assert_eq!(unified("a", "b", "x\ny\n", "x\ny\n", 3), "");
172    }
173
174    #[test]
175    fn a_changed_line_shows_as_a_delete_and_an_insert_with_context() {
176        let d = unified("old", "new", "a\nb\nc\nd\ne\n", "a\nb\nX\nd\ne\n", 1);
177        assert_eq!(d, "--- old\n+++ new\n@@ -2,3 +2,3 @@\n b\n-c\n+X\n d\n");
178    }
179
180    #[test]
181    fn distant_changes_make_separate_hunks_and_near_ones_merge() {
182        let a: String = (1..=20).map(|i| format!("l{i}\n")).collect();
183        let far = a.replace("l2\n", "L2\n").replace("l19\n", "L19\n");
184        assert_eq!(unified("a", "b", &a, &far, 1).matches("@@ -").count(), 2);
185        let near = a.replace("l5\n", "L5\n").replace("l7\n", "L7\n");
186        assert_eq!(unified("a", "b", &a, &near, 1).matches("@@ -").count(), 1);
187    }
188
189    #[test]
190    fn pure_additions_and_removals_head_their_hunks_correctly() {
191        assert_eq!(
192            unified("a", "b", "", "x\ny\n", 3),
193            "--- a\n+++ b\n@@ -0,0 +1,2 @@\n+x\n+y\n"
194        );
195        assert_eq!(
196            unified("a", "b", "x\ny\n", "", 3),
197            "--- a\n+++ b\n@@ -1,2 +0,0 @@\n-x\n-y\n"
198        );
199    }
200
201    #[test]
202    fn the_script_always_reproduces_both_sides() {
203        let cases = [
204            ("a\nb\nc", "a\nc"),
205            ("", "a"),
206            ("a", ""),
207            ("a\nb\nc\nd", "d\nc\nb\na"),
208            ("x\nx\nx", "x\nx"),
209            ("1\n2\n3\n4\n5\n6", "1\n3\n2\n4\n6\n5\n7"),
210        ];
211        for (a, b) in cases {
212            let ops = diff_ops(a, b);
213            assert_eq!(rebuild(&ops, true), a, "side a of {a:?} -> {b:?}");
214            assert_eq!(rebuild(&ops, false), b, "side b of {a:?} -> {b:?}");
215        }
216    }
217
218    #[test]
219    fn the_diff_is_minimal_for_a_single_insertion() {
220        let ops = diff_ops("a\nb\nc", "a\nb\nNEW\nc");
221        assert_eq!(stat(&ops), (1, 0));
222    }
223
224    #[test]
225    fn past_the_cell_ceiling_the_middle_is_replaced_whole_but_still_correct() {
226        let a: String = (0..2100).map(|i| format!("a{i}\n")).collect();
227        let b: String = (0..2100).map(|i| format!("b{i}\n")).collect();
228        let ops = diff_ops(&a, &b);
229        assert_eq!(stat(&ops), (2100, 2100));
230        assert_eq!(rebuild(&ops, true), a.trim_end());
231    }
232}