rustik-diff 0.2.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
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! Unified diff document model.
//!
//! Defines the data tree (`DiffDocument` → `FileDiff` → `Hunk` → `DiffLine`)
//! that callers consume. The decoder that produces these values lives in
//! [`crate::decode`]; `document` is intentionally model-only.

use std::fmt;
use std::io;
use std::num::ParseIntError;
use std::path::PathBuf;
use std::str::FromStr;

/// Stable identifier for a file section in one diff document.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct FileId(usize);

/// Stable identifier for a hunk in one diff document.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct HunkId(usize);

/// Stable identifier for a rendered hunk row in one diff document.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RowId(usize);

/// Object identifier as it appears in a Git diff header.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Oid(String);

impl FileId {
    /// Wraps a raw index as a [`FileId`].
    pub const fn new(index: usize) -> Self {
        Self(index)
    }
}

impl HunkId {
    /// Wraps a raw index as a [`HunkId`].
    pub const fn new(index: usize) -> Self {
        Self(index)
    }
}

impl RowId {
    /// Wraps a raw index as a [`RowId`].
    pub const fn new(index: usize) -> Self {
        Self(index)
    }
}

impl Oid {
    /// Returns the object identifier text.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for Oid {
    type Err = OidError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        if input.is_empty() {
            return Err(OidError);
        }
        if !input.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return Err(OidError);
        }
        Ok(Self(input.to_owned()))
    }
}

impl fmt::Display for Oid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Error returned when a diff object identifier is malformed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OidError;

impl fmt::Display for OidError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("object id must be non-empty hexadecimal text")
    }
}

impl std::error::Error for OidError {}

impl std::ops::Deref for FileId {
    type Target = usize;

    fn deref(&self) -> &usize {
        &self.0
    }
}

impl std::ops::Deref for HunkId {
    type Target = usize;

    fn deref(&self) -> &usize {
        &self.0
    }
}

impl std::ops::Deref for RowId {
    type Target = usize;

    fn deref(&self) -> &usize {
        &self.0
    }
}

/// A complete unified diff document.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DiffDocument {
    /// Commit preamble before the first `diff --git` section, if present.
    pub commit: Option<crate::Commit>,
    /// File diffs in input order.
    pub files: Vec<FileDiff>,
}

/// A single file section in a unified diff.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FileDiff {
    /// Stable file identifier.
    pub id: FileId,
    /// Metadata and raw header lines for this file.
    pub header: FileHeader,
    /// Hunks in input order.
    pub hunks: Vec<Hunk>,
}

/// Metadata lines that introduce a file section in a Git patch.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FileHeader {
    /// Classified kind of file change.
    pub kind: FileKind,
    /// Path on the old side of the diff, when present.
    pub old_path: Option<PathBuf>,
    /// Path on the new side of the diff, when present.
    pub new_path: Option<PathBuf>,
    /// File mode on the old side of the diff, when present.
    pub old_mode: Option<FileMode>,
    /// File mode on the new side of the diff, when present.
    pub new_mode: Option<FileMode>,
    /// Object id on the old side of the diff, when present.
    pub old_oid: Option<Oid>,
    /// Object id on the new side of the diff, when present.
    pub new_oid: Option<Oid>,
    /// Raw header lines preserved for callers that need exact metadata.
    pub raw: Vec<String>,
}

/// File mode in a Git diff, parsed from the octal value Git records.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum FileMode {
    /// Regular file (`100644`).
    Blob,
    /// Executable regular file (`100755`).
    BlobExecutable,
    /// Symbolic link (`120000`).
    Link,
    /// Submodule reference, i.e. a Git commit (`160000`).
    Commit,
    /// Directory tree (`040000`).
    Tree,
    /// Any other mode, preserved as the original octal value.
    Other(u32),
}

/// Kind of file-level change described by a patch file header.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileKind {
    /// Existing file content changed.
    Modified,
    /// New file was added.
    Added,
    /// Existing file was deleted.
    Deleted,
    /// Existing file was renamed.
    Renamed,
    /// Existing file was copied.
    Copied,
    /// File mode changed without a more specific content kind.
    ModeChanged,
    /// File contains binary patch data or a binary comparison marker.
    Binary,
}

impl FileKind {
    /// Returns the compact marker used by diff chrome.
    pub const fn marker(self) -> char {
        match self {
            Self::Added => '⊕',
            Self::Deleted => '⊖',
            Self::Renamed => '↦',
            Self::Copied => '⇉',
            Self::Modified | Self::ModeChanged | Self::Binary => '⊙',
        }
    }
}

