crates/diff/src/decode.rs 31.0 KiB raw
1
//! Unified diff decoder.
2
//!
3
//! Streaming [`Decode`] implementations for [`HunkHeader`], [`DiffLine`],
4
//! [`Hunk`], [`FileDiff`], and [`DiffDocument`]. Hunks are read by their
5
//! header counts (matching radicle-cli's `unified_diff` shape) so callers
6
//! can pull a hunk at a time without arbitrary peek-ahead. File and
7
//! document boundaries are detected with [`BufRead::fill_buf`] since
8
//! rustik-diff has no libgit2 layer to do it for us.
9
//!
10
//! [`Decode::decode_str`] is a thin string entry point — it just wraps the
11
//! input in [`io::Cursor`] and runs the streaming decoder.
12
13
use std::io::{self, BufRead};
14
use std::path::PathBuf;
15
use std::str::FromStr;
16
17
use crate::document::{
18
    DecodeError, DiffDocument, DiffLine, DiffLineKind, FileDiff, FileHeader, FileId, FileKind,
19
    FileMode, Hunk, HunkHeader, HunkId, Oid, RowId,
20
};
21
22
/// Maximum number of hexadecimal characters in a Git object id.
23
const FULL_OBJECT_ID_HEX_LEN: usize = 64;
24
25
/// Decodes a value from unified diff text.
26
///
27
/// The default `decode_str`/`decode_bytes` adapters route through `decode`
28
/// so a single [`BufRead`]-based implementation covers all input shapes.
29
pub trait Decode: Sized {
30
    /// Reads and decodes a value from a buffered input stream.
31
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError>;
32
33
    /// Reads and decodes a value, returning `Ok(None)` at clean end-of-input.
34
    /// Anything else, including a partial value followed by EOF surfaces as
35
    /// `Err`.
36
    fn try_decode(input: &mut impl BufRead) -> Result<Option<Self>, DecodeError> {
37
        match Self::decode(input) {
38
            Ok(value) => Ok(Some(value)),
39
            Err(error) if error.is_eof() => Ok(None),
40
            Err(error) => Err(error),
41
        }
42
    }
43
44
    /// Decodes a value from a UTF-8 string.
45
    fn decode_str(input: &str) -> Result<Self, DecodeError> {
46
        Self::decode_bytes(input.as_bytes())
47
    }
48
49
    /// Decodes a value from raw UTF-8 bytes.
50
    fn decode_bytes(input: &[u8]) -> Result<Self, DecodeError> {
51
        let mut reader = io::BufReader::new(input);
52
        Self::decode(&mut reader)
53
    }
54
}
55
56
impl Decode for HunkHeader {
57
    /// Reads a hunk header line from the input stream.
58
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
59
        let mut stream = Stream::new(input);
60
        let line = stream.read_line()?.ok_or_else(DecodeError::eof)?;
61
        HunkHeader::decode_line(&line.text).map_err(|error| error.at_line(line.line_no))
62
    }
63
}
64
65
impl Decode for DiffLine {
66
    /// Reads one hunk-body line from the input stream.
67
    ///
68
    /// The returned [`DiffLine`] uses a zero row id; callers should
69
    /// assign a stable ID.
70
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
71
        let mut stream = Stream::new(input);
72
        let line = stream.read_line()?.ok_or_else(DecodeError::eof)?;
73
        line.decode_diff_line(RowId::new(0))
74
    }
75
}
76
77
impl Decode for Hunk {
78
    /// Reads a complete hunk from the input stream.
79
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
80
        Stream::new(input).decode_hunk()
81
    }
82
}
83
84
impl Decode for FileDiff {
85
    /// Reads one file diff from the input stream.
86
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
87
        let mut stream = Stream::new(input);
88
        if !stream.has_more()? {
89
            return Err(DecodeError::eof());
90
        }
91
        stream.decode_file(FileId::new(0))
92
    }
93
}
94
95
impl Decode for DiffDocument {
96
    /// Reads a full diff document from the input stream.
97
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
98
        Stream::new(input).decode_document()
99
    }
100
101
    /// Decodes a diff document from raw bytes.
102
    ///
103
    /// Non-UTF-8 bytes are replaced with U+FFFD and ANSI escape sequences are
104
    /// stripped before parsing, so output from colored Git pipes round-trips
105
    /// without caller-side preprocessing.
