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