rustik-diff 0.3.0

Pure diff viewer and Git diff pager for Rustik.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! Per-pair intra-line word diff.
//!
//! Walks each hunk's change blocks (consecutive `-`/`+` runs separated by
//! context lines) and pairs the i-th deletion with the i-th addition in the
//! same block. For each pair, the line texts are tokenized and an LCS is
//! computed to find the byte ranges that differ between them.
//!
//! A similarity gate filters out pairs whose lines share too few tokens --
//! those are two distinct edits that happen to be adjacent, not two versions
//! of the same line. Highlighting their internal differences only produces
//! noise, so the overlay is suppressed and the dim row tint stands alone.
//!
//! The same gate naturally handles pure-addition and pure-deletion runs:
//! no pairs form, so no overlay is emitted.

use std::collections::BTreeMap;
use std::ops::Range;

use crate::{DiffLine, DiffLineKind, Hunk, RowId};

/// Numerator of the minimum LCS-match ratio. A pair must match at least
/// `SIMILARITY_NUMERATOR / SIMILARITY_DENOMINATOR` of the longer line's
/// tokens or it is treated as two unrelated edits and skipped.
const SIMILARITY_NUMERATOR: usize = 1;
/// Denominator of the minimum LCS-match ratio. See [`SIMILARITY_NUMERATOR`].
const SIMILARITY_DENOMINATOR: usize = 2;

/// Byte ranges per row that mark changed spans inside a hunk.
pub type WordChanges = BTreeMap<RowId, Vec<Range<usize>>>;

/// A single token taken from one diff line.
#[derive(Clone, Debug, Eq, PartialEq)]
struct Token<'a> {
    /// Row this token came from.
    row: RowId,
    /// Byte range within the row's text.
    range: Range<usize>,
    /// Category used for similarity checks.
    class: Class,
    /// Token text (a slice of the row's text).
    text: &'a str,
}

/// One dynamic-programming cell for the token LCS.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct Cell {
    /// Length of the best LCS ending at this cell.
    len: u32,
    /// Whether that LCS contains at least one relevant token.
    is_relevant: bool,
}

/// Token category, used to decide where a token boundary falls.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Class {
    /// Run of `[A-Za-z0-9_]`.
    Ident,
    /// Run of `' '` or `'\t'`.
    Space,
    /// Any other character (one per token).
    Other,
}

impl Class {
    /// Classifies one character.
    fn of(ch: char) -> Self {
        if ch.is_ascii_alphanumeric() || ch == '_' {
            Self::Ident
        } else if ch == ' ' || ch == '\t' {
            Self::Space
        } else {
            Self::Other
        }
    }

    /// Returns whether this class can anchor a meaningful word-diff pair.
    fn is_relevant(self) -> bool {
        matches!(self, Self::Ident)
    }
}

/// Iterator over tokens in one diff line's text.
struct Tokens<'a> {
    /// Row identifier carried into each yielded token.
    row: RowId,
    /// Full line text being tokenized.
    text: &'a str,
    /// Byte cursor into the line text.
    cursor: usize,
}

impl<'a> Iterator for Tokens<'a> {
    type Item = Token<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let rest = self.text.get(self.cursor..)?;
        let mut chars = rest.char_indices();
        let (_, first) = chars.next()?;
        let class = Class::of(first);
        let end_local = if matches!(class, Class::Ident | Class::Space) {
            chars
                .find(|(_, ch)| Class::of(*ch) != class)
                .map_or(rest.len(), |(i, _)| i)
        } else {
            first.len_utf8()
        };
        let start = self.cursor;
        let end = self.cursor + end_local;
        self.cursor = end;

        Some(Token {
            row: self.row,
            range: start..end,
            class,
            text: &self.text[start..end],
        })
    }
}

impl Tokens<'_> {
    /// Returns an iterator over tokens in one diff line.
    fn new(line: &DiffLine) -> Tokens<'_> {
        Tokens {
            row: line.id,
            text: line.text.as_str(),
            cursor: 0,
        }
    }
}

