crates/diff/src/document.rs 25.0 KiB raw
1
//! Unified diff document model.
2
//!
3
//! Defines the data tree (`DiffDocument` → `FileDiff` → `Hunk` → `DiffLine`)
4
//! that callers consume. The decoder that produces these values lives in
5
//! [`crate::decode`]; `document` is intentionally model-only.
6
7
pub use rustik_repo::{Oid, OidError};
8
9
use rustik_repo::DiffStat;
10
use std::fmt;
11
use std::io;
12
use std::num::ParseIntError;
13
use std::path::PathBuf;
14
15
/// Stable identifier for a file section in one diff document.
16
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
17
pub struct FileId(usize);
18
19
/// Stable identifier for a hunk in one diff document.
20
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
21
pub struct HunkId(usize);
22
23
/// Stable identifier for a rendered hunk row in one diff document.
24
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
25
pub struct RowId(usize);
26
27
impl FileId {
28
    /// Wraps a raw index as a [`FileId`].
29
    pub const fn new(index: usize) -> Self {
30
        Self(index)
31
    }
32
}
33
34
impl HunkId {
35
    /// Wraps a raw index as a [`HunkId`].
36
    pub const fn new(index: usize) -> Self {
37
        Self(index)
38
    }
39
}
40
41
impl RowId {
42
    /// Wraps a raw index as a [`RowId`].
43
    pub const fn new(index: usize) -> Self {
44
        Self(index)
45
    }
46
}
47
48
impl std::ops::Deref for FileId {
49
    type Target = usize;
50
51
    fn deref(&self) -> &usize {
52
        &self.0
53
    }
54
}
55
56
impl std::ops::Deref for HunkId {
57
    type Target = usize;
58
59
    fn deref(&self) -> &usize {
60
        &self.0
61
    }
62
}
63
64
impl std::ops::Deref for RowId {
65
    type Target = usize;
66
67
    fn deref(&self) -> &usize {
68
        &self.0
69
    }
70
}
71
72
/// A complete unified diff document.
73
#[derive(Clone, Debug, Default, Eq, PartialEq)]
74
pub struct DiffDocument {
75
    /// Commit preamble before the first `diff --git` section, if present.
76
    pub commit: Option<crate::CommitHeader>,
77
    /// File diffs in input order.
78
    pub files: Vec<FileDiff>,
79
}
80
81
/// A single file section in a unified diff.
82
#[derive(Clone, Debug, Eq, PartialEq)]
83
pub struct FileDiff {
84
    /// Stable file identifier.
85
    pub id: FileId,
86
    /// Metadata and raw header lines for this file.
87
    pub header: FileHeader,
88
    /// Hunks in input order.
89
    pub hunks: Vec<Hunk>,
90
}
91
92
/// Metadata lines that introduce a file section in a Git patch.
93
#[derive(Clone, Debug, Eq, PartialEq)]
94
pub struct FileHeader {
95
    /// Classified kind of file change.
96
    pub kind: FileKind,
97
    /// Path on the old side of the diff, when present.
98
    pub old_path: Option<PathBuf>,
99
    /// Path on the new side of the diff, when present.
100
    pub new_path: Option<PathBuf>,
101
    /// File mode on the old side of the diff, when present.
102
    pub old_mode: Option<FileMode>,
103
    /// File mode on the new side of the diff, when present.
104
    pub new_mode: Option<FileMode>,
105
    /// Object id on the old side of the diff, when present.
106
    pub old_oid: Option<Oid>,
107
    /// Object id on the new side of the diff, when present.
108
    pub new_oid: Option<Oid>,
109
    /// Raw header lines preserved for callers that need exact metadata.
110
    pub raw: Vec<String>,
111
}
112
113
/// File mode in a Git diff, parsed from the octal value Git records.
114
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115
pub enum FileMode {
116
    /// Regular file (`100644`).
117
    Blob,
118
    /// Executable regular file (`100755`).
119
    BlobExecutable,
120
    /// Symbolic link (`120000`).
121
    Link,
122
    /// Submodule reference, i.e. a Git commit (`160000`).
123
    Commit,
124
    /// Directory tree (`040000`).
125
    Tree,
126
    /// Any other mode, preserved as the original octal value.
127
    Other(u32),
128
}
129
130
/// Kind of file-level change described by a patch file header.
131
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
132
pub enum FileKind {
133
    /// Existing file content changed.
134
    Modified,
135
    /// New file was added.
136
    Added,
137
    /// Existing file was deleted.
138
    Deleted,
139
    /// Existing file was renamed.
140
    Renamed,
141
    /// Existing file was copied.
142
    Copied,
143
    /// File mode changed without a more specific content kind.
144
    ModeChanged,
145
    /// File contains binary patch data or a binary comparison marker.
146
    Binary,
147
}
148
149
impl FileKind {
150
    /// Returns the compact marker used by diff chrome.
151
    pub const fn marker(self) -> char {
152
        match self {
153
            Self::Added => '⊕',
154
            Self::Deleted => '⊖',
155
            Self::Renamed => '↦',
156
            Self::Copied => '⇉',
157
            Self::Modified | Self::ModeChanged | Self::Binary => '⊙',
158
        }
159
    }
160
}
161
162
/// Aggregate statistics for one [`FileDiff`].
163
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
164
pub struct FileStats {
165
    /// Total addition lines across all hunks in the file.
166
    pub additions: usize,
167
    /// Total deletion lines across all hunks in the file.
168
    pub deletions: usize,
169
}
170
171
/// Aggregate statistics for one [`DiffDocument`].
172
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
173
pub struct Stats {
174
    /// Number of file sections in the document.
175
    pub files_changed: usize,
176
    /// Total addition lines across all files.
177
    pub insertions: usize,
178
    /// Total deletion lines across all files.
179
    pub deletions: usize,
180
}
181
182
impl From<DiffStat> for Stats {
183
    fn from(stats: DiffStat) -> Self {
184
        Self {
185
            files_changed: stats.files_changed,
186
            insertions: stats.insertions,
187
            deletions: stats.deletions,
188
        }
189
    }
190
}
191
192
/// A unified diff hunk and its body lines.
193
#[derive(Clone, Debug, Eq, PartialEq)]
194
pub struct Hunk {
195
    /// Stable hunk identifier.
196
    pub id: HunkId,
197
    /// Parsed hunk header.
198
    pub header: HunkHeader,
199
    /// Lines contained in the hunk body.
200
    pub lines: Vec<DiffLine>,
201
}
202
203
/// Metadata from a unified diff hunk header.
204
///
205
/// Example: `@@ -24,8 +24,6 @@ fn main`.
206
#[derive(Clone, Debug, Default, Eq, PartialEq)]
207
pub struct HunkHeader {
208
    /// Starting line number on the old side of the diff.
209
    pub old_line_no: u32,
210
    /// Number of old-side lines covered by the hunk.
211
    pub old_size: u32,
212
    /// Starting line number on the new side of the diff.
213
    pub new_line_no: u32,
214
    /// Number of new-side lines covered by the hunk.
215
    pub new_size: u32,
216
    /// Optional trailing hunk context text.
217
    pub text: String,
218
}
219
220
/// A single line in a unified diff hunk.
221
#[derive(Clone, Debug, Eq, PartialEq)]
222
pub struct DiffLine {
223
    /// Stable row identifier.
224
    pub id: RowId,
225
    /// Line role inside the hunk.
226
    pub kind: DiffLineKind,
227
    /// Line text without the leading diff marker.
228
    pub text: String,
229
}
230
231
/// Role of a line inside a unified diff hunk.
232
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
233
pub enum DiffLineKind {
234
    /// Unchanged context line.
235
    Context,
236
    /// Added line.
237
    Addition,
238
    /// Deleted line.
239
    Deletion,
240
    /// Marker for a file without a trailing newline.
241
    NoNewline,
242
}
243
244
/// Error produced while decoding a unified diff.
245
#[derive(Clone, Debug, Eq, PartialEq)]
246
pub struct DecodeError {
247
    /// One-based input line number where decoding failed.
248
    pub line: usize,
249
    /// Human-readable failure message.
250
    pub message: String,
251
    /// Whether this error represents a clean end-of-input signal.
252
    is_eof: bool,
253
}
254
255
impl DiffDocument {
256
    /// Returns whether the document contains no changed files.
257
    pub fn is_empty(&self) -> bool {
258
        self.files.is_empty()
259
    }
260
261
    /// Returns the totals of files changed, insertions, and deletions.
262
    pub fn stats(&self) -> Stats {
263
        let mut stats = Stats {
264
            files_changed: self.files.len(),
265
            ..Stats::default()
266
        };
267
        for file in &self.files {
268
            let file_stats = file.stats();
269
            stats.insertions += file_stats.additions;
270
            stats.deletions += file_stats.deletions;
271
        }
272
        stats
273
    }
274
}
275
276
impl FileHeader {
277
    /// Returns whether the header describes binary content.
278
    pub(crate) fn is_binary(&self) -> bool {
279
        self.kind == FileKind::Binary
280
            || self
281
                .raw
282
                .iter()
283
                .any(|line| line.starts_with("Binary files ") || line == "GIT binary patch")
284
    }
285
286
    /// Returns the path callers should usually show for this file.
287
    pub fn display_path(&self) -> Option<&PathBuf> {
288
        self.new_path.as_ref().or(self.old_path.as_ref())
289
    }
290
}
291
292
impl FileMode {
293
    /// Returns the octal mode value Git records on the wire.
294
    pub const fn as_octal(self) -> u32 {
295
        match self {
296
            Self::Blob => 0o100644,
297
            Self::BlobExecutable => 0o100755,
298
            Self::Link => 0o120000,
299
            Self::Commit => 0o160000,
300
            Self::Tree => 0o040000,
301
            Self::Other(value) => value,
302
        }
303
    }
304
305
    /// Builds a [`FileMode`] from an octal value, mapping known modes.
306
    pub const fn from_octal(value: u32) -> Self {
307
        match value {
308
            0o100644 => Self::Blob,
309
            0o100755 => Self::BlobExecutable,
310
            0o120000 => Self::Link,
311
            0o160000 => Self::Commit,
312
            0o040000 => Self::Tree,
313
            other => Self::Other(other),
314
        }
315
    }
316
317
    /// Parses an octal mode token from a Git diff header (e.g. `"100644"`).
318
    pub fn parse(input: &str) -> Option<Self> {
319
        u32::from_str_radix(input.trim(), 8)
320
            .ok()
321
            .map(Self::from_octal)
322
    }
323
}
324
325
impl fmt::Display for FileMode {
326
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327
        write!(f, "{:o}", self.as_octal())
328
    }
