1use std::fmt;
8use std::io;
9use std::num::ParseIntError;
10use std::path::PathBuf;
11use std::str::FromStr;
12
13#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
15pub struct FileId(usize);
16
17#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
19pub struct HunkId(usize);
20
21#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
23pub struct RowId(usize);
24
25#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
27pub struct Oid(String);
28
29impl FileId {
30 pub const fn new(index: usize) -> Self {
32 Self(index)
33 }
34}
35
36impl HunkId {
37 pub const fn new(index: usize) -> Self {
39 Self(index)
40 }
41}
42
43impl RowId {
44 pub const fn new(index: usize) -> Self {
46 Self(index)
47 }
48}
49
50impl Oid {
51 pub fn as_str(&self) -> &str {
53 &self.0
54 }
55}
56
57impl FromStr for Oid {
58 type Err = OidError;
59
60 fn from_str(input: &str) -> Result<Self, Self::Err> {
61 if input.is_empty() {
62 return Err(OidError);
63 }
64 if !input.bytes().all(|byte| byte.is_ascii_hexdigit()) {
65 return Err(OidError);
66 }
67 Ok(Self(input.to_owned()))
68 }
69}
70
71impl fmt::Display for Oid {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 f.write_str(&self.0)
74 }
75}
76
77#[derive(Clone, Copy, Debug, Eq, PartialEq)]
79pub struct OidError;
80
81impl fmt::Display for OidError {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 f.write_str("object id must be non-empty hexadecimal text")
84 }
85}
86
87impl std::error::Error for OidError {}
88
89impl std::ops::Deref for FileId {
90 type Target = usize;
91
92 fn deref(&self) -> &usize {
93 &self.0
94 }
95}
96
97impl std::ops::Deref for HunkId {
98 type Target = usize;
99
100 fn deref(&self) -> &usize {
101 &self.0
102 }
103}
104
105impl std::ops::Deref for RowId {
106 type Target = usize;
107
108 fn deref(&self) -> &usize {
109 &self.0
110 }
111}
112
113#[derive(Clone, Debug, Default, Eq, PartialEq)]
115pub struct DiffDocument {
116 pub commit: Option<crate::Commit>,
118 pub files: Vec<FileDiff>,
120}
121
122#[derive(Clone, Debug, Eq, PartialEq)]
124pub struct FileDiff {
125 pub id: FileId,
127 pub header: FileHeader,
129 pub hunks: Vec<Hunk>,
131}
132
133#[derive(Clone, Debug, Eq, PartialEq)]
135pub struct FileHeader {
136 pub kind: FileKind,
138 pub old_path: Option<PathBuf>,
140 pub new_path: Option<PathBuf>,
142 pub old_mode: Option<FileMode>,
144 pub new_mode: Option<FileMode>,
146 pub old_oid: Option<Oid>,
148 pub new_oid: Option<Oid>,
150 pub raw: Vec<String>,
152}
153
154#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
156pub enum FileMode {
157 Blob,
159 BlobExecutable,
161 Link,
163 Commit,
165 Tree,
167 Other(u32),
169}
170
171#[derive(Clone, Copy, Debug, Eq, PartialEq)]
173pub enum FileKind {
174 Modified,
176 Added,
178 Deleted,
180 Renamed,
182 Copied,
184 ModeChanged,
186 Binary,
188}
189
190impl FileKind {
191 pub const fn marker(self) -> char {
193 match self {
194 Self::Added => '⊕',
195 Self::Deleted => '⊖',
196 Self::Renamed => '↦',
197 Self::Copied => '⇉',
198 Self::Modified | Self::ModeChanged | Self::Binary => '⊙',
199 }
200 }
201}
202
203#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
205pub struct FileStats {
206 pub additions: usize,
208 pub deletions: usize,
210}
211
212#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
214pub struct Stats {
215 pub files_changed: usize,
217 pub insertions: usize,
219 pub deletions: usize,
221}
222
223#[derive(Clone, Debug, Eq, PartialEq)]
225pub struct Hunk {
226 pub id: HunkId,
228 pub header: HunkHeader,
230 pub lines: Vec<DiffLine>,
232}
233
234#[derive(Clone, Debug, Default, Eq, PartialEq)]
238pub struct HunkHeader {
239 pub old_line_no: u32,
241 pub old_size: u32,
243 pub new_line_no: u32,
245 pub new_size: u32,
247 pub text: String,
249}
250
251#[derive(Clone, Debug, Eq, PartialEq)]
253pub struct DiffLine {
254 pub id: RowId,
256 pub kind: DiffLineKind,
258 pub text: String,
260}
261
262#[derive(Clone, Copy, Debug, Eq, PartialEq)]
264pub enum DiffLineKind {
265 Context,
267 Addition,
269 Deletion,
271 NoNewline,
273}
274
275#[derive(Clone, Debug, Eq, PartialEq)]
277pub struct DecodeError {
278 pub line: usize,
280 pub message: String,
282 is_eof: bool,
284}
285
286impl DiffDocument {
287 pub fn is_empty(&self) -> bool {
289 self.files.is_empty()
290 }
291
292 pub fn stats(&self) -> Stats {
294 let mut stats = Stats {
295 files_changed: self.files.len(),
296 ..Stats::default()
297 };
298 for file in &self.files {
299 let file_stats = file.stats();
300 stats.insertions += file_stats.additions;
301 stats.deletions += file_stats.deletions;
302 }
303 stats
304 }
305}
306
307impl FileHeader {
308 pub fn display_path(&self) -> Option<&PathBuf> {
310 self.new_path.as_ref().or(self.old_path.as_ref())
311 }
312}
313
314impl FileMode {
315 pub const fn as_octal(self) -> u32 {
317 match self {
318 Self::Blob => 0o100644,
319 Self::BlobExecutable => 0o100755,
320 Self::Link => 0o120000,
321 Self::Commit => 0o160000,
322 Self::Tree => 0o040000,
323 Self::Other(value) => value,
324 }
325 }
326
327 pub const fn from_octal(value: u32) -> Self {
329 match value {
330 0o100644 => Self::Blob,
331 0o100755 => Self::BlobExecutable,
332 0o120000 => Self::Link,
333 0o160000 => Self::Commit,
334 0o040000 => Self::Tree,
335 other => Self::Other(other),
336 }
337 }
338
339 pub fn parse(input: &str) -> Option<Self> {
341 u32::from_str_radix(input.trim(), 8)
342 .ok()
343 .map(Self::from_octal)
344 }
345}
346
347impl fmt::Display for FileMode {
348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
349 write!(f, "{:o}", self.as_octal())
350 }
351}
352
353impl DecodeError {
354 pub fn new(line: usize, message: impl Into<String>) -> Self {
356 Self {
357 line,
358 message: message.into(),
359 is_eof: false,
360 }
361 }
362
363 pub fn eof() -> Self {
366 Self {
367 line: 0,
368 message: "unexpected end of file".to_owned(),
369 is_eof: true,
370 }
371 }
372
373 pub fn is_eof(&self) -> bool {
376 self.is_eof
377 }
378
379 pub(crate) fn at_line(mut self, line: usize) -> Self {
381 if self.line == 0 {
382 self.line = line;
383 }
384 self
385 }
386}
387
388impl fmt::Display for DecodeError {
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 if self.line == 0 {
391 f.write_str(&self.message)
392 } else {
393 write!(f, "line {}: {}", self.line, self.message)
394 }
395 }
396}
397
398impl std::error::Error for DecodeError {}
399
400impl From<ParseIntError> for DecodeError {
401 fn from(error: ParseIntError) -> Self {
402 Self::new(0, error.to_string())
403 }
404}
405
406impl From<io::Error> for DecodeError {
407 fn from(error: io::Error) -> Self {
408 Self {
409 line: 0,
410 message: error.to_string(),
411 is_eof: error.kind() == io::ErrorKind::UnexpectedEof,
412 }
413 }
414}
415
416impl fmt::Display for FileKind {
417 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418 let name = match self {
419 Self::Modified => "modified",
420 Self::Added => "added",
421 Self::Deleted => "deleted",
422 Self::Renamed => "renamed",
423 Self::Copied => "copied",
424 Self::ModeChanged => "mode changed",
425 Self::Binary => "binary",
426 };
427 f.write_str(name)
428 }
429}
430
431impl DiffLineKind {
432 pub const fn old_len(self) -> u32 {
434 match self {
435 Self::Context | Self::Deletion => 1,
436 Self::Addition | Self::NoNewline => 0,
437 }
438 }
439
440 pub const fn new_len(self) -> u32 {
442 match self {
443 Self::Context | Self::Addition => 1,
444 Self::Deletion | Self::NoNewline => 0,
445 }
446 }
447}
448
449impl HunkHeader {
450 pub fn shifted(&self, old_delta: i32, new_delta: i32) -> Self {
452 Self {
453 old_line_no: Self::add_delta(self.old_line_no, old_delta),
454 new_line_no: Self::add_delta(self.new_line_no, new_delta),
455 ..self.clone()
456 }
457 }
458
459 fn add_delta(line: u32, delta: i32) -> u32 {
461 if delta.is_negative() {
462 line.saturating_sub(delta.unsigned_abs())
463 } else {
464 line.saturating_add(delta.unsigned_abs())
465 }
466 }
467}
468
469impl Hunk {
470 pub fn old_size(&self) -> u32 {
472 self.sizes().old
473 }
474
475 pub fn new_size(&self) -> u32 {
477 self.sizes().new
478 }
479
480 pub fn stats(&self) -> FileStats {
482 let mut stats = FileStats::default();
483 for line in &self.lines {
484 match line.kind {
485 DiffLineKind::Addition => stats.additions += 1,
486 DiffLineKind::Deletion => stats.deletions += 1,
487 DiffLineKind::Context | DiffLineKind::NoNewline => {}
488 }
489 }
490 stats
491 }
492
493 pub fn delta(&self) -> i32 {
495 let sizes = self.sizes();
496 let new_size = i32::try_from(sizes.new).unwrap_or(i32::MAX);
497 let old_size = i32::try_from(sizes.old).unwrap_or(i32::MAX);
498 new_size - old_size
499 }
500
501 pub fn split(&self) -> Option<impl Iterator<Item = Self> + '_> {
505 let groups = self.change_groups();
506 if groups.len() < 2 {
507 return None;
508 }
509 Some((0..groups.len()).map(move |index| {
510 let group = groups[index];
511 let start = if index == 0 {
512 0
513 } else {
514 groups[index - 1].split_context_before(group)
515 };
516 let end = groups
517 .get(index + 1)
518 .map_or(self.lines.len(), |next| group.split_context_before(*next));
519 self.segment(start, end)
520 }))
521 }
522
523 fn change_groups(&self) -> Vec<ChangeGroup> {
525 let mut groups = Vec::new();
526 let mut current = None;
527
528 for (index, line) in self.lines.iter().enumerate() {
529 if matches!(line.kind, DiffLineKind::Context) {
530 if let Some(start) = current.take() {
531 groups.push(ChangeGroup { start, end: index });
532 }
533 } else if current.is_none() {
534 current = Some(index);
535 }
536 }
537 if let Some(start) = current {
538 groups.push(ChangeGroup {
539 start,
540 end: self.lines.len(),
541 });
542 }
543 groups
544 }
545
546 fn segment(&self, start: usize, end: usize) -> Self {
548 let lines = self.lines[start..end].to_vec();
549 let old_delta = self.lines[..start]
550 .iter()
551 .map(|l| l.kind.old_len())
552 .sum::<u32>();
553 let new_delta = self.lines[..start]
554 .iter()
555 .map(|l| l.kind.new_len())
556 .sum::<u32>();
557 let sizes = HunkSizes::from_lines(&lines);
558
559 Self {
560 id: self.id,
561 header: HunkHeader {
562 old_line_no: self.header.old_line_no.saturating_add(old_delta),
563 old_size: sizes.old,
564 new_line_no: self.header.new_line_no.saturating_add(new_delta),
565 new_size: sizes.new,
566 text: self.header.text.clone(),
567 },
568 lines,
569 }
570 }
571
572 fn sizes(&self) -> HunkSizes {
574 HunkSizes::from_lines(&self.lines)
575 }
576}
577
578#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
580struct HunkSizes {
581 old: u32,
583 new: u32,
585}
586
587impl HunkSizes {
588 fn from_lines(lines: &[DiffLine]) -> Self {
590 let mut sizes = Self::default();
591 for line in lines {
592 sizes.old += line.kind.old_len();
593 sizes.new += line.kind.new_len();
594 }
595 sizes
596 }
597}
598
599impl FileDiff {
600 pub fn stats(&self) -> FileStats {
602 let mut total = FileStats::default();
603 for hunk in &self.hunks {
604 let hunk_stats = hunk.stats();
605 total.additions += hunk_stats.additions;
606 total.deletions += hunk_stats.deletions;
607 }
608 total
609 }
610
611 pub fn selected(&self, hunks: impl IntoIterator<Item = usize>) -> Self {
613 Self {
614 id: self.id,
615 header: self.header.clone(),
616 hunks: hunks
617 .into_iter()
618 .filter_map(|ix| self.hunks.get(ix).cloned())
619 .collect(),
620 }
621 }
622}
623
624impl DiffDocument {
625 pub fn for_hunks(file: &FileDiff, hunks: impl IntoIterator<Item = Hunk>) -> Self {
628 Self {
629 commit: None,
630 files: vec![FileDiff {
631 id: file.id,
632 header: file.header.clone(),
633 hunks: hunks.into_iter().collect(),
634 }],
635 }
636 }
637}
638
639#[derive(Clone, Copy, Debug)]
641struct ChangeGroup {
642 start: usize,
644 end: usize,
646}
647
648impl ChangeGroup {
649 const fn split_context_before(self, next: Self) -> usize {
651 self.end + (next.start - self.end) / 2
652 }
653}
654
655#[cfg(test)]
656#[allow(clippy::unwrap_used)]
657mod tests {
658 use super::*;
659 use crate::Decode;
660
661 fn parse_patch(input: &str) -> DiffDocument {
662 DiffDocument::decode_str(input).unwrap()
663 }
664
665 const PATCH: &str = "\
666diff --git a/a.txt b/a.txt
667index 7898192..6178079 100644
668--- a/a.txt
669+++ b/a.txt
670@@ -1,3 +1,4 @@
671 one
672+two
673 three
674-four
675+five
676";
677
678 #[test]
679 fn diff_line_kind_counts_old_and_new_contributions() {
680 assert_eq!(DiffLineKind::Context.old_len(), 1);
681 assert_eq!(DiffLineKind::Context.new_len(), 1);
682 assert_eq!(DiffLineKind::Addition.old_len(), 0);
683 assert_eq!(DiffLineKind::Addition.new_len(), 1);
684 assert_eq!(DiffLineKind::Deletion.old_len(), 1);
685 assert_eq!(DiffLineKind::Deletion.new_len(), 0);
686 assert_eq!(DiffLineKind::NoNewline.old_len(), 0);
687 assert_eq!(DiffLineKind::NoNewline.new_len(), 0);
688 }
689
690 #[test]
691 fn hunk_recomputes_sizes_from_lines() {
692 let doc = parse_patch(PATCH);
693 let hunk = &doc.files[0].hunks[0];
694
695 assert_eq!(hunk.old_size(), 3);
696 assert_eq!(hunk.new_size(), 4);
697 assert_eq!(hunk.delta(), 1);
698 }
699
700 #[test]
701 fn hunk_split_separates_change_groups() {
702 let doc = parse_patch(PATCH);
703 let hunk = &doc.files[0].hunks[0];
704 let split = hunk.split().unwrap().collect::<Vec<_>>();
705
706 assert_eq!(split.len(), 2);
707 assert_eq!(split[0].header.old_line_no, 1);
708 assert_eq!(split[0].header.old_size, 1);
709 assert_eq!(split[0].header.new_line_no, 1);
710 assert_eq!(split[0].header.new_size, 2);
711 assert_eq!(split[1].header.old_line_no, 2);
712 assert_eq!(split[1].header.old_size, 2);
713 assert_eq!(split[1].header.new_line_no, 3);
714 assert_eq!(split[1].header.new_size, 2);
715 }
716
717 #[test]
718 fn hunk_split_returns_none_for_single_change_group() {
719 let doc = parse_patch(
720 "\
721diff --git a/a b/a
722@@ -1 +1,2 @@
723 one
724+two
725",
726 );
727
728 assert!(doc.files[0].hunks[0].split().is_none());
729 }
730
731 #[test]
732 fn hunk_header_shifted_moves_line_numbers() {
733 let header = HunkHeader::decode_str("@@ -10,3 +20,3 @@").unwrap();
734 let shifted = header.shifted(2, -3);
735
736 assert_eq!(shifted.old_line_no, 12);
737 assert_eq!(shifted.new_line_no, 17);
738 assert_eq!(shifted.old_size, 3);
739 assert_eq!(shifted.new_size, 3);
740 }
741
742 #[test]
743 fn file_diff_selected_keeps_only_chosen_hunks() {
744 let doc = parse_patch(PATCH);
745 let only = doc.files[0].selected([0]);
746
747 assert_eq!(only.hunks.len(), 1);
748 assert_eq!(only.id, doc.files[0].id);
749 }
750
751 #[test]
752 fn document_for_hunks_drops_preamble() {
753 let with_preamble = format!("commit abc\n\n{PATCH}");
754 let doc = parse_patch(&with_preamble);
755 let single = DiffDocument::for_hunks(&doc.files[0], doc.files[0].hunks.clone());
756
757 assert!(single.commit.is_none());
758 assert_eq!(single.files.len(), 1);
759 assert_eq!(single.files[0].hunks.len(), doc.files[0].hunks.len());
760 }
761
762 #[test]
763 fn stats_aggregate_across_hunks_and_files() {
764 let doc = parse_patch(PATCH);
765 let hunk_stats = doc.files[0].hunks[0].stats();
766 let file_stats = doc.files[0].stats();
767 let doc_stats = doc.stats();
768
769 assert_eq!(
770 hunk_stats,
771 FileStats {
772 additions: 2,
773 deletions: 1
774 }
775 );
776 assert_eq!(
777 file_stats,
778 FileStats {
779 additions: 2,
780 deletions: 1
781 }
782 );
783 assert_eq!(
784 doc_stats,
785 Stats {
786 files_changed: 1,
787 insertions: 2,
788 deletions: 1,
789 }
790 );
791 }
792
793 #[test]
794 fn file_mode_round_trips_through_octal() {
795 for mode in [
796 FileMode::Blob,
797 FileMode::BlobExecutable,
798 FileMode::Link,
799 FileMode::Commit,
800 FileMode::Tree,
801 FileMode::Other(0o123456),
802 ] {
803 assert_eq!(FileMode::from_octal(mode.as_octal()), mode);
804 assert_eq!(FileMode::parse(&mode.to_string()), Some(mode));
805 }
806 assert_eq!(FileMode::parse("not-octal"), None);
807 }
808
809 #[test]
810 fn oid_parses_hexadecimal_text() {
811 let oid = Oid::from_str("ABC123").unwrap();
812
813 assert_eq!(oid.as_str(), "ABC123");
814 assert_eq!(oid.to_string(), "ABC123");
815 assert_eq!("".parse::<Oid>(), Err(OidError));
816 assert_eq!("not-hex".parse::<Oid>(), Err(OidError));
817 }
818
819 #[test]
820 fn add_delta_saturates_at_zero() {
821 assert_eq!(HunkHeader::add_delta(5, 3), 8);
822 assert_eq!(HunkHeader::add_delta(5, -3), 2);
823 assert_eq!(HunkHeader::add_delta(2, -10), 0);
824 }
825}