diffler-core 0.17.0

Core review engine for diffler: diffs, sessions, comments, viewed marks
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Diff model: what changed, organized as files -> hunks -> lines.

use std::ops::Range;

use serde::{Deserialize, Serialize};

/// FNV-1a 64 as lowercase hex. Content hashes key persisted viewed marks and
/// derived caches, so the algorithm is pinned forever (tested below).
fn stable_hash(bytes: &[u8]) -> String {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in bytes {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x0100_0000_01b3);
    }
    format!("{hash:016x}")
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DiffModel {
    pub files: Vec<FileDiff>,
}

impl DiffModel {
    /// Cheap content identity of the whole model (file paths + per-file
    /// sides hashes), so callers can skip invalidating derived state when
    /// a refresh recomputed an identical diff.
    pub fn fingerprint(&self) -> String {
        let mut buf = Vec::new();
        for file in &self.files {
            buf.extend_from_slice(file.path.as_bytes());
            buf.push(0);
            buf.extend_from_slice(file.sides_hash().as_bytes());
            buf.push(b'\n');
        }
        stable_hash(&buf)
    }

    /// The diff line carrying number `line` on the requested side of
    /// `file`'s hunks, if it is part of the diff.
    pub fn find_line(&self, file: &str, line: u32, on_old_side: bool) -> Option<&DiffLine> {
        let file = self.files.iter().find(|f| f.path == file)?;
        file.hunks.iter().flat_map(|h| &h.lines).find(|l| {
            let no = if on_old_side { l.old_no } else { l.new_no };
            no == Some(line)
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileDiff {
    pub path: String,
    pub old_path: Option<String>,
    pub status: FileStatus,
    pub binary: bool,
    /// Full contents of each side, used for whole-file syntax highlighting.
    /// `None` for binary files and for the missing side of adds/deletes.
    pub old_text: Option<String>,
    pub new_text: Option<String>,
    pub hunks: Vec<Hunk>,
    /// Lazily memoized content hashes; texts never change after construction.
    pub hashes: HashCache,
    /// Each side's git blob, for a binary file the pane reads bytes from (an
    /// image preview).
    pub blobs: BlobIds,
}

/// The git blob ids of a file's two sides, hex-encoded, `None` for a side
/// that does not exist (an add, a delete). A working-tree side's id is only
/// a hash of the file on disk, with no object behind it in the store.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BlobIds {
    pub old: Option<String>,
    pub new: Option<String>,
}

/// Memo slots for [`FileDiff::content_hash`]/[`FileDiff::sides_hash`], which
/// the UI probes every frame: hashing full file contents per frame is the
/// cost this avoids. Compares equal always so `FileDiff` equality is on data.
#[derive(Debug, Clone, Default)]
pub struct HashCache {
    content: std::sync::OnceLock<String>,
    sides: std::sync::OnceLock<String>,
}

impl PartialEq for HashCache {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

impl Eq for HashCache {}

impl FileDiff {
    /// Content identity of the new side, used for viewed-mark invalidation.
    /// A binary file has no text, so its new side's git blob id stands in.
    pub fn content_hash(&self) -> String {
        self.hashes
            .content
            .get_or_init(|| match (&self.new_text, &self.blobs.new) {
                (None, Some(blob)) => blob.clone(),
                (text, _) => stable_hash(text.as_deref().unwrap_or("").as_bytes()),
            })
            .clone()
    }

    /// `(added, deleted)` line counts across the file's hunks.
    pub fn diffstat(&self) -> (usize, usize) {
        let mut added = 0;
        let mut deleted = 0;
        for line in self.hunks.iter().flat_map(|h| &h.lines) {
            match line.kind {
                LineKind::Added => added += 1,
                LineKind::Deleted => deleted += 1,
                LineKind::Context => {}
            }
        }
        (added, deleted)
    }

    /// Content identity of both sides, for caches derived from old and new
    /// text (e.g. syntax highlighting). Viewed marks key on `content_hash`
    /// instead: they only care about the side the reviewer reads.
    pub fn sides_hash(&self) -> String {
        self.hashes
            .sides
            .get_or_init(|| {
                let mut bytes = Vec::from(self.old_text.as_deref().unwrap_or("").as_bytes());
                bytes.push(0);
                bytes.extend_from_slice(self.new_text.as_deref().unwrap_or("").as_bytes());
                // a binary file carries no text, so its blob ids are its identity
                for blob in [&self.blobs.old, &self.blobs.new] {
                    bytes.push(0);
                    bytes.extend_from_slice(blob.as_deref().unwrap_or("").as_bytes());
                }
                stable_hash(&bytes)
            })
            .clone()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FileStatus {
    Added,
    Modified,
    Deleted,
    Renamed,
    Untracked,
    /// A walkthrough's own file: one a stop or note anchors outside the diff,
    /// shown at its current content with nothing to compare it against.
    Unchanged,
}

impl FileStatus {
    /// Single-character shape naming the status in the diff sidebar. It reads
    /// by form alone, so a palette whose hues a reader cannot separate still
    /// carries the status; colour reinforces it.
    pub const fn glyph(self) -> char {
        match self {
            Self::Added => '+',
            Self::Modified => '●',
            Self::Deleted => '−',
            Self::Renamed => '~',
            Self::Untracked => '○',
            Self::Unchanged => '·',
        }
    }

    /// Neogit-style row label shown in file headers and the diff pane.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Added => "new file",
            Self::Modified => "modified",
            Self::Deleted => "deleted",
            Self::Renamed => "renamed",
            Self::Untracked => "untracked",
            Self::Unchanged => "unchanged",
        }
    }
}

/// Stable identity for a hunk: hash of its normalized content. Survives
/// edits elsewhere in the file; changes when the hunk's lines change.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HunkId(pub String);

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hunk {
    pub id: HunkId,
    pub old_start: u32,
    pub old_lines: u32,
    pub new_start: u32,
    pub new_lines: u32,
    /// git's section heading: the enclosing function/section name git emits
    /// after the second `@@` of the hunk header. Empty when git gives none
    /// (e.g. a top-of-file hunk). Excluded from `id`, which keys only on lines.
    pub context: String,
    pub lines: Vec<DiffLine>,
}

impl Hunk {
    pub fn header(&self) -> String {
        format!(
            "@@ -{},{} +{},{} @@",
            self.old_start, self.old_lines, self.new_start, self.new_lines
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LineKind {
    Context,
    Deleted,
    Added,
}

impl LineKind {
    /// Unified-diff origin character (' ', '-', '+').
    pub const fn origin(self) -> char {
        match self {
            Self::Context => ' ',
            Self::Deleted => '-',
            Self::Added => '+',
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiffLine {
    pub kind: LineKind,
    pub old_no: Option<u32>,
    pub new_no: Option<u32>,
    /// Line content without the trailing newline.
    pub text: String,
    /// Byte ranges within `text` to emphasize (intra-line changes).
    pub emphasis: Vec<Range<usize>>,
    /// True on a paired deleted/added line the structural algorithm found to
    /// be a pure reformat (identical token structure, e.g. reindentation):
    /// the renderer dims it, leaving red/green for an actual change.
    pub reformat_only: bool,
}

impl DiffLine {
    pub fn new(kind: LineKind, old_no: Option<u32>, new_no: Option<u32>, text: String) -> Self {
        Self {
            kind,
            old_no,
            new_no,
            text,
            emphasis: Vec::new(),
            reformat_only: false,
        }
    }

    /// The line number on the named side: `old_no` on the old side (where a
    /// deletion lives), `new_no` everywhere else.
    pub const fn number_on(&self, old_side: bool) -> Option<u32> {
        if old_side { self.old_no } else { self.new_no }
    }
}

/// Hash the hunk's content (kinds + text) into a stable id. `occurrence` is
/// how many earlier hunks in the same file hash to the same content: two
/// hunks with byte-identical lines in one file get distinct ids this way,
/// while every other hunk's id depends on its own content alone, so it
/// survives edits elsewhere in the file. [`disambiguated_hunk_id`] is the
/// usual way to call this, since it tracks the count for the caller.
pub fn hunk_id(file_path: &str, lines: &[DiffLine], occurrence: usize) -> HunkId {
    let mut buf = String::new();
    buf.push_str(file_path);
    buf.push('\n');
    for line in lines {
        let tag = match line.kind {
            LineKind::Context => ' ',
            LineKind::Deleted => '-',
            LineKind::Added => '+',
        };
        buf.push(tag);
        buf.push_str(&line.text);
        buf.push('\n');
    }
    if occurrence > 0 {
        buf.push_str(&occurrence.to_string());
        buf.push('\n');
    }
    HunkId(stable_hash(buf.as_bytes()))
}

/// [`hunk_id`] for one hunk of a file whose other hunks are being assigned
/// ids through the same `seen` map: each distinct content gets occurrence 0
/// the first time and counts up from there, so two identical hunks in one
/// file never collide.
// every caller shares one default-hashed map for one file's hunks, so a
// generic hasher buys nothing
#[allow(clippy::implicit_hasher)]
pub fn disambiguated_hunk_id(
    file_path: &str,
    lines: &[DiffLine],
    seen: &mut std::collections::HashMap<HunkId, usize>,
) -> HunkId {
    let base = hunk_id(file_path, lines, 0);
    let occurrence = seen.entry(base).or_insert(0);
    let id = hunk_id(file_path, lines, *occurrence);
    *occurrence += 1;
    id
}

#[cfg(test)]
mod tests {
    use super::*;

    // hashes key persisted viewed marks: the algorithm must stay stable
    // across releases, so pin known FNV-1a 64 values
    #[test]
    fn stable_hash_is_fnv1a64_and_never_changes() {
        assert_eq!(stable_hash(b""), "cbf29ce484222325");
        assert_eq!(stable_hash(b"hello"), "a430d84680aabd0b");
    }

    #[test]
    fn file_status_glyph_and_label_cover_all_variants() {
        let glyphs = [
            FileStatus::Added,
            FileStatus::Modified,
            FileStatus::Deleted,
            FileStatus::Renamed,
            FileStatus::Untracked,
            FileStatus::Unchanged,
        ]
        .map(FileStatus::glyph);
        assert_eq!(glyphs, ['+', '●', '−', '~', '○', '·']);
        let mut distinct = glyphs.to_vec();
        distinct.sort_unstable();
        distinct.dedup();
        assert_eq!(
            distinct.len(),
            glyphs.len(),
            "no two statuses share a shape"
        );

        assert_eq!(FileStatus::Added.label(), "new file");
        assert_eq!(FileStatus::Modified.label(), "modified");
        assert_eq!(FileStatus::Deleted.label(), "deleted");
        assert_eq!(FileStatus::Renamed.label(), "renamed");
        assert_eq!(FileStatus::Untracked.label(), "untracked");
        assert_eq!(FileStatus::Unchanged.label(), "unchanged");
    }

    fn line(kind: LineKind, text: &str) -> DiffLine {
        DiffLine::new(kind, None, None, text.to_owned())
    }

    #[test]
    fn hunk_id_is_stable() {
        let lines = vec![line(LineKind::Deleted, "a"), line(LineKind::Added, "b")];
        let id1 = hunk_id("src/x.rs", &lines, 0);
        let id2 = hunk_id("src/x.rs", &lines, 0);
        assert_eq!(id1, id2);
    }

    #[test]
    fn hunk_id_changes_with_content() {
        let a = vec![line(LineKind::Added, "x")];
        let b = vec![line(LineKind::Added, "y")];
        assert_ne!(hunk_id("f", &a, 0), hunk_id("f", &b, 0));
    }

    #[test]
    fn hunk_id_changes_with_kind() {
        let a = vec![line(LineKind::Added, "x")];
        let b = vec![line(LineKind::Deleted, "x")];
        assert_ne!(hunk_id("f", &a, 0), hunk_id("f", &b, 0));
    }

    #[test]
    fn hunk_id_changes_with_file() {
        let lines = vec![line(LineKind::Added, "x")];
        assert_ne!(hunk_id("a", &lines, 0), hunk_id("b", &lines, 0));
    }

    #[test]
    fn hunk_id_changes_with_occurrence() {
        let lines = vec![line(LineKind::Added, "x")];
        assert_ne!(hunk_id("f", &lines, 0), hunk_id("f", &lines, 1));
    }

    #[test]
    fn disambiguated_hunk_id_gives_identical_hunks_distinct_ids() {
        let lines = vec![line(LineKind::Added, "x")];
        let mut seen = std::collections::HashMap::new();
        let first = disambiguated_hunk_id("f", &lines, &mut seen);
        let second = disambiguated_hunk_id("f", &lines, &mut seen);
        assert_ne!(first, second);
        assert_eq!(first, hunk_id("f", &lines, 0));
        assert_eq!(second, hunk_id("f", &lines, 1));
    }

    #[test]
    fn header_formats() {
        let hunk = Hunk {
            id: HunkId("h".into()),
            old_start: 10,
            old_lines: 7,
            new_start: 10,
            new_lines: 9,
            context: String::new(),
            lines: vec![],
        };
        assert_eq!(hunk.header(), "@@ -10,7 +10,9 @@");
    }

    #[test]
    fn content_hash_changes_when_new_text_changes() {
        let base = FileDiff {
            path: "f.rs".into(),
            old_path: None,
            status: FileStatus::Modified,
            binary: false,
            old_text: None,
            new_text: Some("fn main() {}".into()),
            hunks: vec![],
            hashes: HashCache::default(),
            blobs: BlobIds::default(),
        };
        let mut changed = base.clone();
        changed.new_text = Some("fn main() { let x = 1; }".into());
        assert_ne!(base.content_hash(), changed.content_hash());
    }

    #[test]
    fn content_hash_is_stable() {
        let file = FileDiff {
            path: "f.rs".into(),
            old_path: None,
            status: FileStatus::Modified,
            binary: false,
            old_text: None,
            new_text: Some("same content".into()),
            hunks: vec![],
            hashes: HashCache::default(),
            blobs: BlobIds::default(),
        };
        assert_eq!(file.content_hash(), file.content_hash());
    }

    #[test]
    fn sides_hash_changes_when_old_text_changes() {
        let base = FileDiff {
            path: "f.rs".into(),
            old_path: None,
            status: FileStatus::Modified,
            binary: false,
            old_text: Some("fn main() {}".into()),
            new_text: Some("fn main() { let x = 1; }".into()),
            hunks: vec![],
            hashes: HashCache::default(),
            blobs: BlobIds::default(),
        };
        let mut changed = base.clone();
        changed.old_text = Some("fn main() { unreachable!() }".into());
        assert_eq!(
            base.content_hash(),
            changed.content_hash(),
            "same new side, same content hash"
        );
        assert_ne!(base.sides_hash(), changed.sides_hash());
    }

    fn one_file_model(path: &str, old_text: &str, new_text: &str) -> DiffModel {
        DiffModel {
            files: vec![FileDiff {
                path: path.to_owned(),
                old_path: None,
                status: FileStatus::Modified,
                binary: false,
                old_text: Some(old_text.to_owned()),
                new_text: Some(new_text.to_owned()),
                hunks: vec![],
                hashes: HashCache::default(),
                blobs: BlobIds::default(),
            }],
        }
    }

    #[test]
    fn fingerprint_is_stable_for_identical_models() {
        let a = one_file_model("f.rs", "old", "new");
        let b = one_file_model("f.rs", "old", "new");
        assert_eq!(a.fingerprint(), b.fingerprint());
    }

    #[test]
    fn fingerprint_changes_with_content_path_and_file_set() {
        let base = one_file_model("f.rs", "old", "new");
        assert_ne!(
            base.fingerprint(),
            one_file_model("f.rs", "old", "newer").fingerprint(),
            "changed side changes the fingerprint"
        );
        assert_ne!(
            base.fingerprint(),
            one_file_model("g.rs", "old", "new").fingerprint(),
            "renamed file changes the fingerprint"
        );
        let mut grown = base.clone();
        grown.files.extend(one_file_model("g.rs", "", "x").files);
        assert_ne!(
            base.fingerprint(),
            grown.fingerprint(),
            "added file changes the fingerprint"
        );
    }

    fn model_with_lines() -> DiffModel {
        DiffModel {
            files: vec![FileDiff {
                path: "f.rs".into(),
                old_path: None,
                status: FileStatus::Modified,
                binary: false,
                old_text: None,
                new_text: None,
                hunks: vec![Hunk {
                    id: HunkId("h".into()),
                    old_start: 1,
                    old_lines: 2,
                    new_start: 1,
                    new_lines: 2,
                    context: String::new(),
                    lines: vec![
                        DiffLine::new(LineKind::Context, Some(1), Some(1), "one".into()),
                        DiffLine::new(LineKind::Deleted, Some(2), None, "two".into()),
                        DiffLine::new(LineKind::Added, None, Some(2), "TWO".into()),
                    ],
                }],
                hashes: HashCache::default(),
                blobs: BlobIds::default(),
            }],
        }
    }

    #[test]
    fn diffstat_counts_added_and_deleted_over_hunks() {
        // model_with_lines: one context, one deleted, one added line
        let model = model_with_lines();
        assert_eq!(model.files[0].diffstat(), (1, 1));

        // two hunks: 2 added + 1 deleted total, context ignored
        let file = FileDiff {
            path: "f.rs".into(),
            old_path: None,
            status: FileStatus::Modified,
            binary: false,
            old_text: None,
            new_text: None,
            hunks: vec![
                Hunk {
                    id: HunkId("a".into()),
                    old_start: 1,
                    old_lines: 1,
                    new_start: 1,
                    new_lines: 2,
                    context: String::new(),
                    lines: vec![
                        DiffLine::new(LineKind::Context, Some(1), Some(1), "ctx".into()),
                        DiffLine::new(LineKind::Added, None, Some(2), "add one".into()),
                    ],
                },
                Hunk {
                    id: HunkId("b".into()),
                    old_start: 5,
                    old_lines: 1,
                    new_start: 6,
                    new_lines: 1,
                    context: String::new(),
                    lines: vec![
                        DiffLine::new(LineKind::Deleted, Some(5), None, "gone".into()),
                        DiffLine::new(LineKind::Added, None, Some(6), "add two".into()),
                    ],
                },
            ],
            hashes: HashCache::default(),
            blobs: BlobIds::default(),
        };
        assert_eq!(file.diffstat(), (2, 1));
    }

    #[test]
    fn find_line_matches_the_requested_side() {
        let model = model_with_lines();
        let new_side = model.find_line("f.rs", 2, false).expect("new side");
        assert_eq!(new_side.text, "TWO");
        let old_side = model.find_line("f.rs", 2, true).expect("old side");
        assert_eq!(old_side.text, "two");
    }

    #[test]
    fn find_line_misses_unknown_files_and_lines() {
        let model = model_with_lines();
        assert!(model.find_line("nope.rs", 1, false).is_none());
        assert!(model.find_line("f.rs", 99, false).is_none());
    }

    #[test]
    fn content_hash_falls_back_for_none() {
        let file = FileDiff {
            path: "f.rs".into(),
            old_path: None,
            status: FileStatus::Deleted,
            binary: false,
            old_text: None,
            new_text: None,
            hunks: vec![],
            hashes: HashCache::default(),
            blobs: BlobIds::default(),
        };
        // must not panic, must return a non-empty string (git hash of empty blob)
        let hash = file.content_hash();
        assert!(!hash.is_empty());
    }
}