329
}
330
331
impl DecodeError {
332
    /// Creates a decode error at a one-based line number.
333
    pub fn new(line: usize, message: impl Into<String>) -> Self {
334
        Self {
335
            line,
336
            message: message.into(),
337
            is_eof: false,
338
        }
339
    }
340
341
    /// Creates an end-of-input error used to signal a clean EOF to streaming
342
    /// callers. [`crate::Decode::try_decode`] turns this into `Ok(None)`.
343
    pub fn eof() -> Self {
344
        Self {
345
            line: 0,
346
            message: "unexpected end of file".to_owned(),
347
            is_eof: true,
348
        }
349
    }
350
351
    /// Returns whether this error represents end of input rather than a
352
    /// malformed patch.
353
    pub fn is_eof(&self) -> bool {
354
        self.is_eof
355
    }
356
357
    /// Returns a copy of this error with a line number when the error has none.
358
    pub(crate) fn at_line(mut self, line: usize) -> Self {
359
        if self.line == 0 {
360
            self.line = line;
361
        }
362
        self
363
    }
364
}
365
366
impl fmt::Display for DecodeError {
367
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368
        if self.line == 0 {
369
            f.write_str(&self.message)
370
        } else {
371
            write!(f, "line {}: {}", self.line, self.message)
372
        }
373
    }
