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
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! Unified diff decoder.
//!
//! Streaming [`Decode`] implementations for [`HunkHeader`], [`DiffLine`],
//! [`Hunk`], [`FileDiff`], and [`DiffDocument`]. Hunks are read by their
//! header counts (matching radicle-cli's `unified_diff` shape) so callers
//! can pull a hunk at a time without arbitrary peek-ahead. File and
//! document boundaries are detected with [`BufRead::fill_buf`] since
//! rustik-diff has no libgit2 layer to do it for us.
//!
//! [`Decode::decode_str`] is a thin string entry point — it just wraps the
//! input in [`io::Cursor`] and runs the streaming decoder.

use std::io::{self, BufRead};
use std::path::PathBuf;
use std::str::FromStr;

use crate::document::{
    DecodeError, DiffDocument, DiffLine, DiffLineKind, FileDiff, FileHeader, FileId, FileKind,
    FileMode, Hunk, HunkHeader, HunkId, Oid, RowId,
};

/// Maximum number of hexadecimal characters in a Git object id.
const FULL_OBJECT_ID_HEX_LEN: usize = 64;

/// Decodes a value from unified diff text.
///
/// The default `decode_str`/`decode_bytes` adapters route through `decode`
/// so a single [`BufRead`]-based implementation covers all input shapes.
pub trait Decode: Sized {
    /// Reads and decodes a value from a buffered input stream.
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError>;

    /// Reads and decodes a value, returning `Ok(None)` at clean end-of-input.
    /// Anything else, including a partial value followed by EOF surfaces as
    /// `Err`.
    fn try_decode(input: &mut impl BufRead) -> Result<Option<Self>, DecodeError> {
        match Self::decode(input) {
            Ok(value) => Ok(Some(value)),
            Err(error) if error.is_eof() => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// Decodes a value from a UTF-8 string.
    fn decode_str(input: &str) -> Result<Self, DecodeError> {
        Self::decode_bytes(input.as_bytes())
    }

    /// Decodes a value from raw UTF-8 bytes.
    fn decode_bytes(input: &[u8]) -> Result<Self, DecodeError> {
        let mut reader = io::BufReader::new(input);
        Self::decode(&mut reader)
    }
}

impl Decode for HunkHeader {
    /// Reads a hunk header line from the input stream.
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
        let mut stream = Stream::new(input);
        let line = stream.read_line()?.ok_or_else(DecodeError::eof)?;
        HunkHeader::decode_line(&line.text).map_err(|error| error.at_line(line.line_no))
    }
}

impl Decode for DiffLine {
    /// Reads one hunk-body line from the input stream.
    ///
    /// The returned [`DiffLine`] uses a zero row id; callers should
    /// assign a stable ID.
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
        let mut stream = Stream::new(input);
        let line = stream.read_line()?.ok_or_else(DecodeError::eof)?;
        line.decode_diff_line(RowId::new(0))
    }
}

impl Decode for Hunk {
    /// Reads a complete hunk from the input stream.
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
        Stream::new(input).decode_hunk()
    }
}

impl Decode for FileDiff {
    /// Reads one file diff from the input stream.
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
        let mut stream = Stream::new(input);
        if !stream.has_more()? {
            return Err(DecodeError::eof());
        }
        stream.decode_file(FileId::new(0))
    }
}

impl Decode for DiffDocument {
    /// Reads a full diff document from the input stream.
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
        Stream::new(input).decode_document()
    }

    /// Decodes a diff document from raw bytes.
    ///
    /// Non-UTF-8 bytes are replaced with U+FFFD and ANSI escape sequences are
    /// stripped before parsing, so output from colored Git pipes round-trips
    /// without caller-side preprocessing.
    fn decode_bytes(input: &[u8]) -> Result<Self, DecodeError> {
        if !input.contains(&b'\x1b')
            && let Ok(text) = std::str::from_utf8(input)
        {
            let mut reader = io::BufReader::new(text.as_bytes());
            return Self::decode(&mut reader);
        }

        let text = String::from_utf8_lossy(input);
        let stripped = rustik_tui::ansi::strip(&text);
        let mut reader = io::BufReader::new(stripped.as_bytes());
        Self::decode(&mut reader)
    }
}