/// Aggregate statistics for one [`FileDiff`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct FileStats {
    /// Total addition lines across all hunks in the file.
    pub additions: usize,
    /// Total deletion lines across all hunks in the file.
    pub deletions: usize,
}

/// Aggregate statistics for one [`DiffDocument`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Stats {
    /// Number of file sections in the document.
    pub files_changed: usize,
    /// Total addition lines across all files.
    pub insertions: usize,
    /// Total deletion lines across all files.
    pub deletions: usize,
}

/// A unified diff hunk and its body lines.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Hunk {
    /// Stable hunk identifier.
    pub id: HunkId,
    /// Parsed hunk header.
    pub header: HunkHeader,
    /// Lines contained in the hunk body.
    pub lines: Vec<DiffLine>,
}

/// Metadata from a unified diff hunk header.
///
/// Example: `@@ -24,8 +24,6 @@ fn main`.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct HunkHeader {
    /// Starting line number on the old side of the diff.
    pub old_line_no: u32,
    /// Number of old-side lines covered by the hunk.
    pub old_size: u32,
    /// Starting line number on the new side of the diff.
    pub new_line_no: u32,
    /// Number of new-side lines covered by the hunk.
    pub new_size: u32,
    /// Optional trailing hunk context text.
    pub text: String,
}

/// A single line in a unified diff hunk.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DiffLine {
    /// Stable row identifier.
    pub id: RowId,
    /// Line role inside the hunk.
    pub kind: DiffLineKind,
    /// Line text without the leading diff marker.
    pub text: String,
}

/// Role of a line inside a unified diff hunk.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiffLineKind {
    /// Unchanged context line.
    Context,
    /// Added line.
    Addition,
    /// Deleted line.
    Deletion,
    /// Marker for a file without a trailing newline.
    NoNewline,
}

/// Error produced while decoding a unified diff.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DecodeError {
    /// One-based input line number where decoding failed.
    pub line: usize,
    /// Human-readable failure message.
    pub message: String,
    /// Whether this error represents a clean end-of-input signal.
    is_eof: bool,
}

impl DiffDocument {
    /// Returns whether the document contains no changed files.
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    /// Returns the totals of files changed, insertions, and deletions.
    pub fn stats(&self) -> Stats {
        let mut stats = Stats {
            files_changed: self.files.len(),
            ..Stats::default()
        };
        for file in &self.files {
            let file_stats = file.stats();
            stats.insertions += file_stats.additions;
            stats.deletions += file_stats.deletions;
        }
        stats
    }
}

impl FileHeader {
    /// Returns the path callers should usually show for this file.
    pub fn display_path(&self) -> Option<&PathBuf> {
        self.new_path.as_ref().or(self.old_path.as_ref())
    }
}

impl FileMode {
    /// Returns the octal mode value Git records on the wire.
    pub const fn as_octal(self) -> u32 {
        match self {
            Self::Blob => 0o100644,
            Self::BlobExecutable => 0o100755,
            Self::Link => 0o120000,
            Self::Commit => 0o160000,
            Self::Tree => 0o040000,
            Self::Other(value) => value,
        }
    }

    /// Builds a [`FileMode`] from an octal value, mapping known modes.
    pub const fn from_octal(value: u32) -> Self {
        match value {
            0o100644 => Self::Blob,
            0o100755 => Self::BlobExecutable,
            0o120000 => Self::Link,
            0o160000 => Self::Commit,
            0o040000 => Self::Tree,
            other => Self::Other(other),
        }
    }

    /// Parses an octal mode token from a Git diff header (e.g. `"100644"`).
    pub fn parse(input: &str) -> Option<Self> {
        u32::from_str_radix(input.trim(), 8)
            .ok()
            .map(Self::from_octal)
    }
}

impl fmt::Display for FileMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:o}", self.as_octal())
    }
}

impl DecodeError {
    /// Creates a decode error at a one-based line number.
    pub fn new(line: usize, message: impl Into<String>) -> Self {
        Self {
            line,
            message: message.into(),
            is_eof: false,
        }
    }

    /// Creates an end-of-input error used to signal a clean EOF to streaming
    /// callers. [`crate::Decode::try_decode`] turns this into `Ok(None)`.
    pub fn eof() -> Self {
        Self {
            line: 0,
            message: "unexpected end of file".to_owned(),
            is_eof: true,
        }
    }