374
}
375
376
impl std::error::Error for DecodeError {}
377
378
impl From<ParseIntError> for DecodeError {
379
    fn from(error: ParseIntError) -> Self {
380
        Self::new(0, error.to_string())
381
    }
382
}
383
384
impl From<io::Error> for DecodeError {
385
    fn from(error: io::Error) -> Self {
386
        Self {
387
            line: 0,
388
            message: error.to_string(),
389
            is_eof: error.kind() == io::ErrorKind::UnexpectedEof,
390
        }
391
    }
392
}
393
394
impl fmt::Display for FileKind {
395
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396
        let name = match self {
397
            Self::Modified => "modified",
398
            Self::Added => "added",
399
            Self::Deleted => "deleted",
400
            Self::Renamed => "renamed",
401
            Self::Copied => "copied",
402
            Self::ModeChanged => "mode changed",
403
            Self::Binary => "binary",
404
        };
405
        f.write_str(name)
406
    }
407
}
408
409
impl DiffLineKind {
410
    /// Returns how many old-side lines this kind contributes to a hunk.
411
    pub const fn old_len(self) -> u32 {
412
        match self {
413
            Self::Context | Self::Deletion => 1,
414
            Self::Addition | Self::NoNewline => 0,
415
        }
416
    }
417
418
    /// Returns how many new-side lines this kind contributes to a hunk.
419
    pub const fn new_len(self) -> u32 {
420
        match self {
421
            Self::Context | Self::Addition => 1,
422
            Self::Deletion | Self::NoNewline => 0,
423
        }
424
    }
425
}
426
427
impl HunkHeader {
428
    /// Returns a copy with old and new line numbers shifted by the deltas.
429
    pub fn shifted(&self, old_delta: i32, new_delta: i32) -> Self {
430
        Self {
431
            old_line_no: Self::add_delta(self.old_line_no, old_delta),
432
            new_line_no: Self::add_delta(self.new_line_no, new_delta),
433
            ..self.clone()
434
        }
435
    }
436
437
    /// Adds a signed delta to an unsigned line number with saturation.
438
    fn add_delta(line: u32, delta: i32) -> u32 {
439
        if delta.is_negative() {
440
            line.saturating_sub(delta.unsigned_abs())
441
        } else {
442
            line.saturating_add(delta.unsigned_abs())
443
        }
444
    }
445
}
446
447
impl Hunk {
448
    /// Returns the number of old-side lines covered by the hunk body.
449
    pub fn old_size(&self) -> u32 {
450
        self.sizes().old
451
    }
452
453
    /// Returns the number of new-side lines covered by the hunk body.
454
    pub fn new_size(&self) -> u32 {
455
        self.sizes().new
456
    }
457
458
    /// Counts addition and deletion lines in this hunk.
459
    pub fn stats(&self) -> FileStats {
460
        let mut stats = FileStats::default();
461
        for line in &self.lines {
462
            match line.kind {
463
                DiffLineKind::Addition => stats.additions += 1,
464
                DiffLineKind::Deletion => stats.deletions += 1,
465
                DiffLineKind::Context | DiffLineKind::NoNewline => {}
466
            }
467
        }
468
        stats
469
    }
470
471
    /// Returns the net line offset introduced by applying this hunk.
472
    pub fn delta(&self) -> i32 {
473
        let sizes = self.sizes();
474
        let new_size = i32::try_from(sizes.new).unwrap_or(i32::MAX);
475
        let old_size = i32::try_from(sizes.old).unwrap_or(i32::MAX);
476
        new_size - old_size
477
    }
478
479
    /// Splits this hunk into context-separated change groups, each with its
480
    /// own recomputed header. Returns `None` when the hunk has fewer than two
481
    /// change groups (nothing to split).
482
    pub fn split(&self) -> Option<impl Iterator<Item = Self> + '_> {
483
        let groups = self.change_groups();
484
        if groups.len() < 2 {
485
            return None;
486
        }
487
        Some((0..groups.len()).map(move |index| {
488
            let group = groups[index];
489
            let start = if index == 0 {
490
                0
491
            } else {
492
                groups[index - 1].split_context_before(group)
493
            };
494
            let end = groups
495
                .get(index + 1)
496
                .map_or(self.lines.len(), |next| group.split_context_before(*next));
497
            self.segment(start, end)
498
        }))
499
    }