/// Streaming decoder over a buffered input stream.
///
/// Stores the reader, a line counter, and per-document ID counters used while
/// building a [`DiffDocument`]. Each decode call (`Hunk` or `FileDiff`) starts
/// from a fresh stream, so IDs begin at zero and callers that combine pieces
/// must renumber as needed.
struct Stream<R> {
    /// Buffered source of unified diff text.
    reader: R,
    /// Number of physical input lines already consumed.
    line_no: usize,
    /// Hunk ID to assign to the next decoded hunk.
    next_hunk_id: usize,
    /// Row ID to assign to the next decoded hunk-body line.
    next_row_id: usize,
}

/// One physical line read from the stream, with its 1-based line number.
struct ReadLine {
    /// 1-based physical input line number.
    line_no: usize,
    /// Line contents without trailing line endings.
    text: String,
}

impl<R: BufRead> Stream<R> {
    /// Creates a new streaming decoder.
    fn new(reader: R) -> Self {
        Self {
            reader,
            line_no: 0,
            next_hunk_id: 0,
            next_row_id: 0,
        }
    }

    /// Decodes a full document from the remaining input.
    fn decode_document(&mut self) -> Result<DiffDocument, DecodeError> {
        let mut commit = Vec::new();
        while self.has_more()? && !self.peek_starts_with(b"diff --git ")? {
            let Some(line) = self.read_line()? else {
                break;
            };
            commit.push(line.text);
        }
        let commit = commit.join("\n").parse().ok();
        let mut files = Vec::new();

        while self.has_more()? {
            let id = FileId::new(files.len());
            files.push(self.decode_file(id)?);
        }
        Ok(DiffDocument { commit, files })
    }

    /// Decodes one file diff from the remaining input.
    fn decode_file(&mut self, id: FileId) -> Result<FileDiff, DecodeError> {
        let line = self.read_line()?.ok_or_else(DecodeError::eof)?;
        let rest = line
            .text
            .strip_prefix("diff --git ")
            .ok_or_else(|| DecodeError::new(line.line_no, "missing 'diff --git' prefix"))?;
        let (old, new) = if rest.starts_with('"') {
            let mut escaped = false;
            let end = rest
                .char_indices()
                .skip(1)
                .find_map(|(index, ch)| match (ch, escaped) {
                    (_, true) => {
                        escaped = false;
                        None
                    }
                    ('\\', false) => {
                        escaped = true;
                        None
                    }
                    ('"', false) => Some(index + 1),
                    _ => None,
                })
                .ok_or_else(|| DecodeError::new(line.line_no, "unterminated quoted path"))?;
            let new = rest[end..]
                .strip_prefix(' ')
                .ok_or_else(|| DecodeError::new(line.line_no, "diff header is missing paths"))?;

            (&rest[..end], new)
        } else if let Some(index) = rest.find(" b/") {
            (&rest[..index], &rest[index + 1..])
        } else if let Some(index) = rest.find(" \"") {
            (&rest[..index], &rest[index + 1..])
        } else {
            rest.split_once(' ')
                .ok_or_else(|| DecodeError::new(line.line_no, "diff header is missing paths"))?
        };
        let old_path = Some(decode_git_path(old, "a/"));
        let new_path = Some(decode_git_path(new, "b/"));
        let mut header = FileHeader {
            kind: FileKind::Modified,
            old_path,
            new_path,
            old_mode: None,
            new_mode: None,
            old_oid: None,
            new_oid: None,
            raw: vec![line.text.clone()],
        };
        let mut hunks = Vec::new();

        loop {
            match self.peek_byte()? {
                None => break,
                Some(b'@') => hunks.push(self.decode_hunk()?),
                Some(b'd') if self.peek_starts_with(b"diff --git ")? => break,
                Some(_) => {
                    let Some(line) = self.read_line()? else {
                        return Err(DecodeError::eof());
                    };
                    if let Some(mode) = line.text.strip_prefix("new file mode ") {
                        header.kind = FileKind::Added;
                        header.new_mode = FileMode::parse(mode);
                    } else if let Some(mode) = line.text.strip_prefix("deleted file mode ") {
                        header.kind = FileKind::Deleted;
                        header.old_mode = FileMode::parse(mode);
                    } else if let Some(mode) = line.text.strip_prefix("old mode ") {
                        header.old_mode = FileMode::parse(mode);
                    } else if let Some(mode) = line.text.strip_prefix("new mode ") {
                        header.new_mode = FileMode::parse(mode);
                        if header.kind == FileKind::Modified {
                            header.kind = FileKind::ModeChanged;
                        }
                    } else if let Some(path) = line.text.strip_prefix("rename from ") {
                        header.kind = FileKind::Renamed;
                        header.old_path = Some(decode_git_path(path, ""));
                    } else if let Some(path) = line.text.strip_prefix("rename to ") {
                        header.kind = FileKind::Renamed;
                        header.new_path = Some(decode_git_path(path, ""));
                    } else if let Some(path) = line.text.strip_prefix("copy from ") {
                        header.kind = FileKind::Copied;
                        header.old_path = Some(decode_git_path(path, ""));
                    } else if let Some(path) = line.text.strip_prefix("copy to ") {
                        header.kind = FileKind::Copied;
                        header.new_path = Some(decode_git_path(path, ""));
                    } else if line.text.starts_with("Binary files ")
                        || line.text == "GIT binary patch"
                    {
                        header.kind = FileKind::Binary;
                    } else if let Some(rest) = line.text.strip_prefix("index ") {
                        let mut parts = rest.split_whitespace();
                        if let Some(oids) = parts.next()
                            && let Some((old, new)) = oids.split_once("..")
                        {
                            header.old_oid = parse_index_oid(old, line.line_no, "old object id")?;
                            header.new_oid = parse_index_oid(new, line.line_no, "new object id")?;
                        }
                        if let Some(mode) = parts.next()
                            && let Some(parsed) = FileMode::parse(mode)
                        {
                            header.old_mode.get_or_insert(parsed);
                            header.new_mode.get_or_insert(parsed);
                        }
                    }
                    header.raw.push(line.text);
                }
            }
        }
        Ok(FileDiff { id, header, hunks })
    }