    /// Returns whether this error represents end of input rather than a
    /// malformed patch.
    pub fn is_eof(&self) -> bool {
        self.is_eof
    }

    /// Returns a copy of this error with a line number when the error has none.
    pub(crate) fn at_line(mut self, line: usize) -> Self {
        if self.line == 0 {
            self.line = line;
        }
        self
    }
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.line == 0 {
            f.write_str(&self.message)
        } else {
            write!(f, "line {}: {}", self.line, self.message)
        }
    }
}

impl std::error::Error for DecodeError {}

impl From<ParseIntError> for DecodeError {
    fn from(error: ParseIntError) -> Self {
        Self::new(0, error.to_string())
    }
}

impl From<io::Error> for DecodeError {
    fn from(error: io::Error) -> Self {
        Self {
            line: 0,
            message: error.to_string(),
            is_eof: error.kind() == io::ErrorKind::UnexpectedEof,
        }
    }
}

impl fmt::Display for FileKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::Modified => "modified",
            Self::Added => "added",
            Self::Deleted => "deleted",
            Self::Renamed => "renamed",
            Self::Copied => "copied",
            Self::ModeChanged => "mode changed",
            Self::Binary => "binary",
        };
        f.write_str(name)
    }
}

impl DiffLineKind {
    /// Returns how many old-side lines this kind contributes to a hunk.
    pub const fn old_len(self) -> u32 {
        match self {
            Self::Context | Self::Deletion => 1,
            Self::Addition | Self::NoNewline => 0,
        }
    }

    /// Returns how many new-side lines this kind contributes to a hunk.
    pub const fn new_len(self) -> u32 {
        match self {
            Self::Context | Self::Addition => 1,
            Self::Deletion | Self::NoNewline => 0,
        }
    }
}

impl HunkHeader {
    /// Returns a copy with old and new line numbers shifted by the deltas.
    pub fn shifted(&self, old_delta: i32, new_delta: i32) -> Self {
        Self {
            old_line_no: Self::add_delta(self.old_line_no, old_delta),
            new_line_no: Self::add_delta(self.new_line_no, new_delta),
            ..self.clone()
        }
    }

    /// Adds a signed delta to an unsigned line number with saturation.
    fn add_delta(line: u32, delta: i32) -> u32 {
        if delta.is_negative() {
            line.saturating_sub(delta.unsigned_abs())
        } else {
            line.saturating_add(delta.unsigned_abs())
        }
    }
}

impl Hunk {
    /// Returns the number of old-side lines covered by the hunk body.
    pub fn old_size(&self) -> u32 {
        self.sizes().old
    }

    /// Returns the number of new-side lines covered by the hunk body.
    pub fn new_size(&self) -> u32 {
        self.sizes().new
    }

    /// Counts addition and deletion lines in this hunk.
    pub fn stats(&self) -> FileStats {
        let mut stats = FileStats::default();
        for line in &self.lines {
            match line.kind {
                DiffLineKind::Addition => stats.additions += 1,
                DiffLineKind::Deletion => stats.deletions += 1,
                DiffLineKind::Context | DiffLineKind::NoNewline => {}
            }
        }
        stats
    }

    /// Returns the net line offset introduced by applying this hunk.
    pub fn delta(&self) -> i32 {
        let sizes = self.sizes();
        let new_size = i32::try_from(sizes.new).unwrap_or(i32::MAX);
        let old_size = i32::try_from(sizes.old).unwrap_or(i32::MAX);
        new_size - old_size
    }