500
501
    /// Returns half-open ranges of contiguous non-context lines.
502
    fn change_groups(&self) -> Vec<ChangeGroup> {
503
        let mut groups = Vec::new();
504
        let mut current = None;
505
506
        for (index, line) in self.lines.iter().enumerate() {
507
            if matches!(line.kind, DiffLineKind::Context) {
508
                if let Some(start) = current.take() {
509
                    groups.push(ChangeGroup { start, end: index });
510
                }
511
            } else if current.is_none() {
512
                current = Some(index);
513
            }
514
        }
515
        if let Some(start) = current {
516
            groups.push(ChangeGroup {
517
                start,
518
                end: self.lines.len(),
519
            });
520
        }
521
        groups
522
    }
523
524
    /// Returns one hunk segment with line numbers and sizes recomputed.
525
    fn segment(&self, start: usize, end: usize) -> Self {
526
        let lines = self.lines[start..end].to_vec();
527
        let old_delta = self.lines[..start]
528
            .iter()
529
            .map(|l| l.kind.old_len())
530
            .sum::<u32>();
531
        let new_delta = self.lines[..start]
532
            .iter()
533
            .map(|l| l.kind.new_len())
534
            .sum::<u32>();
535
        let sizes = HunkSizes::from_lines(&lines);
536
537
        Self {
538
            id: self.id,
539
            header: HunkHeader {
540
                old_line_no: self.header.old_line_no.saturating_add(old_delta),
541
                old_size: sizes.old,
542
                new_line_no: self.header.new_line_no.saturating_add(new_delta),
543
                new_size: sizes.new,
544
                text: self.header.text.clone(),
545
            },
546
            lines,
547
        }
548
    }