/// Returns the per-row changed byte ranges for one hunk.
pub fn compute(hunk: &Hunk) -> WordChanges {
    let mut changes = WordChanges::new();
    let mut dels: Vec<&DiffLine> = Vec::new();
    let mut adds: Vec<&DiffLine> = Vec::new();
    for line in &hunk.lines {
        match line.kind {
            DiffLineKind::Deletion => dels.push(line),
            DiffLineKind::Addition => adds.push(line),
            DiffLineKind::Context => {
                flush_block(&mut dels, &mut adds, &mut changes);
            }
            DiffLineKind::NoNewline => {}
        }
    }
    flush_block(&mut dels, &mut adds, &mut changes);

    // The LCS walks back-to-front, so per-row ranges arrive in reverse order;
    // sort and collapse adjacent ranges into clean spans.
    for ranges in changes.values_mut() {
        ranges.sort_by_key(|range| range.start);
        ranges.dedup_by(|next, prev| {
            if prev.end >= next.start {
                prev.end = prev.end.max(next.end);
                true
            } else {
                false
            }
        });
    }
    changes
}

/// Pairs up the deletions and additions in one change block and emits ranges
/// for each pair that passes the similarity gate. Clears both buffers so the
/// next block starts fresh.
fn flush_block(dels: &mut Vec<&DiffLine>, adds: &mut Vec<&DiffLine>, changes: &mut WordChanges) {
    let pairs = dels.len().min(adds.len());
    for i in 0..pairs {
        lcs(dels[i], adds[i], changes);
    }
    dels.clear();
    adds.clear();
}

/// Runs an LCS between one deletion and one addition line. If the pair shares
/// enough tokens to look like two edits of the same line, the differing byte
/// ranges on each side are pushed into `changes`. Otherwise the pair is
/// treated as unrelated and skipped.
fn lcs(del: &DiffLine, add: &DiffLine, changes: &mut WordChanges) {
    let old: Vec<Token<'_>> = Tokens::new(del).collect();
    let new: Vec<Token<'_>> = Tokens::new(add).collect();
    if old.is_empty() || new.is_empty() {
        return;
    }
    if non_space_tokens_equal(&old, &new) {
        return;
    }

    // Build the standard LCS length table over token texts.
    let rows = old.len() + 1;
    let cols = new.len() + 1;
    let mut table = vec![vec![Cell::default(); cols]; rows];
    for i in 1..rows {
        for j in 1..cols {
            let prev = table[i - 1][j - 1];
            let top = table[i - 1][j];
            let left = table[i][j - 1];
            table[i][j] = if old[i - 1].text == new[j - 1].text {
                Cell {
                    len: prev.len + 1,
                    is_relevant: prev.is_relevant || old[i - 1].class.is_relevant(),
                }
            } else if top.len >= left.len {
                top
            } else {
                left
            };
        }
    }

    // Similarity gate: the LCS length must cover at least the configured
    // fraction of the longer line, or the lines are too different to usefully
    // word-diff against each other.
    let common = table[old.len()][new.len()];
    let max_len = old.len().max(new.len());
    if common.len as usize * SIMILARITY_DENOMINATOR < max_len * SIMILARITY_NUMERATOR
        || !common.is_relevant
    {
        return;
    }

    // Walk the table backwards from the bottom-right corner. Each step that
    // advances along only one axis is an old-only or new-only token, whose
    // byte range we record under its source row.
    let mut i = old.len();
    let mut j = new.len();
    while i > 0 && j > 0 {
        if old[i - 1].text == new[j - 1].text {
            i -= 1;
            j -= 1;
        } else if table[i - 1][j].len >= table[i][j - 1].len {
            i -= 1;
            push_changed_token(&old, i, changes);
        } else {
            j -= 1;
            push_changed_token(&new, j, changes);
        }
    }
    while i > 0 {
        i -= 1;
        push_changed_token(&old, i, changes);
    }
    while j > 0 {
        j -= 1;
        push_changed_token(&new, j, changes);
    }
}