    /// Splits this hunk into context-separated change groups, each with its
    /// own recomputed header. Returns `None` when the hunk has fewer than two
    /// change groups (nothing to split).
    pub fn split(&self) -> Option<impl Iterator<Item = Self> + '_> {
        let groups = self.change_groups();
        if groups.len() < 2 {
            return None;
        }
        Some((0..groups.len()).map(move |index| {
            let group = groups[index];
            let start = if index == 0 {
                0
            } else {
                groups[index - 1].split_context_before(group)
            };
            let end = groups
                .get(index + 1)
                .map_or(self.lines.len(), |next| group.split_context_before(*next));
            self.segment(start, end)
        }))
    }

    /// Returns half-open ranges of contiguous non-context lines.
    fn change_groups(&self) -> Vec<ChangeGroup> {
        let mut groups = Vec::new();
        let mut current = None;

        for (index, line) in self.lines.iter().enumerate() {
            if matches!(line.kind, DiffLineKind::Context) {
                if let Some(start) = current.take() {
                    groups.push(ChangeGroup { start, end: index });
                }
            } else if current.is_none() {
                current = Some(index);
            }
        }
        if let Some(start) = current {
            groups.push(ChangeGroup {
                start,
                end: self.lines.len(),
            });
        }
        groups
    }

    /// Returns one hunk segment with line numbers and sizes recomputed.
    fn segment(&self, start: usize, end: usize) -> Self {
        let lines = self.lines[start..end].to_vec();
        let old_delta = self.lines[..start]
            .iter()
            .map(|l| l.kind.old_len())
            .sum::<u32>();
        let new_delta = self.lines[..start]
            .iter()
            .map(|l| l.kind.new_len())
            .sum::<u32>();
        let sizes = HunkSizes::from_lines(&lines);

        Self {
            id: self.id,
            header: HunkHeader {
                old_line_no: self.header.old_line_no.saturating_add(old_delta),
                old_size: sizes.old,
                new_line_no: self.header.new_line_no.saturating_add(new_delta),
                new_size: sizes.new,
                text: self.header.text.clone(),
            },
            lines,
        }
    }

    /// Returns old-side and new-side body sizes.
    fn sizes(&self) -> HunkSizes {
        HunkSizes::from_lines(&self.lines)
    }
}

/// Old-side and new-side line counts for a hunk body.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct HunkSizes {
    /// Old-side line count.
    old: u32,
    /// New-side line count.
    new: u32,
}

impl HunkSizes {
    /// Counts old-side and new-side contributions across diff lines.
    fn from_lines(lines: &[DiffLine]) -> Self {
        let mut sizes = Self::default();
        for line in lines {
            sizes.old += line.kind.old_len();
            sizes.new += line.kind.new_len();
        }
        sizes
    }
}

impl FileDiff {
    /// Returns the sum of addition and deletion lines across all hunks.
    pub fn stats(&self) -> FileStats {
        let mut total = FileStats::default();
        for hunk in &self.hunks {
            let hunk_stats = hunk.stats();
            total.additions += hunk_stats.additions;
            total.deletions += hunk_stats.deletions;
        }
        total
    }

    /// Returns a copy containing only the hunks at the given indexes.
    pub fn selected(&self, hunks: impl IntoIterator<Item = usize>) -> Self {
        Self {
            id: self.id,
            header: self.header.clone(),
            hunks: hunks
                .into_iter()
                .filter_map(|ix| self.hunks.get(ix).cloned())
                .collect(),
        }
    }
}

impl DiffDocument {
    /// Returns a single-file document with the given hunks, suitable for
    /// `git apply`. The preamble is dropped.
    pub fn for_hunks(file: &FileDiff, hunks: impl IntoIterator<Item = Hunk>) -> Self {
        Self {
            commit: None,
            files: vec![FileDiff {
                id: file.id,
                header: file.header.clone(),
                hunks: hunks.into_iter().collect(),
            }],
        }
    }
}

/// Half-open range of non-context lines inside a hunk.
#[derive(Clone, Copy, Debug)]
struct ChangeGroup {
    /// First changed line index.
    start: usize,
    /// One past the final changed line index.
    end: usize,
}

impl ChangeGroup {
    /// Returns the split point in the context before `next`.
    const fn split_context_before(self, next: Self) -> usize {
        self.end + (next.start - self.end) / 2
    }
}

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

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

    const PATCH: &str = "\
diff --git a/a.txt b/a.txt
index 7898192..6178079 100644
--- a/a.txt
+++ b/a.txt
@@ -1,3 +1,4 @@
 one
+two
 three