106
    fn decode_bytes(input: &[u8]) -> Result<Self, DecodeError> {
107
        if !input.contains(&b'\x1b')
108
            && let Ok(text) = std::str::from_utf8(input)
109
        {
110
            let mut reader = io::BufReader::new(text.as_bytes());
111
            return Self::decode(&mut reader);
112
        }
113
114
        let text = String::from_utf8_lossy(input);
115
        let stripped = rustik_tui::ansi::strip(&text);
116
        let mut reader = io::BufReader::new(stripped.as_bytes());
117
        Self::decode(&mut reader)
118
    }
119
}
120
121
/// Streaming decoder over a buffered input stream.
122
///
123
/// Stores the reader, a line counter, and per-document ID counters used while
124
/// building a [`DiffDocument`]. Each decode call (`Hunk` or `FileDiff`) starts
125
/// from a fresh stream, so IDs begin at zero and callers that combine pieces
126
/// must renumber as needed.
127
struct Stream<R> {
128
    /// Buffered source of unified diff text.
129
    reader: R,
130
    /// Number of physical input lines already consumed.
131
    line_no: usize,
132
    /// Hunk ID to assign to the next decoded hunk.
133
    next_hunk_id: usize,
134
    /// Row ID to assign to the next decoded hunk-body line.
135
    next_row_id: usize,
136
}
137
138
/// One physical line read from the stream, with its 1-based line number.
139
struct ReadLine {
140
    /// 1-based physical input line number.
141
    line_no: usize,
142
    /// Line contents without trailing line endings.
143
    text: String,
144
}
145
146
impl<R: BufRead> Stream<R> {
147
    /// Creates a new streaming decoder.
148
    fn new(reader: R) -> Self {
149
        Self {
150
            reader,
151
            line_no: 0,
152
            next_hunk_id: 0,
153
            next_row_id: 0,
154
        }
155
    }
156
157
    /// Decodes a full document from the remaining input.
158
    fn decode_document(&mut self) -> Result<DiffDocument, DecodeError> {
159
        let mut commit = Vec::new();
160
        while self.has_more()? && !self.peek_starts_with(b"diff --git ")? {
161
            let Some(line) = self.read_line()? else {
162
                break;
163
            };
164
            commit.push(line.text);
165
        }
166
        let commit = commit.join("\n").parse().ok();
167
        let mut files = Vec::new();
168
169
        while self.has_more()? {
170
            let id = FileId::new(files.len());
171
            files.push(self.decode_file(id)?);
172
        }
173
        Ok(DiffDocument { commit, files })
174
    }
175
176
    /// Decodes one file diff from the remaining input.
177
    fn decode_file(&mut self, id: FileId) -> Result<FileDiff, DecodeError> {
178
        let line = self.read_line()?.ok_or_else(DecodeError::eof)?;
179
        let rest = line
180
            .text
181
            .strip_prefix("diff --git ")
182
            .ok_or_else(|| DecodeError::new(line.line_no, "missing 'diff --git' prefix"))?;
183
        let (old, new) = if rest.starts_with('"') {
184
            let mut escaped = false;
185
            let end = rest
186
                .char_indices()
187
                .skip(1)
188
                .find_map(|(index, ch)| match (ch, escaped) {
189
                    (_, true) => {
190
                        escaped = false;
191
                        None
192
                    }
193
                    ('\\', false) => {
194
                        escaped = true;
195
                        None
196
                    }
197
                    ('"', false) => Some(index + 1),
198
                    _ => None,
199
                })
200
                .ok_or_else(|| DecodeError::new(line.line_no, "unterminated quoted path"))?;
201
            let new = rest[end..]
202
                .strip_prefix(' ')
203
                .ok_or_else(|| DecodeError::new(line.line_no, "diff header is missing paths"))?;
204
205
            (&rest[..end], new)
206
        } else if let Some(index) = rest.find(" b/") {
207
            (&rest[..index], &rest[index + 1..])
208
        } else if let Some(index) = rest.find(" \"") {
209
            (&rest[..index], &rest[index + 1..])
210
        } else {
211
            rest.split_once(' ')
212
                .ok_or_else(|| DecodeError::new(line.line_no, "diff header is missing paths"))?
213
        };
214
        let old_path = Some(decode_git_path(old, "a/"));
215
        let new_path = Some(decode_git_path(new, "b/"));
216
        let mut header = FileHeader {
217
            kind: FileKind::Modified,
218
            old_path,
219
            new_path,
220
            old_mode: None,
221
            new_mode: None,
222
            old_oid: None,
223
            new_oid: None,
224
            raw: vec![line.text.clone()],
225
        };
226
        let mut hunks = Vec::new();
227
228
        loop {
229
            match self.peek_byte()? {
230
                None => break,
231
                Some(b'@') => hunks.push(self.decode_hunk()?),
232
                Some(b'd') if self.peek_starts_with(b"diff --git ")? => break,
233
                Some(_) => {
234
                    let Some(line) = self.read_line()? else {
235
                        return Err(DecodeError::eof());
236
                    };
237
                    if let Some(mode) = line.text.strip_prefix("new file mode ") {
238
                        header.kind = FileKind::Added;
239
                        header.new_mode = FileMode::parse(mode);
240
                    } else if let Some(mode) = line.text.strip_prefix("deleted file mode ") {
241
                        header.kind = FileKind::Deleted;
242
                        header.old_mode = FileMode::parse(mode);
243
                    } else if let Some(mode) = line.text.strip_prefix("old mode ") {
244
                        header.old_mode = FileMode::parse(mode);
245
                    } else if let Some(mode) = line.text.strip_prefix("new mode ") {
246
                        header.new_mode = FileMode::parse(mode);
247
                        if header.kind == FileKind::Modified {
248
                            header.kind = FileKind::ModeChanged;
249
                        }
250
                    } else if let Some(path) = line.text.strip_prefix("rename from ") {
251
                        header.kind = FileKind::Renamed;
252
                        header.old_path = Some(decode_git_path(path, ""));
253
                    } else if let Some(path) = line.text.strip_prefix("rename to ") {
254
                        header.kind = FileKind::Renamed;
255
                        header.new_path = Some(decode_git_path(path, ""));
256
                    } else if let Some(path) = line.text.strip_prefix("copy from ") {
257
                        header.kind = FileKind::Copied;
258
                        header.old_path = Some(decode_git_path(path, ""));
259
                    } else if let Some(path) = line.text.strip_prefix("copy to ") {
260
                        header.kind = FileKind::Copied;
261
                        header.new_path = Some(decode_git_path(path, ""));
262
                    } else if line.text.starts_with("Binary files ")
263
                        || line.text == "GIT binary patch"
264
                    {
265
                        header.kind = FileKind::Binary;
266
                    } else if let Some(rest) = line.text.strip_prefix("index ") {
267
                        let mut parts = rest.split_whitespace();
268
                        if let Some(oids) = parts.next()
269
                            && let Some((old, new)) = oids.split_once("..")
270
                        {
271
                            header.old_oid = parse_index_oid(old, line.line_no, "old object id")?;
272
                            header.new_oid = parse_index_oid(new, line.line_no, "new object id")?;
273
                        }
274
                        if let Some(mode) = parts.next()
275
                            && let Some(parsed) = FileMode::parse(mode)
276
                        {
277
                            header.old_mode.get_or_insert(parsed);
278
                            header.new_mode.get_or_insert(parsed);
279
                        }
280
                    }
281
                    header.raw.push(line.text);
282
                }
283
            }
284
        }
285
        if header.kind == FileKind::Binary {
286
            hunks.push(Hunk {
287
                id: HunkId::new(self.next_hunk_id),
288
                header: HunkHeader::default(),
289
                lines: Vec::new(),
290
            });
291
            self.next_hunk_id += 1;
292
        }
293
        Ok(FileDiff { id, header, hunks })
294
    }
295
296
    /// Decodes one hunk from the remaining input.
297
    fn decode_hunk(&mut self) -> Result<Hunk, DecodeError> {
298
        let line = self.read_line()?.ok_or_else(DecodeError::eof)?;
299
        let header =
300
            HunkHeader::decode_line(&line.text).map_err(|error| error.at_line(line.line_no))?;
301
        let id = HunkId::new(self.next_hunk_id);
302
        self.next_hunk_id += 1;
303
304
        let mut lines = Vec::new();
305
        let mut old_consumed: u32 = 0;
306
        let mut new_consumed: u32 = 0;
307
308
        loop {
309
            if old_consumed >= header.old_size && new_consumed >= header.new_size {
310
                while self.peek_byte()? == Some(b'\\') {
311
                    let Some(raw) = self.read_line()? else {
312
                        return Err(DecodeError::eof());
313
                    };
314
                    lines.push(raw.decode_diff_line(self.take_row_id())?);
315
                }
316
                break;
317
            }
318
            let Some(raw) = self.read_line()? else {
319
                return Err(DecodeError::new(
320
                    0,
321
                    format!(
322
                        "expected '{}' old lines and '{}' new lines, but found '{}' and '{}'",
323
                        header.old_size, header.new_size, old_consumed, new_consumed
324
                    ),
325
                ));
326
            };
327
            let row_id = self.take_row_id();
328
            let parsed = raw.decode_diff_line(row_id)?;
329
330
            match parsed.kind {
331
                DiffLineKind::Context => {
332
                    old_consumed += 1;
333
                    new_consumed += 1;
334
                }
335
                DiffLineKind::Addition => new_consumed += 1,
336
                DiffLineKind::Deletion => old_consumed += 1,
337
                DiffLineKind::NoNewline => {}
338
            }
339
            lines.push(parsed);
340
        }
341
        Ok(Hunk { id, header, lines })
342
    }
343
344
    /// Returns whether unread input remains in the stream.
345
    fn has_more(&mut self) -> Result<bool, DecodeError> {
346
        Ok(!self.reader.fill_buf()?.is_empty())
347
    }
348
349
    /// Returns the next byte without consuming it.
350
    fn peek_byte(&mut self) -> Result<Option<u8>, DecodeError> {
351
        Ok(self.reader.fill_buf()?.first().copied())
352
    }
353
354
    /// Checks whether the next bytes match a required prefix.
355
    fn peek_starts_with(&mut self, prefix: &[u8]) -> Result<bool, DecodeError> {
356
        let buf = self.reader.fill_buf()?;
357
        Ok(buf.len() >= prefix.len() && &buf[..prefix.len()] == prefix)
358
    }
359
360
    /// Reads the next line, stripping trailing line endings.
361
    fn read_line(&mut self) -> Result<Option<ReadLine>, DecodeError> {
362
        let mut buf = String::new();
363
        let n = self.reader.read_line(&mut buf)?;
364
        if n == 0 {
365
            return Ok(None);
366
        }
367
        self.line_no += 1;
368
369
        if buf.ends_with('\n') {
370
            buf.pop();
371
            if buf.ends_with('\r') {
372
                buf.pop();
373
            }
374
        }
375
        Ok(Some(ReadLine {
376
            line_no: self.line_no,
377
            text: buf,
378
        }))
379
    }
380
381
    /// Returns the next row identifier.
382
    fn take_row_id(&mut self) -> RowId {
383
        let id = RowId::new(self.next_row_id);
384
        self.next_row_id += 1;
385
        id
386
    }
387
}
388
389
impl HunkHeader {
390
    /// Decodes one unified diff hunk header line like `@@ -A,B +C,D @@ optional text`.
391
    fn decode_line(line: &str) -> Result<Self, DecodeError> {
392
        let rest = line
393
            .strip_prefix("@@ -")
394
            .ok_or_else(|| DecodeError::new(0, "hunk header must start with '@@ -'"))?;
395
        let (old, rest) = rest
396
            .split_once(" +")
397
            .ok_or_else(|| DecodeError::new(0, "hunk header is missing new-file range"))?;
398
        let (new, text) = rest
399
            .split_once(" @@")
400
            .ok_or_else(|| DecodeError::new(0, "hunk header is missing closing '@@'"))?;
401
        let (old_line_no, old_size) = Self::decode_range(old)?;
402
        let (new_line_no, new_size) = Self::decode_range(new)?;
403
404
        Ok(Self {
405
            old_line_no,
406
            old_size,
407
            new_line_no,
408
            new_size,
409
            text: text.strip_prefix(' ').unwrap_or(text).to_owned(),
410
        })
411
    }
412
413
    /// Decodes a unified diff range into a start and size pair.
414
    fn decode_range(input: &str) -> Result<(u32, u32), DecodeError> {
415
        let (line, size) = input.split_once(',').unwrap_or((input, "1"));
416
        Ok((line.parse()?, size.parse()?))
417
    }
418
}
419
420
impl ReadLine {
421
    /// Decodes one hunk-body line into a [`DiffLine`] with the given id.
422
    fn decode_diff_line(&self, id: RowId) -> Result<DiffLine, DecodeError> {
423
        if self.text.starts_with('\\') {
424
            if !self.text.starts_with("\\ No newline at end of file") {
425
                return Err(DecodeError::new(
426
                    self.line_no,
427
                    format!("invalid hunk line: {}", self.text),
428
                ));
429
            }
430
            return Ok(DiffLine {
431
                id,
432
                kind: DiffLineKind::NoNewline,
433
                text: String::new(),
434
            });
435
        }
436
        let mut chars = self.text.chars();
437
        let marker = chars.next().ok_or_else(|| {
438
            DecodeError::new(self.line_no, format!("invalid hunk line: {}", self.text))
439
        })?;
440
        let text = chars.as_str();
441
        let kind = match marker {
442
            ' ' => DiffLineKind::Context,
443
            '+' => DiffLineKind::Addition,
444
            '-' => DiffLineKind::Deletion,
445
            _ => {
446
                return Err(DecodeError::new(
447
                    self.line_no,
448
                    format!("invalid hunk line: {}", self.text),
449
                ));
450
            }
451
        };
452
        Ok(DiffLine {
453
            id,
454
            kind,
455
            text: text.to_owned(),
456
        })
457
    }
458
}
459
460
/// Decodes Git's C-style path quoting and removes a diff-side prefix.
461
fn decode_git_path(input: &str, prefix: &str) -> PathBuf {
462
    let Some(input) = input
463
        .strip_prefix('"')
464
        .and_then(|input| input.strip_suffix('"'))
465
    else {
466
        return PathBuf::from(input.strip_prefix(prefix).unwrap_or(input));
467
    };
468
    let input = input.as_bytes();
469
    let mut decoded = Vec::with_capacity(input.len());
470
    let mut index = 0;
471
472
    while index < input.len() {
473
        if input[index] != b'\\' {
474
            decoded.push(input[index]);
475
            index += 1;
476
            continue;
477
        }
478
        let Some(escape) = input.get(index + 1).copied() else {
479
            decoded.push(b'\\');
480
            break;
481
        };
482
483
        match escape {
484
            b'a' => decoded.push(b'\x07'),
485
            b'b' => decoded.push(b'\x08'),
486
            b't' => decoded.push(b'\t'),
487
            b'n' => decoded.push(b'\n'),
488
            b'v' => decoded.push(b'\x0b'),
489
            b'f' => decoded.push(b'\x0c'),
490
            b'r' => decoded.push(b'\r'),
491
            b'\\' | b'"' => decoded.push(escape),
492
            b'0'..=b'7' => {
493
                let mut value = 0;
494
                let mut digits = 0;
495
                while digits < 3
496
                    && let Some(digit @ b'0'..=b'7') = input.get(index + 1 + digits).copied()
497
                {
498
                    value = value * 8 + (digit - b'0');
499
                    digits += 1;
500
                }
501
                decoded.push(value);
502
                index += digits - 1;
503
            }
504
            _ => {
505
                decoded.push(b'\\');
506
                decoded.push(escape);
507
            }
508
        }
509
        index += 2;
510
    }
511
512
    if decoded.starts_with(prefix.as_bytes()) {
513
        drop(decoded.drain(..prefix.len()));
514
    }
515
516
    #[cfg(unix)]
517
    {
518
        use std::os::unix::ffi::OsStringExt as _;
519
520
        PathBuf::from(std::ffi::OsString::from_vec(decoded))
521
    }
522
    #[cfg(not(unix))]
523
    {
524
        PathBuf::from(String::from_utf8_lossy(&decoded).into_owned())
525
    }
526
}
527
528
/// Parses a full object id and accepts abbreviated hex ids as unavailable.
529
fn parse_index_oid(
530
    input: &str,
531
    line_no: usize,
532
    description: &'static str,
533
) -> Result<Option<Oid>, DecodeError> {
534
    match Oid::from_str(input) {
535
        Ok(oid) => Ok(Some(oid)),
536
        Err(_) if is_abbreviated_oid(input) => Ok(None),
537
        Err(_) => Err(DecodeError::new(line_no, format!("invalid {description}"))),
538
    }
539
}
540
541
/// Returns whether `input` is a syntactically valid abbreviated object id.
542
fn is_abbreviated_oid(input: &str) -> bool {
543
    !input.is_empty()
544
        && input.len() < FULL_OBJECT_ID_HEX_LEN
545
        && input.bytes().all(|byte| byte.is_ascii_hexdigit())
546
}
547
548
#[cfg(test)]
549
mod tests {
550
    use super::*;
551
552
    #[test]
553
    fn parses_preamble_and_modified_hunk() {
554
        let doc = DiffDocument::decode_str(
555
            "\
556
commit 1234567890abcdef1234567890abcdef12345678
557
Author: A
558
559
diff --git a/a.rs b/a.rs
560
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
561
--- a/a.rs
562
+++ b/a.rs
563
@@ -1 +1 @@
564
-old
565
+new
566
\\ No newline at end of file
567
",
568
        )
569
        .expect("diff parses");
570
571
        let commit = doc.commit.as_ref().expect("preamble parsed");
572
        assert_eq!(
573
            commit.hash.to_string(),
574
            "1234567890abcdef1234567890abcdef12345678"
575
        );
576
        assert_eq!(commit.header("Author"), Some("A"));
577
        assert!(commit.message.is_empty());
578
        assert_eq!(doc.files.len(), 1);
579
        assert_eq!(doc.files[0].header.kind, FileKind::Modified);
580
        assert_eq!(
581
            doc.files[0].header.old_oid.map(|oid| oid.to_string()),
582
            Some("1111111111111111111111111111111111111111".to_owned())
583
        );
584
        assert_eq!(
585
            doc.files[0].header.new_oid.map(|oid| oid.to_string()),
586
            Some("2222222222222222222222222222222222222222".to_owned())
587
        );
588
        assert_eq!(doc.files[0].hunks[0].header.old_line_no, 1);
589
        assert_eq!(doc.files[0].hunks[0].lines[0].kind, DiffLineKind::Deletion);
590
        assert_eq!(doc.files[0].hunks[0].lines[1].kind, DiffLineKind::Addition);
591
        assert_eq!(doc.files[0].hunks[0].lines[2].kind, DiffLineKind::NoNewline);
592
    }
593
594
    #[test]
595
    fn parses_added_deleted_renamed_copied_mode_and_binary_files() {
596
        let doc = DiffDocument::decode_str(
597
            "\
598
diff --git a/new.rs b/new.rs
599
new file mode 100644
600
index 0000000000000000000000000000000000000000..1111111111111111111111111111111111111111
601
--- /dev/null
602
+++ b/new.rs
603
@@ -0,0 +1 @@
604
+new
605
diff --git a/old.rs b/old.rs
606
deleted file mode 100644
607
index 1111111111111111111111111111111111111111..0000000000000000000000000000000000000000
608
--- a/old.rs
609
+++ /dev/null
610
@@ -1 +0,0 @@
611
-old
612
diff --git a/from.rs b/to.rs
613
similarity index 100%
614
rename from from.rs
615
rename to to.rs
616
diff --git a/copy.rs b/copy2.rs
617
similarity index 100%
618
copy from copy.rs
619
copy to copy2.rs
620
diff --git a/mode.sh b/mode.sh
621
old mode 100644
622
new mode 100755
623
diff --git a/image.png b/image.png
624
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
625
Binary files a/image.png and b/image.png differ
626
",
627
        )
628
        .expect("diff parses");
629
630
        let kinds = doc
631
            .files
632
            .iter()
633
            .map(|file| file.header.kind)
634
            .collect::<Vec<_>>();
635
        assert_eq!(
636
            kinds,
637
            vec![
638
                FileKind::Added,
639
                FileKind::Deleted,
640
                FileKind::Renamed,
641
                FileKind::Copied,
642
                FileKind::ModeChanged,
643
                FileKind::Binary,
644
            ]
645
        );
646
        assert_eq!(doc.files[2].header.old_path, Some(PathBuf::from("from.rs")));
647
        assert_eq!(doc.files[2].header.new_path, Some(PathBuf::from("to.rs")));
648
        assert_eq!(doc.files[4].header.old_mode, Some(FileMode::Blob));
649
        assert_eq!(doc.files[4].header.new_mode, Some(FileMode::BlobExecutable));
650
        assert_eq!(doc.files[5].hunks.len(), 1);
651
        assert!(doc.files[5].hunks[0].lines.is_empty());
652
    }
653
654
    #[test]
655
    fn decodes_git_quoted_paths() {
656
        let doc = DiffDocument::decode_str(
657
            r#"diff --git "a/modified caf\303\251\t\"slash\\.rs" "b/modified caf\303\251\t\"slash\\.rs"
658
index 438999b..4c0acd2 100644
659
--- "a/modified caf\303\251\t\"slash\\.rs"	
660
+++ "b/modified caf\303\251\t\"slash\\.rs"	
661
@@ -1,2 +1,2 @@
662
-old
663
+new
664
 keep
665
diff --git a/ordinary.rs b/ordinary.rs
666
index 3367afd..3e75765 100644
667
--- a/ordinary.rs
668
+++ b/ordinary.rs
669
@@ -1 +1 @@
670
-old
671
+new
672
diff --git "a/rename from caf\303\251\t\"slash\\.rs" "b/rename to caf\303\251\t\"slash\\.rs"
673
similarity index 100%
674
rename from "rename from caf\303\251\t\"slash\\.rs"
675
rename to "rename to caf\303\251\t\"slash\\.rs"
676
"#,
677
        )
678
        .unwrap();
679
680
        assert_eq!(
681
            doc.files[0].header.old_path,
682
            Some(PathBuf::from("modified café\t\"slash\\.rs"))
683
        );
684
        assert_eq!(
685
            doc.files[0].header.new_path,
686
            Some(PathBuf::from("modified café\t\"slash\\.rs"))
687
        );
688
        assert_eq!(
689
            doc.files[1].header.old_path,
690
            Some(PathBuf::from("ordinary.rs"))
691
        );
692
        assert_eq!(
693
            doc.files[1].header.new_path,
694
            Some(PathBuf::from("ordinary.rs"))
695
        );
696
        assert_eq!(
697
            doc.files[2].header.old_path,
698
            Some(PathBuf::from("rename from café\t\"slash\\.rs"))
699
        );
700
        assert_eq!(
701
            doc.files[2].header.new_path,
702
            Some(PathBuf::from("rename to café\t\"slash\\.rs"))
703
        );
704
    }
705
706
    #[cfg(unix)]
707
    #[test]
708
    fn preserves_non_utf8_bytes_in_git_quoted_paths() {
709
        use std::os::unix::ffi::OsStrExt as _;
710
711
        let doc = DiffDocument::decode_str(
712
            r#"diff --git "a/non-utf8-\377.rs" "b/non-utf8-\377.rs"
713
"#,
714
        )
715
        .expect("diff parses");
716
717
        assert_eq!(
718
            doc.files[0]
719
                .header
720
                .old_path
721
                .as_deref()
722
                .expect("old path")
723
                .as_os_str()
724
                .as_bytes(),
725
            b"non-utf8-\xff.rs"
726
        );
727
        assert_eq!(
728
            doc.files[0]
729
                .header
730
                .new_path
731
                .as_deref()
732
                .expect("new path")
733
                .as_os_str()
734
                .as_bytes(),
735
            b"non-utf8-\xff.rs"
736
        );
737
    }
738
739
    #[test]
740
    fn parses_hunk_header_default_sizes() {
741
        let header = HunkHeader::decode_line("@@ -7 +8 @@ fn main").expect("header parses");
742
743
        assert_eq!(header.old_line_no, 7);
744
        assert_eq!(header.old_size, 1);
745
        assert_eq!(header.new_line_no, 8);
746
        assert_eq!(header.new_size, 1);
747
        assert_eq!(header.text, "fn main");
748
    }
749
750
    #[test]
751
    fn decode_via_bufread_matches_zero_copy_parse() {
752
        let input = "\
753
diff --git a/a b/a
754
@@ -1 +1 @@
755
-old
756
+new
757
";
758
        let from_str = DiffDocument::decode_str(input).expect("zero-copy parse");
759
        let from_bytes = DiffDocument::decode_bytes(input.as_bytes()).expect("bufread decode");
760
761
        assert_eq!(from_str, from_bytes);
762
    }
763
764
    #[test]
765
    fn reports_invalid_hunk_lines() {
766
        let error = DiffDocument::decode_str(
767
            "\
768
diff --git a/a b/a
769
@@ -1 +1 @@
770
?bad
771
",
772
        )
773
        .expect_err("invalid hunk line is rejected");
774
775
        assert_eq!(error.line, 3);
776
        assert!(error.message.contains("invalid hunk line"));
777
        assert!(!error.is_eof());
778
    }
779
780
    #[test]
781
    fn reports_invalid_index_object_ids() {
782
        let error = DiffDocument::decode_str(
783
            "\
784
diff --git a/a b/a
785
index not-hex..2222222222222222222222222222222222222222 100644
786
@@ -1 +1 @@
787
-old
788
+new
789
",
790
        )
791
        .expect_err("invalid object id should be rejected");
792
793
        assert_eq!(error.line, 2);
794
        assert_eq!(error.message, "invalid old object id");
795
    }
796
797
    #[test]
798
    fn accepts_abbreviated_index_object_ids() {
799
        let doc = DiffDocument::decode_str(
800
            "\
801
diff --git a/a b/a
802
index 1234567..89abcde 100644
803
@@ -1 +1 @@
804
-old
805
+new
806
",
807
        )
808
        .unwrap();
809
810
        assert_eq!(doc.files.len(), 1);
811
        assert_eq!(doc.files[0].header.old_oid, None);
812
        assert_eq!(doc.files[0].header.new_oid, None);
813
        assert_eq!(doc.files[0].header.old_mode, Some(FileMode::Blob));
814
        assert_eq!(doc.files[0].header.new_mode, Some(FileMode::Blob));
815
        assert_eq!(doc.stats().insertions, 1);
816
        assert_eq!(doc.stats().deletions, 1);
817
    }
818
819
    #[test]
820
    fn try_decode_hunks_one_at_a_time() {
821
        let input = "\
822
@@ -1 +1 @@
823
-old
824
+new
825
@@ -10,2 +10,2 @@ ctx
826
 a
827
-b
828
+c
829
";
830
        let mut reader = io::BufReader::new(input.as_bytes());
831
832
        let first = Hunk::try_decode(&mut reader)
833
            .expect("decodes")
834
            .expect("first hunk present");
835
        assert_eq!(first.header.old_line_no, 1);
836
        assert_eq!(first.lines.len(), 2);
837
838
        let second = Hunk::try_decode(&mut reader)
839
            .expect("decodes")
840
            .expect("second hunk present");
841
        assert_eq!(second.header.old_line_no, 10);
842
        assert_eq!(second.header.text, "ctx");
843
        assert_eq!(second.lines.len(), 3);
844
845
        assert!(
846
            Hunk::try_decode(&mut reader).expect("decodes").is_none(),
847
            "stream should be drained",
848
        );
849
    }
850
851
    #[test]
852
    fn try_decode_returns_none_on_empty_input() {
853
        let mut empty = io::BufReader::new(&[][..]);
854
        assert!(FileDiff::try_decode(&mut empty).expect("eof").is_none());
855
        let mut empty = io::BufReader::new(&[][..]);
856
        assert!(Hunk::try_decode(&mut empty).expect("eof").is_none());
857
        // An empty stream is a valid (empty) document.
858
        let mut empty = io::BufReader::new(&[][..]);
859
        assert!(
860
            DiffDocument::decode(&mut empty)
861
                .expect("decodes empty")
862
                .is_empty()
863
        );
864
    }
865
866
    #[test]
867
    fn try_decode_distinguishes_eof_from_syntax_error() {
868
        let mut bad = io::BufReader::new(&b"@@ not a hunk header\n"[..]);
869
        let error = Hunk::try_decode(&mut bad).expect_err("syntax error surfaces");
870
        assert!(!error.is_eof());
871
    }
872
873
    #[test]
874
    fn streaming_decode_matches_zero_copy_parse_for_full_document() {
875
        let input = "\
876
commit 1234567890abcdef1234567890abcdef12345678
877
878
diff --git a/a.rs b/a.rs
879
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
880
--- a/a.rs
881
+++ b/a.rs
882
@@ -1 +1 @@
883
-old
884
+new
885
diff --git a/b.rs b/b.rs
886
new file mode 100644
887
index 0000000000000000000000000000000000000000..3333333333333333333333333333333333333333
888
--- /dev/null
889
+++ b/b.rs
890
@@ -0,0 +1 @@
891
+only
892
";
893
        let zero_copy = DiffDocument::decode_str(input).expect("zero-copy parses");
894
        let streamed = {
895
            let mut reader = io::BufReader::new(input.as_bytes());
896
            DiffDocument::decode(&mut reader).expect("stream decodes")
897
        };
898
899
        assert_eq!(zero_copy, streamed);
900
    }
901
902
    #[test]
903
    fn raw_bytes_strip_ansi_before_decoding_document() {
904
        let input = b"\
905
\x1b[33mdiff --git a/a.rs b/a.rs\x1b[m
906
\x1b[33mindex 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\x1b[m
907
\x1b[33m--- a/a.rs\x1b[m
908
\x1b[33m+++ b/a.rs\x1b[m
909
\x1b[35m@@ -1 +1 @@\x1b[m
910
\x1b[31m-old\x1b[m
911
\x1b[32m+new\x1b[m
912
";
913
        let document = DiffDocument::decode_bytes(input).unwrap();
914
915
        assert_eq!(document.files.len(), 1);
916
        assert_eq!(document.stats().insertions, 1);
917
        assert_eq!(document.stats().deletions, 1);
918
    }
919
920
    #[test]
921
    fn hunk_body_uses_header_counts_to_terminate() {
922
        // Body is exactly old_size + new_size = 1 + 2 = 3 line-types.
923
        // After the body, a `\ No newline...` marker must still be consumed.
924
        let input = "\
925
@@ -1 +1,2 @@
926
-old
927
+new
928
+extra
929
\\ No newline at end of file
930
";
931
        let mut reader = io::BufReader::new(input.as_bytes());
932
        let hunk = Hunk::decode(&mut reader).expect("decodes");
933
934
        assert_eq!(hunk.lines.len(), 4);
935
        assert_eq!(hunk.lines[3].kind, DiffLineKind::NoNewline);
936
        assert!(reader.fill_buf().expect("fills").is_empty());
937
    }
938
}