    /// Decodes one hunk from the remaining input.
    fn decode_hunk(&mut self) -> Result<Hunk, DecodeError> {
        let line = self.read_line()?.ok_or_else(DecodeError::eof)?;
        let header =
            HunkHeader::decode_line(&line.text).map_err(|error| error.at_line(line.line_no))?;
        let id = HunkId::new(self.next_hunk_id);
        self.next_hunk_id += 1;

        let mut lines = Vec::new();
        let mut old_consumed: u32 = 0;
        let mut new_consumed: u32 = 0;

        loop {
            if old_consumed >= header.old_size && new_consumed >= header.new_size {
                while self.peek_byte()? == Some(b'\\') {
                    let Some(raw) = self.read_line()? else {
                        return Err(DecodeError::eof());
                    };
                    lines.push(raw.decode_diff_line(self.take_row_id())?);
                }
                break;
            }
            let Some(raw) = self.read_line()? else {
                return Err(DecodeError::new(
                    0,
                    format!(
                        "expected '{}' old lines and '{}' new lines, but found '{}' and '{}'",
                        header.old_size, header.new_size, old_consumed, new_consumed
                    ),
                ));
            };
            let row_id = self.take_row_id();
            let parsed = raw.decode_diff_line(row_id)?;

            match parsed.kind {
                DiffLineKind::Context => {
                    old_consumed += 1;
                    new_consumed += 1;
                }
                DiffLineKind::Addition => new_consumed += 1,
                DiffLineKind::Deletion => old_consumed += 1,
                DiffLineKind::NoNewline => {}
            }
            lines.push(parsed);
        }
        Ok(Hunk { id, header, lines })
    }

    /// Returns whether unread input remains in the stream.
    fn has_more(&mut self) -> Result<bool, DecodeError> {
        Ok(!self.reader.fill_buf()?.is_empty())
    }

    /// Returns the next byte without consuming it.
    fn peek_byte(&mut self) -> Result<Option<u8>, DecodeError> {
        Ok(self.reader.fill_buf()?.first().copied())
    }

    /// Checks whether the next bytes match a required prefix.
    fn peek_starts_with(&mut self, prefix: &[u8]) -> Result<bool, DecodeError> {
        let buf = self.reader.fill_buf()?;
        Ok(buf.len() >= prefix.len() && &buf[..prefix.len()] == prefix)
    }

    /// Reads the next line, stripping trailing line endings.
    fn read_line(&mut self) -> Result<Option<ReadLine>, DecodeError> {
        let mut buf = String::new();
        let n = self.reader.read_line(&mut buf)?;
        if n == 0 {
            return Ok(None);
        }
        self.line_no += 1;

        if buf.ends_with('\n') {
            buf.pop();
            if buf.ends_with('\r') {
                buf.pop();
            }
        }
        Ok(Some(ReadLine {
            line_no: self.line_no,
            text: buf,
        }))
    }