549
550
    /// Returns old-side and new-side body sizes.
551
    fn sizes(&self) -> HunkSizes {
552
        HunkSizes::from_lines(&self.lines)
553
    }
554
555
    /// Returns a copy identifying the change independently of its context.
556
    ///
557
    /// Context lines are dropped, sizes are recomputed, and the header text is
558
    /// cleared, so the same change produces the same patch text even when its
559
    /// surrounding context or position drifts.
560
    pub fn identity(&self) -> Self {
561
        let lines: Vec<_> = self
562
            .lines
563
            .iter()
564
            .filter(|line| !matches!(line.kind, DiffLineKind::Context))
565
            .cloned()
566
            .collect();
567
        let sizes = HunkSizes::from_lines(&lines);
568
569
        Self {
570
            id: self.id,
571
            header: HunkHeader {
572
                old_line_no: self.header.old_line_no,
573
                old_size: sizes.old,
574
                new_line_no: self.header.new_line_no,
575
                new_size: sizes.new,
576
                text: String::new(),
577
            },
578
            lines,
579
        }
580
    }
581
}
582
583
/// Old-side and new-side line counts for a hunk body.
584
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
585
struct HunkSizes {
586
    /// Old-side line count.
587
    old: u32,
588
    /// New-side line count.
589
    new: u32,
590
}
591
592
impl HunkSizes {
593
    /// Counts old-side and new-side contributions across diff lines.
594
    fn from_lines(lines: &[DiffLine]) -> Self {
595
        let mut sizes = Self::default();
596
        for line in lines {
597
            sizes.old += line.kind.old_len();
598
            sizes.new += line.kind.new_len();
599
        }
600
        sizes
601
    }
602
}
603
604
impl FileDiff {
605
    /// Returns the sum of addition and deletion lines across all hunks.
606
    pub fn stats(&self) -> FileStats {
607
        let mut total = FileStats::default();
608
        for hunk in &self.hunks {
609
            let hunk_stats = hunk.stats();
610
            total.additions += hunk_stats.additions;
611
            total.deletions += hunk_stats.deletions;
612
        }
613
        total
614
    }
615
616
    /// Returns a copy containing only the hunks at the given indexes.
617
    pub fn selected(&self, hunks: impl IntoIterator<Item = usize>) -> Self {
618
        Self {
619
            id: self.id,
620
            header: self.header.clone(),
621
            hunks: hunks
622
                .into_iter()
623
                .filter_map(|ix| self.hunks.get(ix).cloned())
624
                .collect(),
625
        }
626
    }
627
}
628
629
impl DiffDocument {
630
    /// Returns a single-file document with the given hunks, suitable for
631
    /// `git apply`. The preamble is dropped.
632
    pub fn for_hunks(file: &FileDiff, hunks: impl IntoIterator<Item = Hunk>) -> Self {
633
        Self {
634
            commit: None,
635
            files: vec![FileDiff {
636
                id: file.id,
637
                header: file.header.clone(),
638
                hunks: hunks.into_iter().collect(),
639
            }],
640
        }
641
    }
642
643
    /// Splits multi-change hunks into independently reviewable hunks.
644
    ///
645
    /// Hunk ids are reassigned sequentially across the whole document, so the
646
    /// split must run before any per-hunk state is derived for pieces to keep
647
    /// stable identities across reloads.
648
    pub fn split_hunks(mut self) -> Self {
649
        let mut next = 0;
650
        for file in &mut self.files {
651
            let mut hunks = Vec::with_capacity(file.hunks.len());
652
            for hunk in std::mem::take(&mut file.hunks) {
653
                if let Some(split) = hunk.split() {
654
                    for mut hunk in split {
655
                        hunk.id = HunkId::new(next);
656
                        next += 1;
657
                        hunks.push(hunk);
658
                    }
659
                } else {
660
                    let mut hunk = hunk;
661
                    hunk.id = HunkId::new(next);
662
                    next += 1;
663
                    hunks.push(hunk);
664
                }
665
            }
666
            file.hunks = hunks;
667
        }
668
        self
669
    }
670
}
671
672
/// Half-open range of non-context lines inside a hunk.
673
#[derive(Clone, Copy, Debug)]
674
struct ChangeGroup {
675
    /// First changed line index.
676
    start: usize,
677
    /// One past the final changed line index.
678
    end: usize,
679
}
680
681
impl ChangeGroup {
682
    /// Returns the split point in the context before `next`.
683
    const fn split_context_before(self, next: Self) -> usize {
684
        self.end + (next.start - self.end) / 2
685
    }
686
}
687
688
#[cfg(test)]
689
#[allow(clippy::unwrap_used)]
690
mod tests {
691
    use super::*;
692
    use crate::Decode;
693
694
    fn parse_patch(input: &str) -> DiffDocument {
695
        DiffDocument::decode_str(input).unwrap()
696
    }
697
698
    const PATCH: &str = "\
699
diff --git a/a.txt b/a.txt
700
index 7898192789819278981927898192789819278981..6178079617807961780796178079617807961780 100644
701
--- a/a.txt
702
+++ b/a.txt
703
@@ -1,3 +1,4 @@
704
 one
705
+two
706
 three
707
-four
708
+five
709
";
710
711
    #[test]
712
    fn diff_line_kind_counts_old_and_new_contributions() {
713
        assert_eq!(DiffLineKind::Context.old_len(), 1);
714
        assert_eq!(DiffLineKind::Context.new_len(), 1);
715
        assert_eq!(DiffLineKind::Addition.old_len(), 0);
716
        assert_eq!(DiffLineKind::Addition.new_len(), 1);
717
        assert_eq!(DiffLineKind::Deletion.old_len(), 1);
718
        assert_eq!(DiffLineKind::Deletion.new_len(), 0);
719
        assert_eq!(DiffLineKind::NoNewline.old_len(), 0);
720
        assert_eq!(DiffLineKind::NoNewline.new_len(), 0);
721
    }
722
723
    #[test]
724
    fn hunk_recomputes_sizes_from_lines() {
725
        let doc = parse_patch(PATCH);
726
        let hunk = &doc.files[0].hunks[0];
727
728
        assert_eq!(hunk.old_size(), 3);
729
        assert_eq!(hunk.new_size(), 4);
730
        assert_eq!(hunk.delta(), 1);
731
    }
732
733
    #[test]
734
    fn hunk_split_separates_change_groups() {
735
        let doc = parse_patch(PATCH);
736
        let hunk = &doc.files[0].hunks[0];
737
        let split = hunk.split().unwrap().collect::<Vec<_>>();
738
739
        assert_eq!(split.len(), 2);
740
        assert_eq!(split[0].header.old_line_no, 1);
741
        assert_eq!(split[0].header.old_size, 1);
742
        assert_eq!(split[0].header.new_line_no, 1);
743
        assert_eq!(split[0].header.new_size, 2);
744
        assert_eq!(split[1].header.old_line_no, 2);
745
        assert_eq!(split[1].header.old_size, 2);
746
        assert_eq!(split[1].header.new_line_no, 3);
747
        assert_eq!(split[1].header.new_size, 2);
748
    }
749
750
    #[test]
751
    fn hunk_split_returns_none_for_single_change_group() {
752
        let doc = parse_patch(
753
            "\
754
diff --git a/a b/a
755
@@ -1 +1,2 @@
756
 one
757
+two
758
",
759
        );
760
761
        assert!(doc.files[0].hunks[0].split().is_none());
762
    }
763
764
    #[test]
765
    fn hunk_header_shifted_moves_line_numbers() {
766
        let header = HunkHeader::decode_str("@@ -10,3 +20,3 @@").unwrap();
767
        let shifted = header.shifted(2, -3);
768
769
        assert_eq!(shifted.old_line_no, 12);
770
        assert_eq!(shifted.new_line_no, 17);
771
        assert_eq!(shifted.old_size, 3);
772
        assert_eq!(shifted.new_size, 3);
773
    }
774
775
    #[test]
776
    fn file_diff_selected_keeps_only_chosen_hunks() {
777
        let doc = parse_patch(PATCH);
778
        let only = doc.files[0].selected([0]);
779
780
        assert_eq!(only.hunks.len(), 1);
781
        assert_eq!(only.id, doc.files[0].id);
782
    }
783
784
    #[test]
785
    fn document_for_hunks_drops_preamble() {
786
        let with_preamble = format!("commit 1234567890abcdef1234567890abcdef12345678\n\n{PATCH}");
787
        let doc = parse_patch(&with_preamble);
788
        let single = DiffDocument::for_hunks(&doc.files[0], doc.files[0].hunks.clone());
789
790
        assert!(single.commit.is_none());
791
        assert_eq!(single.files.len(), 1);
792
        assert_eq!(single.files[0].hunks.len(), doc.files[0].hunks.len());
793
    }
794
795
    #[test]
796
    fn stats_aggregate_across_hunks_and_files() {
797
        let doc = parse_patch(PATCH);
798
        let hunk_stats = doc.files[0].hunks[0].stats();
799
        let file_stats = doc.files[0].stats();
800
        let doc_stats = doc.stats();
801
802
        assert_eq!(
803
            hunk_stats,
804
            FileStats {
805
                additions: 2,
806
                deletions: 1
807
            }
808
        );
809
        assert_eq!(
810
            file_stats,
811
            FileStats {
812
                additions: 2,
813
                deletions: 1
814
            }
815
        );
816
        assert_eq!(
817
            doc_stats,
818
            Stats {
819
                files_changed: 1,
820
                insertions: 2,
821
                deletions: 1,
822
            }
823
        );
824
    }
825
826
    #[test]
827
    fn file_mode_round_trips_through_octal() {
828
        for mode in [
829
            FileMode::Blob,
830
            FileMode::BlobExecutable,
831
            FileMode::Link,
832
            FileMode::Commit,
833
            FileMode::Tree,
834
            FileMode::Other(0o123456),
835
        ] {
836
            assert_eq!(FileMode::from_octal(mode.as_octal()), mode);
837
            assert_eq!(FileMode::parse(&mode.to_string()), Some(mode));
838
        }
839
        assert_eq!(FileMode::parse("not-octal"), None);
840
    }
841
842
    #[test]
843
    fn oid_parses_hexadecimal_text() {
844
        let oid = "ABC1230000000000000000000000000000000000"
845
            .parse::<Oid>()
846
            .unwrap();
847
848
        assert_eq!(oid.to_string(), "abc1230000000000000000000000000000000000");
849
        assert_eq!("".parse::<Oid>(), Err(OidError));
850
        assert_eq!("not-hex".parse::<Oid>(), Err(OidError));
851
        assert_eq!("ABC123".parse::<Oid>(), Err(OidError));
852
    }
853
854
    #[test]
855
    fn add_delta_saturates_at_zero() {
856
        assert_eq!(HunkHeader::add_delta(5, 3), 8);
857
        assert_eq!(HunkHeader::add_delta(5, -3), 2);
858
        assert_eq!(HunkHeader::add_delta(2, -10), 0);
859
    }
860
}