1pub use rustik_repo::{Oid, OidError};
8
9use rustik_repo::DiffStat;
10use std::fmt;
11use std::io;
12use std::num::ParseIntError;
13use std::path::PathBuf;
14
15#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
17pub struct FileId(usize);
18
19#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
21pub struct HunkId(usize);
22
23#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
25pub struct RowId(usize);
26
27impl FileId {
28 pub const fn new(index: usize) -> Self {
30 Self(index)
31 }
32}
33
34impl HunkId {
35 pub const fn new(index: usize) -> Self {
37 Self(index)
38 }
39}
40
41impl RowId {
42 pub const fn new(index: usize) -> Self {
44 Self(index)
45 }
46}
47
48impl std::ops::Deref for FileId {
49 type Target = usize;
50
51 fn deref(&self) -> &usize {
52 &self.0
53 }
54}
55
56impl std::ops::Deref for HunkId {
57 type Target = usize;
58
59 fn deref(&self) -> &usize {
60 &self.0
61 }
62}
63
64impl std::ops::Deref for RowId {
65 type Target = usize;
66
67 fn deref(&self) -> &usize {
68 &self.0
69 }
70}
71
72#[derive(Clone, Debug, Default, Eq, PartialEq)]
74pub struct DiffDocument {
75 pub commit: Option<crate::CommitHeader>,
77 pub files: Vec<FileDiff>,
79}
80
81#[derive(Clone, Debug, Eq, PartialEq)]
83pub struct FileDiff {
84 pub id: FileId,
86 pub header: FileHeader,
88 pub hunks: Vec<Hunk>,
90}
91
92#[derive(Clone, Debug, Eq, PartialEq)]
94pub struct FileHeader {
95 pub kind: FileKind,
97 pub old_path: Option<PathBuf>,
99 pub new_path: Option<PathBuf>,
101 pub old_mode: Option<FileMode>,
103 pub new_mode: Option<FileMode>,
105 pub old_oid: Option<Oid>,
107 pub new_oid: Option<Oid>,
109 pub raw: Vec<String>,
111}
112
113#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115pub enum FileMode {
116 Blob,
118 BlobExecutable,
120 Link,
122 Commit,
124 Tree,
126 Other(u32),
128}
129
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
132pub enum FileKind {
133 Modified,
135 Added,
137 Deleted,
139 Renamed,
141 Copied,
143 ModeChanged,
145 Binary,
147}
148
149impl FileKind {
150 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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
164pub struct FileStats {
165 pub additions: usize,
167 pub deletions: usize,
169}
170
171#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
173pub struct Stats {
174 pub files_changed: usize,
176 pub insertions: usize,
178 pub deletions: usize,
180}
181
182impl 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#[derive(Clone, Debug, Eq, PartialEq)]
194pub struct Hunk {
195 pub id: HunkId,
197 pub header: HunkHeader,
199 pub lines: Vec<DiffLine>,
201}
202
203#[derive(Clone, Debug, Default, Eq, PartialEq)]
207pub struct HunkHeader {
208 pub old_line_no: u32,
210 pub old_size: u32,
212 pub new_line_no: u32,
214 pub new_size: u32,
216 pub text: String,
218}
219
220#[derive(Clone, Debug, Eq, PartialEq)]
222pub struct DiffLine {
223 pub id: RowId,
225 pub kind: DiffLineKind,
227 pub text: String,
229}
230
231#[derive(Clone, Copy, Debug, Eq, PartialEq)]
233pub enum DiffLineKind {
234 Context,
236 Addition,
238 Deletion,
240 NoNewline,
242}
243
244#[derive(Clone, Debug, Eq, PartialEq)]
246pub struct DecodeError {
247 pub line: usize,
249 pub message: String,
251 is_eof: bool,
253}
254
255impl DiffDocument {
256 pub fn is_empty(&self) -> bool {
258 self.files.is_empty()
259 }
260
261 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
276impl FileHeader {
277 pub fn display_path(&self) -> Option<&PathBuf> {
279 self.new_path.as_ref().or(self.old_path.as_ref())
280 }
281}
282
283impl FileMode {
284 pub const fn as_octal(self) -> u32 {
286 match self {
287 Self::Blob => 0o100644,
288 Self::BlobExecutable => 0o100755,
289 Self::Link => 0o120000,
290 Self::Commit => 0o160000,
291 Self::Tree => 0o040000,
292 Self::Other(value) => value,
293 }
294 }
295
296 pub const fn from_octal(value: u32) -> Self {
298 match value {
299 0o100644 => Self::Blob,
300 0o100755 => Self::BlobExecutable,
301 0o120000 => Self::Link,
302 0o160000 => Self::Commit,
303 0o040000 => Self::Tree,
304 other => Self::Other(other),
305 }
306 }
307
308 pub fn parse(input: &str) -> Option<Self> {
310 u32::from_str_radix(input.trim(), 8)
311 .ok()
312 .map(Self::from_octal)
313 }
314}
315
316impl fmt::Display for FileMode {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 write!(f, "{:o}", self.as_octal())
319 }
320}
321
322impl DecodeError {
323 pub fn new(line: usize, message: impl Into<String>) -> Self {
325 Self {
326 line,
327 message: message.into(),
328 is_eof: false,
329 }
330 }
331
332 pub fn eof() -> Self {
335 Self {
336 line: 0,
337 message: "unexpected end of file".to_owned(),
338 is_eof: true,
339 }
340 }
341
342 pub fn is_eof(&self) -> bool {
345 self.is_eof
346 }
347
348 pub(crate) fn at_line(mut self, line: usize) -> Self {
350 if self.line == 0 {
351 self.line = line;
352 }
353 self
354 }
355}
356
357impl fmt::Display for DecodeError {
358 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359 if self.line == 0 {
360 f.write_str(&self.message)
361 } else {
362 write!(f, "line {}: {}", self.line, self.message)
363 }
364 }
365}
366
367impl std::error::Error for DecodeError {}
368
369impl From<ParseIntError> for DecodeError {
370 fn from(error: ParseIntError) -> Self {
371 Self::new(0, error.to_string())
372 }
373}
374
375impl From<io::Error> for DecodeError {
376 fn from(error: io::Error) -> Self {
377 Self {
378 line: 0,
379 message: error.to_string(),
380 is_eof: error.kind() == io::ErrorKind::UnexpectedEof,
381 }
382 }
383}
384
385impl fmt::Display for FileKind {
386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387 let name = match self {
388 Self::Modified => "modified",
389 Self::Added => "added",
390 Self::Deleted => "deleted",
391 Self::Renamed => "renamed",
392 Self::Copied => "copied",
393 Self::ModeChanged => "mode changed",
394 Self::Binary => "binary",
395 };
396 f.write_str(name)
397 }
398}
399
400impl DiffLineKind {
401 pub const fn old_len(self) -> u32 {
403 match self {
404 Self::Context | Self::Deletion => 1,
405 Self::Addition | Self::NoNewline => 0,
406 }
407 }
408
409 pub const fn new_len(self) -> u32 {
411 match self {
412 Self::Context | Self::Addition => 1,
413 Self::Deletion | Self::NoNewline => 0,
414 }
415 }
416}
417
418impl HunkHeader {
419 pub fn shifted(&self, old_delta: i32, new_delta: i32) -> Self {
421 Self {
422 old_line_no: Self::add_delta(self.old_line_no, old_delta),
423 new_line_no: Self::add_delta(self.new_line_no, new_delta),
424 ..self.clone()
425 }
426 }
427
428 fn add_delta(line: u32, delta: i32) -> u32 {
430 if delta.is_negative() {
431 line.saturating_sub(delta.unsigned_abs())
432 } else {
433 line.saturating_add(delta.unsigned_abs())
434 }
435 }
436}
437
438impl Hunk {
439 pub fn old_size(&self) -> u32 {
441 self.sizes().old
442 }
443
444 pub fn new_size(&self) -> u32 {
446 self.sizes().new
447 }
448
449 pub fn stats(&self) -> FileStats {
451 let mut stats = FileStats::default();
452 for line in &self.lines {
453 match line.kind {
454 DiffLineKind::Addition => stats.additions += 1,
455 DiffLineKind::Deletion => stats.deletions += 1,
456 DiffLineKind::Context | DiffLineKind::NoNewline => {}
457 }
458 }
459 stats
460 }
461
462 pub fn delta(&self) -> i32 {
464 let sizes = self.sizes();
465 let new_size = i32::try_from(sizes.new).unwrap_or(i32::MAX);
466 let old_size = i32::try_from(sizes.old).unwrap_or(i32::MAX);
467 new_size - old_size
468 }
469
470 pub fn split(&self) -> Option<impl Iterator<Item = Self> + '_> {
474 let groups = self.change_groups();
475 if groups.len() < 2 {
476 return None;
477 }
478 Some((0..groups.len()).map(move |index| {
479 let group = groups[index];
480 let start = if index == 0 {
481 0
482 } else {
483 groups[index - 1].split_context_before(group)
484 };
485 let end = groups
486 .get(index + 1)
487 .map_or(self.lines.len(), |next| group.split_context_before(*next));
488 self.segment(start, end)
489 }))
490 }
491
492 fn change_groups(&self) -> Vec<ChangeGroup> {
494 let mut groups = Vec::new();
495 let mut current = None;
496
497 for (index, line) in self.lines.iter().enumerate() {
498 if matches!(line.kind, DiffLineKind::Context) {
499 if let Some(start) = current.take() {
500 groups.push(ChangeGroup { start, end: index });
501 }
502 } else if current.is_none() {
503 current = Some(index);
504 }
505 }
506 if let Some(start) = current {
507 groups.push(ChangeGroup {
508 start,
509 end: self.lines.len(),
510 });
511 }
512 groups
513 }
514
515 fn segment(&self, start: usize, end: usize) -> Self {
517 let lines = self.lines[start..end].to_vec();
518 let old_delta = self.lines[..start]
519 .iter()
520 .map(|l| l.kind.old_len())
521 .sum::<u32>();
522 let new_delta = self.lines[..start]
523 .iter()
524 .map(|l| l.kind.new_len())
525 .sum::<u32>();
526 let sizes = HunkSizes::from_lines(&lines);
527
528 Self {
529 id: self.id,
530 header: HunkHeader {
531 old_line_no: self.header.old_line_no.saturating_add(old_delta),
532 old_size: sizes.old,
533 new_line_no: self.header.new_line_no.saturating_add(new_delta),
534 new_size: sizes.new,
535 text: self.header.text.clone(),
536 },
537 lines,
538 }
539 }
540
541 fn sizes(&self) -> HunkSizes {
543 HunkSizes::from_lines(&self.lines)
544 }
545
546 pub fn identity(&self) -> Self {
552 let lines: Vec<_> = self
553 .lines
554 .iter()
555 .filter(|line| !matches!(line.kind, DiffLineKind::Context))
556 .cloned()
557 .collect();
558 let sizes = HunkSizes::from_lines(&lines);
559
560 Self {
561 id: self.id,
562 header: HunkHeader {
563 old_line_no: self.header.old_line_no,
564 old_size: sizes.old,
565 new_line_no: self.header.new_line_no,
566 new_size: sizes.new,
567 text: String::new(),
568 },
569 lines,
570 }
571 }
572}
573
574#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
576struct HunkSizes {
577 old: u32,
579 new: u32,
581}
582
583impl HunkSizes {
584 fn from_lines(lines: &[DiffLine]) -> Self {
586 let mut sizes = Self::default();
587 for line in lines {
588 sizes.old += line.kind.old_len();
589 sizes.new += line.kind.new_len();
590 }
591 sizes
592 }
593}
594
595impl FileDiff {
596 pub fn stats(&self) -> FileStats {
598 let mut total = FileStats::default();
599 for hunk in &self.hunks {
600 let hunk_stats = hunk.stats();
601 total.additions += hunk_stats.additions;
602 total.deletions += hunk_stats.deletions;
603 }
604 total
605 }
606
607 pub fn selected(&self, hunks: impl IntoIterator<Item = usize>) -> Self {
609 Self {
610 id: self.id,
611 header: self.header.clone(),
612 hunks: hunks
613 .into_iter()
614 .filter_map(|ix| self.hunks.get(ix).cloned())
615 .collect(),
616 }
617 }
618}
619
620impl DiffDocument {
621 pub fn for_hunks(file: &FileDiff, hunks: impl IntoIterator<Item = Hunk>) -> Self {
624 Self {
625 commit: None,
626 files: vec![FileDiff {
627 id: file.id,
628 header: file.header.clone(),
629 hunks: hunks.into_iter().collect(),
630 }],
631 }
632 }
633
634 pub fn split_hunks(mut self) -> Self {
640 let mut next = 0;
641 for file in &mut self.files {
642 let mut hunks = Vec::with_capacity(file.hunks.len());
643 for hunk in std::mem::take(&mut file.hunks) {
644 if let Some(split) = hunk.split() {
645 for mut hunk in split {
646 hunk.id = HunkId::new(next);
647 next += 1;
648 hunks.push(hunk);
649 }
650 } else {
651 let mut hunk = hunk;
652 hunk.id = HunkId::new(next);
653 next += 1;
654 hunks.push(hunk);
655 }
656 }
657 file.hunks = hunks;
658 }
659 self
660 }
661}
662
663#[derive(Clone, Copy, Debug)]
665struct ChangeGroup {
666 start: usize,
668 end: usize,
670}
671
672impl ChangeGroup {
673 const fn split_context_before(self, next: Self) -> usize {
675 self.end + (next.start - self.end) / 2
676 }
677}
678
679#[cfg(test)]
680#[allow(clippy::unwrap_used)]
681mod tests {
682 use super::*;
683 use crate::Decode;
684
685 fn parse_patch(input: &str) -> DiffDocument {
686 DiffDocument::decode_str(input).unwrap()
687 }
688
689 const PATCH: &str = "\
690diff --git a/a.txt b/a.txt
691index 7898192789819278981927898192789819278981..6178079617807961780796178079617807961780 100644
692--- a/a.txt
693+++ b/a.txt
694@@ -1,3 +1,4 @@
695 one
696+two
697 three
698-four
699+five
700";
701
702 #[test]
703 fn diff_line_kind_counts_old_and_new_contributions() {
704 assert_eq!(DiffLineKind::Context.old_len(), 1);
705 assert_eq!(DiffLineKind::Context.new_len(), 1);
706 assert_eq!(DiffLineKind::Addition.old_len(), 0);
707 assert_eq!(DiffLineKind::Addition.new_len(), 1);
708 assert_eq!(DiffLineKind::Deletion.old_len(), 1);
709 assert_eq!(DiffLineKind::Deletion.new_len(), 0);
710 assert_eq!(DiffLineKind::NoNewline.old_len(), 0);
711 assert_eq!(DiffLineKind::NoNewline.new_len(), 0);
712 }
713
714 #[test]
715 fn hunk_recomputes_sizes_from_lines() {
716 let doc = parse_patch(PATCH);
717 let hunk = &doc.files[0].hunks[0];
718
719 assert_eq!(hunk.old_size(), 3);
720 assert_eq!(hunk.new_size(), 4);
721 assert_eq!(hunk.delta(), 1);
722 }
723
724 #[test]
725 fn hunk_split_separates_change_groups() {
726 let doc = parse_patch(PATCH);
727 let hunk = &doc.files[0].hunks[0];
728 let split = hunk.split().unwrap().collect::<Vec<_>>();
729
730 assert_eq!(split.len(), 2);
731 assert_eq!(split[0].header.old_line_no, 1);
732 assert_eq!(split[0].header.old_size, 1);
733 assert_eq!(split[0].header.new_line_no, 1);
734 assert_eq!(split[0].header.new_size, 2);
735 assert_eq!(split[1].header.old_line_no, 2);
736 assert_eq!(split[1].header.old_size, 2);
737 assert_eq!(split[1].header.new_line_no, 3);
738 assert_eq!(split[1].header.new_size, 2);
739 }
740
741 #[test]
742 fn hunk_split_returns_none_for_single_change_group() {
743 let doc = parse_patch(
744 "\
745diff --git a/a b/a
746@@ -1 +1,2 @@
747 one
748+two
749",
750 );
751
752 assert!(doc.files[0].hunks[0].split().is_none());
753 }
754
755 #[test]
756 fn hunk_header_shifted_moves_line_numbers() {
757 let header = HunkHeader::decode_str("@@ -10,3 +20,3 @@").unwrap();
758 let shifted = header.shifted(2, -3);
759
760 assert_eq!(shifted.old_line_no, 12);
761 assert_eq!(shifted.new_line_no, 17);
762 assert_eq!(shifted.old_size, 3);
763 assert_eq!(shifted.new_size, 3);
764 }
765
766 #[test]
767 fn file_diff_selected_keeps_only_chosen_hunks() {
768 let doc = parse_patch(PATCH);
769 let only = doc.files[0].selected([0]);
770
771 assert_eq!(only.hunks.len(), 1);
772 assert_eq!(only.id, doc.files[0].id);
773 }
774
775 #[test]
776 fn document_for_hunks_drops_preamble() {
777 let with_preamble = format!("commit 1234567890abcdef1234567890abcdef12345678\n\n{PATCH}");
778 let doc = parse_patch(&with_preamble);
779 let single = DiffDocument::for_hunks(&doc.files[0], doc.files[0].hunks.clone());
780
781 assert!(single.commit.is_none());
782 assert_eq!(single.files.len(), 1);
783 assert_eq!(single.files[0].hunks.len(), doc.files[0].hunks.len());
784 }
785
786 #[test]
787 fn stats_aggregate_across_hunks_and_files() {
788 let doc = parse_patch(PATCH);
789 let hunk_stats = doc.files[0].hunks[0].stats();
790 let file_stats = doc.files[0].stats();
791 let doc_stats = doc.stats();
792
793 assert_eq!(
794 hunk_stats,
795 FileStats {
796 additions: 2,
797 deletions: 1
798 }
799 );
800 assert_eq!(
801 file_stats,
802 FileStats {
803 additions: 2,
804 deletions: 1
805 }
806 );
807 assert_eq!(
808 doc_stats,
809 Stats {
810 files_changed: 1,
811 insertions: 2,
812 deletions: 1,
813 }
814 );
815 }
816
817 #[test]
818 fn file_mode_round_trips_through_octal() {
819 for mode in [
820 FileMode::Blob,
821 FileMode::BlobExecutable,
822 FileMode::Link,
823 FileMode::Commit,
824 FileMode::Tree,
825 FileMode::Other(0o123456),
826 ] {
827 assert_eq!(FileMode::from_octal(mode.as_octal()), mode);
828 assert_eq!(FileMode::parse(&mode.to_string()), Some(mode));
829 }
830 assert_eq!(FileMode::parse("not-octal"), None);
831 }
832
833 #[test]
834 fn oid_parses_hexadecimal_text() {
835 let oid = "ABC1230000000000000000000000000000000000"
836 .parse::<Oid>()
837 .unwrap();
838
839 assert_eq!(oid.to_string(), "abc1230000000000000000000000000000000000");
840 assert_eq!("".parse::<Oid>(), Err(OidError));
841 assert_eq!("not-hex".parse::<Oid>(), Err(OidError));
842 assert_eq!("ABC123".parse::<Oid>(), Err(OidError));
843 }
844
845 #[test]
846 fn add_delta_saturates_at_zero() {
847 assert_eq!(HunkHeader::add_delta(5, 3), 8);
848 assert_eq!(HunkHeader::add_delta(5, -3), 2);
849 assert_eq!(HunkHeader::add_delta(2, -10), 0);
850 }
851}