    /// Returns the next row identifier.
    fn take_row_id(&mut self) -> RowId {
        let id = RowId::new(self.next_row_id);
        self.next_row_id += 1;
        id
    }
}

impl HunkHeader {
    /// Decodes one unified diff hunk header line like `@@ -A,B +C,D @@ optional text`.
    fn decode_line(line: &str) -> Result<Self, DecodeError> {
        let rest = line
            .strip_prefix("@@ -")
            .ok_or_else(|| DecodeError::new(0, "hunk header must start with '@@ -'"))?;
        let (old, rest) = rest
            .split_once(" +")
            .ok_or_else(|| DecodeError::new(0, "hunk header is missing new-file range"))?;
        let (new, text) = rest
            .split_once(" @@")
            .ok_or_else(|| DecodeError::new(0, "hunk header is missing closing '@@'"))?;
        let (old_line_no, old_size) = Self::decode_range(old)?;
        let (new_line_no, new_size) = Self::decode_range(new)?;

        Ok(Self {
            old_line_no,
            old_size,
            new_line_no,
            new_size,
            text: text.strip_prefix(' ').unwrap_or(text).to_owned(),
        })
    }

    /// Decodes a unified diff range into a start and size pair.
    fn decode_range(input: &str) -> Result<(u32, u32), DecodeError> {
        let (line, size) = input.split_once(',').unwrap_or((input, "1"));
        Ok((line.parse()?, size.parse()?))
    }
}

impl ReadLine {
    /// Decodes one hunk-body line into a [`DiffLine`] with the given id.
    fn decode_diff_line(&self, id: RowId) -> Result<DiffLine, DecodeError> {
        if self.text.starts_with('\\') {
            if !self.text.starts_with("\\ No newline at end of file") {
                return Err(DecodeError::new(
                    self.line_no,
                    format!("invalid hunk line: {}", self.text),
                ));
            }
            return Ok(DiffLine {
                id,
                kind: DiffLineKind::NoNewline,
                text: String::new(),
            });
        }
        let mut chars = self.text.chars();
        let marker = chars.next().ok_or_else(|| {
            DecodeError::new(self.line_no, format!("invalid hunk line: {}", self.text))
        })?;
        let text = chars.as_str();
        let kind = match marker {
            ' ' => DiffLineKind::Context,
            '+' => DiffLineKind::Addition,
            '-' => DiffLineKind::Deletion,
            _ => {
                return Err(DecodeError::new(
                    self.line_no,
                    format!("invalid hunk line: {}", self.text),
                ));
            }
        };
        Ok(DiffLine {
            id,
            kind,
            text: text.to_owned(),
        })
    }
}

/// Decodes Git's C-style path quoting and removes a diff-side prefix.
fn decode_git_path(input: &str, prefix: &str) -> PathBuf {
    let Some(input) = input
        .strip_prefix('"')
        .and_then(|input| input.strip_suffix('"'))
    else {
        return PathBuf::from(input.strip_prefix(prefix).unwrap_or(input));
    };
    let input = input.as_bytes();
    let mut decoded = Vec::with_capacity(input.len());
    let mut index = 0;

    while index < input.len() {
        if input[index] != b'\\' {
            decoded.push(input[index]);
            index += 1;
            continue;
        }
        let Some(escape) = input.get(index + 1).copied() else {
            decoded.push(b'\\');
            break;
        };

        match escape {
            b'a' => decoded.push(b'\x07'),
            b'b' => decoded.push(b'\x08'),
            b't' => decoded.push(b'\t'),
            b'n' => decoded.push(b'\n'),
            b'v' => decoded.push(b'\x0b'),
            b'f' => decoded.push(b'\x0c'),
            b'r' => decoded.push(b'\r'),
            b'\\' | b'"' => decoded.push(escape),
            b'0'..=b'7' => {
                let mut value = 0;
                let mut digits = 0;
                while digits < 3
                    && let Some(digit @ b'0'..=b'7') = input.get(index + 1 + digits).copied()
                {
                    value = value * 8 + (digit - b'0');
                    digits += 1;
                }
                decoded.push(value);
                index += digits - 1;
            }
            _ => {
                decoded.push(b'\\');
                decoded.push(escape);
            }
        }
        index += 2;
    }

    if decoded.starts_with(prefix.as_bytes()) {
        drop(decoded.drain(..prefix.len()));
    }

    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStringExt as _;

        PathBuf::from(std::ffi::OsString::from_vec(decoded))
    }
    #[cfg(not(unix))]
    {
        PathBuf::from(String::from_utf8_lossy(&decoded).into_owned())
    }
}