-four
+five
";

    #[test]
    fn diff_line_kind_counts_old_and_new_contributions() {
        assert_eq!(DiffLineKind::Context.old_len(), 1);
        assert_eq!(DiffLineKind::Context.new_len(), 1);
        assert_eq!(DiffLineKind::Addition.old_len(), 0);
        assert_eq!(DiffLineKind::Addition.new_len(), 1);
        assert_eq!(DiffLineKind::Deletion.old_len(), 1);
        assert_eq!(DiffLineKind::Deletion.new_len(), 0);
        assert_eq!(DiffLineKind::NoNewline.old_len(), 0);
        assert_eq!(DiffLineKind::NoNewline.new_len(), 0);
    }

    #[test]
    fn hunk_recomputes_sizes_from_lines() {
        let doc = parse_patch(PATCH);
        let hunk = &doc.files[0].hunks[0];

        assert_eq!(hunk.old_size(), 3);
        assert_eq!(hunk.new_size(), 4);
        assert_eq!(hunk.delta(), 1);
    }

    #[test]
    fn hunk_split_separates_change_groups() {
        let doc = parse_patch(PATCH);
        let hunk = &doc.files[0].hunks[0];
        let split = hunk.split().unwrap().collect::<Vec<_>>();

        assert_eq!(split.len(), 2);
        assert_eq!(split[0].header.old_line_no, 1);
        assert_eq!(split[0].header.old_size, 1);
        assert_eq!(split[0].header.new_line_no, 1);
        assert_eq!(split[0].header.new_size, 2);
        assert_eq!(split[1].header.old_line_no, 2);
        assert_eq!(split[1].header.old_size, 2);
        assert_eq!(split[1].header.new_line_no, 3);
        assert_eq!(split[1].header.new_size, 2);
    }

    #[test]
    fn hunk_split_returns_none_for_single_change_group() {
        let doc = parse_patch(
            "\
diff --git a/a b/a
@@ -1 +1,2 @@
 one
+two
",
        );

        assert!(doc.files[0].hunks[0].split().is_none());
    }

    #[test]
    fn hunk_header_shifted_moves_line_numbers() {
        let header = HunkHeader::decode_str("@@ -10,3 +20,3 @@").unwrap();
        let shifted = header.shifted(2, -3);

        assert_eq!(shifted.old_line_no, 12);
        assert_eq!(shifted.new_line_no, 17);
        assert_eq!(shifted.old_size, 3);
        assert_eq!(shifted.new_size, 3);
    }

    #[test]
    fn file_diff_selected_keeps_only_chosen_hunks() {
        let doc = parse_patch(PATCH);
        let only = doc.files[0].selected([0]);

        assert_eq!(only.hunks.len(), 1);
        assert_eq!(only.id, doc.files[0].id);
    }

    #[test]
    fn document_for_hunks_drops_preamble() {
        let with_preamble = format!("commit abc\n\n{PATCH}");
        let doc = parse_patch(&with_preamble);
        let single = DiffDocument::for_hunks(&doc.files[0], doc.files[0].hunks.clone());

        assert!(single.commit.is_none());
        assert_eq!(single.files.len(), 1);
        assert_eq!(single.files[0].hunks.len(), doc.files[0].hunks.len());
    }

    #[test]
    fn stats_aggregate_across_hunks_and_files() {
        let doc = parse_patch(PATCH);
        let hunk_stats = doc.files[0].hunks[0].stats();
        let file_stats = doc.files[0].stats();
        let doc_stats = doc.stats();

        assert_eq!(
            hunk_stats,
            FileStats {
                additions: 2,
                deletions: 1
            }
        );
        assert_eq!(
            file_stats,
            FileStats {
                additions: 2,
                deletions: 1
            }
        );
        assert_eq!(
            doc_stats,
            Stats {
                files_changed: 1,
                insertions: 2,
                deletions: 1,
            }
        );
    }

    #[test]
    fn file_mode_round_trips_through_octal() {
        for mode in [
            FileMode::Blob,
            FileMode::BlobExecutable,
            FileMode::Link,
            FileMode::Commit,
            FileMode::Tree,
            FileMode::Other(0o123456),
        ] {
            assert_eq!(FileMode::from_octal(mode.as_octal()), mode);
            assert_eq!(FileMode::parse(&mode.to_string()), Some(mode));
        }
        assert_eq!(FileMode::parse("not-octal"), None);
    }

    #[test]
    fn oid_parses_hexadecimal_text() {
        let oid = Oid::from_str("ABC123").unwrap();

        assert_eq!(oid.as_str(), "ABC123");
        assert_eq!(oid.to_string(), "ABC123");
        assert_eq!("".parse::<Oid>(), Err(OidError));
        assert_eq!("not-hex".parse::<Oid>(), Err(OidError));
    }

    #[test]
    fn add_delta_saturates_at_zero() {
        assert_eq!(HunkHeader::add_delta(5, 3), 8);
        assert_eq!(HunkHeader::add_delta(5, -3), 2);
        assert_eq!(HunkHeader::add_delta(2, -10), 0);
    }
}