/// Returns whether the edit only changes spacing between existing tokens.
fn non_space_tokens_equal(old: &[Token<'_>], new: &[Token<'_>]) -> bool {
    old.iter()
        .filter(|token| token.class != Class::Space)
        .map(|token| (token.class, token.text))
        .eq(new
            .iter()
            .filter(|token| token.class != Class::Space)
            .map(|token| (token.class, token.text)))
}

/// Pushes one changed token range, omitting ordinary spacing edits.
fn push_changed_token(tokens: &[Token<'_>], index: usize, changes: &mut WordChanges) {
    let token = &tokens[index];
    if token.class == Class::Space {
        return;
    }

    let ranges = changes.entry(token.row).or_default();
    if let Some(space) = tokens.get(index + 1)
        && let Some(next) = tokens.get(index + 2)
        && space.class == Class::Space
        && next.class != Class::Space
        && token.row == next.row
        && ranges.iter().any(|range| range == &next.range)
    {
        ranges.push(token.range.end..next.range.start);
    }
    ranges.push(token.range.clone());
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::{Decode, DiffDocument};

    fn parse(input: &str) -> DiffDocument {
        DiffDocument::decode_str(input).unwrap()
    }

    fn tokens(line: &DiffLine) -> Vec<&str> {
        Tokens::new(line).map(|t| t.text).collect()
    }

    #[test]
    fn tokenizer_splits_idents_whitespace_and_punctuation() {
        let line = DiffLine {
            id: RowId::new(0),
            kind: DiffLineKind::Context,
            text: "foo bar+baz".to_owned(),
        };
        assert_eq!(tokens(&line), vec!["foo", " ", "bar", "+", "baz"]);
    }

    #[test]
    fn tokenizer_records_byte_ranges() {
        let line = DiffLine {
            id: RowId::new(0),
            kind: DiffLineKind::Context,
            text: "ab cd".to_owned(),
        };
        let collected: Vec<_> = Tokens::new(&line).collect();
        assert_eq!(collected[0].range, 0..2);
        assert_eq!(collected[1].range, 2..3);
        assert_eq!(collected[2].range, 3..5);
    }

    #[test]
    fn similar_lines_get_word_diff() {
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1 +1 @@
-fn render(view: &View) {
+fn render(view: &mut View, opts: Options) {
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        let new_row = hunk
            .lines
            .iter()
            .find(|l| l.kind == DiffLineKind::Addition)
            .unwrap();
        let new_ranges = changes.get(&new_row.id).cloned().unwrap_or_default();
        assert!(!new_ranges.is_empty(), "expected new-side changed ranges");
        let new_text = new_row.text.as_str();
        let highlighted: String = new_ranges
            .iter()
            .map(|r| &new_text[r.clone()])
            .collect::<Vec<_>>()
            .join("|");
        assert!(highlighted.contains("mut"), "got {highlighted:?}");
        assert!(highlighted.contains("opts"), "got {highlighted:?}");
        assert!(highlighted.contains("Options"), "got {highlighted:?}");
    }

    #[test]
    fn spacing_changes_are_suppressed_except_word_splits() {
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1 +1 @@
-let result = foo + bar;
+let  result = foo+bar;
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        assert!(
            changes.is_empty(),
            "spacing-only edits should not produce a word-diff overlay, got {changes:?}"
        );

        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1 +1 @@
-let word = foobar;
+let word = foo bar;
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        let new_row = hunk
            .lines
            .iter()
            .find(|l| l.kind == DiffLineKind::Addition)
            .unwrap();
        let new_ranges = changes.get(&new_row.id).cloned().unwrap_or_default();
        let highlighted: String = new_ranges
            .iter()
            .map(|r| &new_row.text[r.clone()])
            .collect();
        assert_eq!(highlighted, "foo bar");

        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1 +1 @@
-let msg = old name;
+let msg = new value;
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        let new_row = hunk
            .lines
            .iter()
            .find(|l| l.kind == DiffLineKind::Addition)
            .unwrap();
        let new_ranges = changes.get(&new_row.id).cloned().unwrap_or_default();
        let highlighted: String = new_ranges
            .iter()
            .map(|r| &new_row.text[r.clone()])
            .collect();
        assert_eq!(highlighted, "new value");
    }

    #[test]
    fn dissimilar_lines_are_suppressed() {
        // The deletion and addition share only a few common tokens (mostly
        // spaces and punctuation). Highlighting individual tokens here would
        // just be noise — the dim row tint already conveys the change.
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1 +1 @@
-x = something_complex();
+result.set(other_thing);
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        assert!(
            changes.is_empty(),
            "dissimilar lines should not produce a word-diff overlay, got {changes:?}"
        );
    }

    #[test]
    fn separator_only_matches_are_suppressed() {
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1 +1 @@
-old + stale + gone
+new + fresh + kept
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        assert!(
            changes.is_empty(),
            "lines that share only separators should not produce word-diff overlay"
        );
    }

    #[test]
    fn identical_lines_produce_no_changes() {
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1,2 +1,2 @@
-same
+same
 context
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        assert!(changes.values().all(Vec::is_empty) || changes.is_empty());
    }

    #[test]
    fn pure_context_hunk_produces_no_changes() {
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1,2 +1,2 @@
 one
 two
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        assert!(changes.is_empty() || changes.values().all(Vec::is_empty));
    }

    #[test]
    fn pure_addition_hunk_produces_no_overlay() {
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1,2 +1,4 @@
 fn main() {
+    let foo = 42;
+    let bar = 43;
 }
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        assert!(changes.is_empty(), "got {changes:?}");
    }

    #[test]
    fn pure_deletion_hunk_produces_no_overlay() {
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1,4 +1,2 @@
 fn main() {
-    let foo = 42;
-    let bar = 43;
 }
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        assert!(changes.is_empty());
    }

    #[test]
    fn changed_ranges_per_row_are_merged_and_sorted() {
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1 +1 @@
-a b c d e
+a x y z e
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        for ranges in changes.values() {
            for pair in ranges.windows(2) {
                assert!(
                    pair[0].end <= pair[1].start,
                    "ranges not disjoint: {pair:?}"
                );
            }
        }
    }

    #[test]
    fn pairing_is_one_to_one_within_a_change_block() {
        // alpha/alpha pair is identical → no overlay.
        // beta/gamma pair is dissimilar (no common tokens) → suppressed.
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1,3 +1,3 @@
-alpha
-beta
+alpha
+gamma
 tail
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        assert!(changes.is_empty(), "got {changes:?}");
    }

    #[test]
    fn unpaired_lines_in_a_block_get_no_overlay() {
        // Three deletions, one addition: only the first pair is considered;
        // the extra deletions stay un-highlighted.
        let doc = parse(
            "\
diff --git a/a.rs b/a.rs
@@ -1,3 +1,1 @@
-fn alpha() {}
-fn beta() {}
-fn gamma() {}
+fn alpha() {}
",
        );
        let hunk = &doc.files[0].hunks[0];
        let changes = compute(hunk);
        let beta = hunk
            .lines
            .iter()
            .find(|l| l.kind == DiffLineKind::Deletion && l.text.contains("beta"))
            .unwrap();
        let gamma = hunk
            .lines
            .iter()
            .find(|l| l.kind == DiffLineKind::Deletion && l.text.contains("gamma"))
            .unwrap();
        assert!(changes.get(&beta.id).is_none_or(Vec::is_empty));
        assert!(changes.get(&gamma.id).is_none_or(Vec::is_empty));
    }
}