/// Parses a full object id and accepts abbreviated hex ids as unavailable.
fn parse_index_oid(
    input: &str,
    line_no: usize,
    description: &'static str,
) -> Result<Option<Oid>, DecodeError> {
    match Oid::from_str(input) {
        Ok(oid) => Ok(Some(oid)),
        Err(_) if is_abbreviated_oid(input) => Ok(None),
        Err(_) => Err(DecodeError::new(line_no, format!("invalid {description}"))),
    }
}

/// Returns whether `input` is a syntactically valid abbreviated object id.
fn is_abbreviated_oid(input: &str) -> bool {
    !input.is_empty()
        && input.len() < FULL_OBJECT_ID_HEX_LEN
        && input.bytes().all(|byte| byte.is_ascii_hexdigit())
}

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

    #[test]
    fn parses_preamble_and_modified_hunk() {
        let doc = DiffDocument::decode_str(
            "\
commit 1234567890abcdef1234567890abcdef12345678
Author: A

diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1 +1 @@
-old
+new
\\ No newline at end of file
",
        )
        .expect("diff parses");

        let commit = doc.commit.as_ref().expect("preamble parsed");
        assert_eq!(
            commit.hash.to_string(),
            "1234567890abcdef1234567890abcdef12345678"
        );
        assert_eq!(commit.header("Author"), Some("A"));
        assert!(commit.message.is_empty());
        assert_eq!(doc.files.len(), 1);
        assert_eq!(doc.files[0].header.kind, FileKind::Modified);
        assert_eq!(
            doc.files[0].header.old_oid.map(|oid| oid.to_string()),
            Some("1111111111111111111111111111111111111111".to_owned())
        );
        assert_eq!(
            doc.files[0].header.new_oid.map(|oid| oid.to_string()),
            Some("2222222222222222222222222222222222222222".to_owned())
        );
        assert_eq!(doc.files[0].hunks[0].header.old_line_no, 1);
        assert_eq!(doc.files[0].hunks[0].lines[0].kind, DiffLineKind::Deletion);
        assert_eq!(doc.files[0].hunks[0].lines[1].kind, DiffLineKind::Addition);
        assert_eq!(doc.files[0].hunks[0].lines[2].kind, DiffLineKind::NoNewline);
    }

    #[test]
    fn parses_added_deleted_renamed_copied_mode_and_binary_files() {
        let doc = DiffDocument::decode_str(
            "\
diff --git a/new.rs b/new.rs
new file mode 100644
index 0000000000000000000000000000000000000000..1111111111111111111111111111111111111111
--- /dev/null
+++ b/new.rs
@@ -0,0 +1 @@
+new
diff --git a/old.rs b/old.rs
deleted file mode 100644
index 1111111111111111111111111111111111111111..0000000000000000000000000000000000000000
--- a/old.rs
+++ /dev/null
@@ -1 +0,0 @@
-old
diff --git a/from.rs b/to.rs
similarity index 100%
rename from from.rs
rename to to.rs
diff --git a/copy.rs b/copy2.rs
similarity index 100%
copy from copy.rs
copy to copy2.rs
diff --git a/mode.sh b/mode.sh
old mode 100644
new mode 100755
diff --git a/image.png b/image.png
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
Binary files a/image.png and b/image.png differ
",
        )
        .expect("diff parses");

        let kinds = doc
            .files
            .iter()
            .map(|file| file.header.kind)
            .collect::<Vec<_>>();
        assert_eq!(
            kinds,
            vec![
                FileKind::Added,
                FileKind::Deleted,
                FileKind::Renamed,
                FileKind::Copied,
                FileKind::ModeChanged,
                FileKind::Binary,
            ]
        );
        assert_eq!(doc.files[2].header.old_path, Some(PathBuf::from("from.rs")));
        assert_eq!(doc.files[2].header.new_path, Some(PathBuf::from("to.rs")));
        assert_eq!(doc.files[4].header.old_mode, Some(FileMode::Blob));
        assert_eq!(doc.files[4].header.new_mode, Some(FileMode::BlobExecutable));
    }

    #[test]
    fn decodes_git_quoted_paths() {
        let doc = DiffDocument::decode_str(
            r#"diff --git "a/modified caf\303\251\t\"slash\\.rs" "b/modified caf\303\251\t\"slash\\.rs"
index 438999b..4c0acd2 100644
--- "a/modified caf\303\251\t\"slash\\.rs"	
+++ "b/modified caf\303\251\t\"slash\\.rs"	
@@ -1,2 +1,2 @@
-old
+new
 keep
diff --git a/ordinary.rs b/ordinary.rs
index 3367afd..3e75765 100644
--- a/ordinary.rs
+++ b/ordinary.rs
@@ -1 +1 @@
-old
+new
diff --git "a/rename from caf\303\251\t\"slash\\.rs" "b/rename to caf\303\251\t\"slash\\.rs"
similarity index 100%
rename from "rename from caf\303\251\t\"slash\\.rs"
rename to "rename to caf\303\251\t\"slash\\.rs"
"#,
        )
        .unwrap();

        assert_eq!(
            doc.files[0].header.old_path,
            Some(PathBuf::from("modified café\t\"slash\\.rs"))
        );
        assert_eq!(
            doc.files[0].header.new_path,
            Some(PathBuf::from("modified café\t\"slash\\.rs"))
        );
        assert_eq!(
            doc.files[1].header.old_path,
            Some(PathBuf::from("ordinary.rs"))
        );
        assert_eq!(
            doc.files[1].header.new_path,
            Some(PathBuf::from("ordinary.rs"))
        );
        assert_eq!(
            doc.files[2].header.old_path,
            Some(PathBuf::from("rename from café\t\"slash\\.rs"))
        );
        assert_eq!(
            doc.files[2].header.new_path,
            Some(PathBuf::from("rename to café\t\"slash\\.rs"))
        );
    }

    #[cfg(unix)]
    #[test]
    fn preserves_non_utf8_bytes_in_git_quoted_paths() {
        use std::os::unix::ffi::OsStrExt as _;

        let doc = DiffDocument::decode_str(
            r#"diff --git "a/non-utf8-\377.rs" "b/non-utf8-\377.rs"
"#,
        )
        .expect("diff parses");

        assert_eq!(
            doc.files[0]
                .header
                .old_path
                .as_deref()
                .expect("old path")
                .as_os_str()
                .as_bytes(),
            b"non-utf8-\xff.rs"
        );
        assert_eq!(
            doc.files[0]
                .header
                .new_path
                .as_deref()
                .expect("new path")
                .as_os_str()
                .as_bytes(),
            b"non-utf8-\xff.rs"
        );
    }

    #[test]
    fn parses_hunk_header_default_sizes() {
        let header = HunkHeader::decode_line("@@ -7 +8 @@ fn main").expect("header parses");

        assert_eq!(header.old_line_no, 7);
        assert_eq!(header.old_size, 1);
        assert_eq!(header.new_line_no, 8);
        assert_eq!(header.new_size, 1);
        assert_eq!(header.text, "fn main");
    }

    #[test]
    fn decode_via_bufread_matches_zero_copy_parse() {
        let input = "\
diff --git a/a b/a
@@ -1 +1 @@
-old
+new
";
        let from_str = DiffDocument::decode_str(input).expect("zero-copy parse");
        let from_bytes = DiffDocument::decode_bytes(input.as_bytes()).expect("bufread decode");

        assert_eq!(from_str, from_bytes);
    }

    #[test]
    fn reports_invalid_hunk_lines() {
        let error = DiffDocument::decode_str(
            "\
diff --git a/a b/a
@@ -1 +1 @@
?bad
",
        )
        .expect_err("invalid hunk line is rejected");

        assert_eq!(error.line, 3);
        assert!(error.message.contains("invalid hunk line"));
        assert!(!error.is_eof());
    }

    #[test]
    fn reports_invalid_index_object_ids() {
        let error = DiffDocument::decode_str(
            "\
diff --git a/a b/a
index not-hex..2222222222222222222222222222222222222222 100644
@@ -1 +1 @@
-old
+new
",
        )
        .expect_err("invalid object id should be rejected");

        assert_eq!(error.line, 2);
        assert_eq!(error.message, "invalid old object id");
    }

    #[test]
    fn accepts_abbreviated_index_object_ids() {
        let doc = DiffDocument::decode_str(
            "\
diff --git a/a b/a
index 1234567..89abcde 100644
@@ -1 +1 @@
-old
+new
",
        )
        .unwrap();

        assert_eq!(doc.files.len(), 1);
        assert_eq!(doc.files[0].header.old_oid, None);
        assert_eq!(doc.files[0].header.new_oid, None);
        assert_eq!(doc.files[0].header.old_mode, Some(FileMode::Blob));
        assert_eq!(doc.files[0].header.new_mode, Some(FileMode::Blob));
        assert_eq!(doc.stats().insertions, 1);
        assert_eq!(doc.stats().deletions, 1);
    }

    #[test]
    fn try_decode_hunks_one_at_a_time() {
        let input = "\
@@ -1 +1 @@
-old
+new
@@ -10,2 +10,2 @@ ctx
 a
-b
+c
";
        let mut reader = io::BufReader::new(input.as_bytes());

        let first = Hunk::try_decode(&mut reader)
            .expect("decodes")
            .expect("first hunk present");
        assert_eq!(first.header.old_line_no, 1);
        assert_eq!(first.lines.len(), 2);

        let second = Hunk::try_decode(&mut reader)
            .expect("decodes")
            .expect("second hunk present");
        assert_eq!(second.header.old_line_no, 10);
        assert_eq!(second.header.text, "ctx");
        assert_eq!(second.lines.len(), 3);

        assert!(
            Hunk::try_decode(&mut reader).expect("decodes").is_none(),
            "stream should be drained",
        );
    }

    #[test]
    fn try_decode_returns_none_on_empty_input() {
        let mut empty = io::BufReader::new(&[][..]);
        assert!(FileDiff::try_decode(&mut empty).expect("eof").is_none());
        let mut empty = io::BufReader::new(&[][..]);
        assert!(Hunk::try_decode(&mut empty).expect("eof").is_none());
        // An empty stream is a valid (empty) document.
        let mut empty = io::BufReader::new(&[][..]);
        assert!(
            DiffDocument::decode(&mut empty)
                .expect("decodes empty")
                .is_empty()
        );
    }

    #[test]
    fn try_decode_distinguishes_eof_from_syntax_error() {
        let mut bad = io::BufReader::new(&b"@@ not a hunk header\n"[..]);
        let error = Hunk::try_decode(&mut bad).expect_err("syntax error surfaces");
        assert!(!error.is_eof());
    }

    #[test]
    fn streaming_decode_matches_zero_copy_parse_for_full_document() {
        let input = "\
commit 1234567890abcdef1234567890abcdef12345678

diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1 +1 @@
-old
+new
diff --git a/b.rs b/b.rs
new file mode 100644
index 0000000000000000000000000000000000000000..3333333333333333333333333333333333333333
--- /dev/null
+++ b/b.rs
@@ -0,0 +1 @@
+only
";
        let zero_copy = DiffDocument::decode_str(input).expect("zero-copy parses");
        let streamed = {
            let mut reader = io::BufReader::new(input.as_bytes());
            DiffDocument::decode(&mut reader).expect("stream decodes")
        };

        assert_eq!(zero_copy, streamed);
    }

    #[test]
    fn raw_bytes_strip_ansi_before_decoding_document() {
        let input = b"\
\x1b[33mdiff --git a/a.rs b/a.rs\x1b[m
\x1b[33mindex 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\x1b[m
\x1b[33m--- a/a.rs\x1b[m
\x1b[33m+++ b/a.rs\x1b[m
\x1b[35m@@ -1 +1 @@\x1b[m
\x1b[31m-old\x1b[m
\x1b[32m+new\x1b[m
";
        let document = DiffDocument::decode_bytes(input).unwrap();

        assert_eq!(document.files.len(), 1);
        assert_eq!(document.stats().insertions, 1);
        assert_eq!(document.stats().deletions, 1);
    }

    #[test]
    fn hunk_body_uses_header_counts_to_terminate() {
        // Body is exactly old_size + new_size = 1 + 2 = 3 line-types.
        // After the body, a `\ No newline...` marker must still be consumed.
        let input = "\
@@ -1 +1,2 @@
-old
+new
+extra
\\ No newline at end of file
";
        let mut reader = io::BufReader::new(input.as_bytes());
        let hunk = Hunk::decode(&mut reader).expect("decodes");

        assert_eq!(hunk.lines.len(), 4);
        assert_eq!(hunk.lines[3].kind, DiffLineKind::NoNewline);
        assert!(reader.fill_buf().expect("fills").is_empty());
    }
}