//! Unified diff document model. //! //! Defines the data tree (`DiffDocument` → `FileDiff` → `Hunk` → `DiffLine`) //! that callers consume. The decoder that produces these values lives in //! [`crate::decode`]; `document` is intentionally model-only. pub use rustik_repo::{Oid, OidError}; use rustik_repo::DiffStat; use std::fmt; use std::io; use std::num::ParseIntError; use std::path::PathBuf; /// Stable identifier for a file section in one diff document. #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct FileId(usize); /// Stable identifier for a hunk in one diff document. #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct HunkId(usize); /// Stable identifier for a rendered hunk row in one diff document. #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct RowId(usize); impl FileId { /// Wraps a raw index as a [`FileId`]. pub const fn new(index: usize) -> Self { Self(index) } } impl HunkId { /// Wraps a raw index as a [`HunkId`]. pub const fn new(index: usize) -> Self { Self(index) } } impl RowId { /// Wraps a raw index as a [`RowId`]. pub const fn new(index: usize) -> Self { Self(index) } } impl std::ops::Deref for FileId { type Target = usize; fn deref(&self) -> &usize { &self.0 } } impl std::ops::Deref for HunkId { type Target = usize; fn deref(&self) -> &usize { &self.0 } } impl std::ops::Deref for RowId { type Target = usize; fn deref(&self) -> &usize { &self.0 } } /// A complete unified diff document. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DiffDocument { /// Commit preamble before the first `diff --git` section, if present. pub commit: Option, /// File diffs in input order. pub files: Vec, } /// A single file section in a unified diff. #[derive(Clone, Debug, Eq, PartialEq)] pub struct FileDiff { /// Stable file identifier. pub id: FileId, /// Metadata and raw header lines for this file. pub header: FileHeader, /// Hunks in input order. pub hunks: Vec, } /// Metadata lines that introduce a file section in a Git patch. #[derive(Clone, Debug, Eq, PartialEq)] pub struct FileHeader { /// Classified kind of file change. pub kind: FileKind, /// Path on the old side of the diff, when present. pub old_path: Option, /// Path on the new side of the diff, when present. pub new_path: Option, /// File mode on the old side of the diff, when present. pub old_mode: Option, /// File mode on the new side of the diff, when present. pub new_mode: Option, /// Object id on the old side of the diff, when present. pub old_oid: Option, /// Object id on the new side of the diff, when present. pub new_oid: Option, /// Raw header lines preserved for callers that need exact metadata. pub raw: Vec, } /// File mode in a Git diff, parsed from the octal value Git records. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum FileMode { /// Regular file (`100644`). Blob, /// Executable regular file (`100755`). BlobExecutable, /// Symbolic link (`120000`). Link, /// Submodule reference, i.e. a Git commit (`160000`). Commit, /// Directory tree (`040000`). Tree, /// Any other mode, preserved as the original octal value. Other(u32), } /// Kind of file-level change described by a patch file header. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum FileKind { /// Existing file content changed. Modified, /// New file was added. Added, /// Existing file was deleted. Deleted, /// Existing file was renamed. Renamed, /// Existing file was copied. Copied, /// File mode changed without a more specific content kind. ModeChanged, /// File contains binary patch data or a binary comparison marker. Binary, } impl FileKind { /// Returns the compact marker used by diff chrome. pub const fn marker(self) -> char { match self { Self::Added => '⊕', Self::Deleted => '⊖', Self::Renamed => '↦', Self::Copied => '⇉', Self::Modified | Self::ModeChanged | Self::Binary => '⊙', } } } /// Aggregate statistics for one [`FileDiff`]. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct FileStats { /// Total addition lines across all hunks in the file. pub additions: usize, /// Total deletion lines across all hunks in the file. pub deletions: usize, } /// Aggregate statistics for one [`DiffDocument`]. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct Stats { /// Number of file sections in the document. pub files_changed: usize, /// Total addition lines across all files. pub insertions: usize, /// Total deletion lines across all files. pub deletions: usize, } impl From for Stats { fn from(stats: DiffStat) -> Self { Self { files_changed: stats.files_changed, insertions: stats.insertions, deletions: stats.deletions, } } } /// A unified diff hunk and its body lines. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Hunk { /// Stable hunk identifier. pub id: HunkId, /// Parsed hunk header. pub header: HunkHeader, /// Lines contained in the hunk body. pub lines: Vec, } /// Metadata from a unified diff hunk header. /// /// Example: `@@ -24,8 +24,6 @@ fn main`. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct HunkHeader { /// Starting line number on the old side of the diff. pub old_line_no: u32, /// Number of old-side lines covered by the hunk. pub old_size: u32, /// Starting line number on the new side of the diff. pub new_line_no: u32, /// Number of new-side lines covered by the hunk. pub new_size: u32, /// Optional trailing hunk context text. pub text: String, } /// A single line in a unified diff hunk. #[derive(Clone, Debug, Eq, PartialEq)] pub struct DiffLine { /// Stable row identifier. pub id: RowId, /// Line role inside the hunk. pub kind: DiffLineKind, /// Line text without the leading diff marker. pub text: String, } /// Role of a line inside a unified diff hunk. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DiffLineKind { /// Unchanged context line. Context, /// Added line. Addition, /// Deleted line. Deletion, /// Marker for a file without a trailing newline. NoNewline, } /// Error produced while decoding a unified diff. #[derive(Clone, Debug, Eq, PartialEq)] pub struct DecodeError { /// One-based input line number where decoding failed. pub line: usize, /// Human-readable failure message. pub message: String, /// Whether this error represents a clean end-of-input signal. is_eof: bool, } impl DiffDocument { /// Returns whether the document contains no changed files. pub fn is_empty(&self) -> bool { self.files.is_empty() } /// Returns the totals of files changed, insertions, and deletions. pub fn stats(&self) -> Stats { let mut stats = Stats { files_changed: self.files.len(), ..Stats::default() }; for file in &self.files { let file_stats = file.stats(); stats.insertions += file_stats.additions; stats.deletions += file_stats.deletions; } stats } } impl FileHeader { /// Returns the path callers should usually show for this file. pub fn display_path(&self) -> Option<&PathBuf> { self.new_path.as_ref().or(self.old_path.as_ref()) } } impl FileMode { /// Returns the octal mode value Git records on the wire. pub const fn as_octal(self) -> u32 { match self { Self::Blob => 0o100644, Self::BlobExecutable => 0o100755, Self::Link => 0o120000, Self::Commit => 0o160000, Self::Tree => 0o040000, Self::Other(value) => value, } } /// Builds a [`FileMode`] from an octal value, mapping known modes. pub const fn from_octal(value: u32) -> Self { match value { 0o100644 => Self::Blob, 0o100755 => Self::BlobExecutable, 0o120000 => Self::Link, 0o160000 => Self::Commit, 0o040000 => Self::Tree, other => Self::Other(other), } } /// Parses an octal mode token from a Git diff header (e.g. `"100644"`). pub fn parse(input: &str) -> Option { u32::from_str_radix(input.trim(), 8) .ok() .map(Self::from_octal) } } impl fmt::Display for FileMode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:o}", self.as_octal()) } } impl DecodeError { /// Creates a decode error at a one-based line number. pub fn new(line: usize, message: impl Into) -> Self { Self { line, message: message.into(), is_eof: false, } } /// Creates an end-of-input error used to signal a clean EOF to streaming /// callers. [`crate::Decode::try_decode`] turns this into `Ok(None)`. pub fn eof() -> Self { Self { line: 0, message: "unexpected end of file".to_owned(), is_eof: true, } } /// Returns whether this error represents end of input rather than a /// malformed patch. pub fn is_eof(&self) -> bool { self.is_eof } /// Returns a copy of this error with a line number when the error has none. pub(crate) fn at_line(mut self, line: usize) -> Self { if self.line == 0 { self.line = line; } self } } impl fmt::Display for DecodeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.line == 0 { f.write_str(&self.message) } else { write!(f, "line {}: {}", self.line, self.message) } } } impl std::error::Error for DecodeError {} impl From for DecodeError { fn from(error: ParseIntError) -> Self { Self::new(0, error.to_string()) } } impl From for DecodeError { fn from(error: io::Error) -> Self { Self { line: 0, message: error.to_string(), is_eof: error.kind() == io::ErrorKind::UnexpectedEof, } } } impl fmt::Display for FileKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let name = match self { Self::Modified => "modified", Self::Added => "added", Self::Deleted => "deleted", Self::Renamed => "renamed", Self::Copied => "copied", Self::ModeChanged => "mode changed", Self::Binary => "binary", }; f.write_str(name) } } impl DiffLineKind { /// Returns how many old-side lines this kind contributes to a hunk. pub const fn old_len(self) -> u32 { match self { Self::Context | Self::Deletion => 1, Self::Addition | Self::NoNewline => 0, } } /// Returns how many new-side lines this kind contributes to a hunk. pub const fn new_len(self) -> u32 { match self { Self::Context | Self::Addition => 1, Self::Deletion | Self::NoNewline => 0, } } } impl HunkHeader { /// Returns a copy with old and new line numbers shifted by the deltas. pub fn shifted(&self, old_delta: i32, new_delta: i32) -> Self { Self { old_line_no: Self::add_delta(self.old_line_no, old_delta), new_line_no: Self::add_delta(self.new_line_no, new_delta), ..self.clone() } } /// Adds a signed delta to an unsigned line number with saturation. fn add_delta(line: u32, delta: i32) -> u32 { if delta.is_negative() { line.saturating_sub(delta.unsigned_abs()) } else { line.saturating_add(delta.unsigned_abs()) } } } impl Hunk { /// Returns the number of old-side lines covered by the hunk body. pub fn old_size(&self) -> u32 { self.sizes().old } /// Returns the number of new-side lines covered by the hunk body. pub fn new_size(&self) -> u32 { self.sizes().new } /// Counts addition and deletion lines in this hunk. pub fn stats(&self) -> FileStats { let mut stats = FileStats::default(); for line in &self.lines { match line.kind { DiffLineKind::Addition => stats.additions += 1, DiffLineKind::Deletion => stats.deletions += 1, DiffLineKind::Context | DiffLineKind::NoNewline => {} } } stats } /// Returns the net line offset introduced by applying this hunk. pub fn delta(&self) -> i32 { let sizes = self.sizes(); let new_size = i32::try_from(sizes.new).unwrap_or(i32::MAX); let old_size = i32::try_from(sizes.old).unwrap_or(i32::MAX); new_size - old_size } /// Splits this hunk into context-separated change groups, each with its /// own recomputed header. Returns `None` when the hunk has fewer than two /// change groups (nothing to split). pub fn split(&self) -> Option + '_> { let groups = self.change_groups(); if groups.len() < 2 { return None; } Some((0..groups.len()).map(move |index| { let group = groups[index]; let start = if index == 0 { 0 } else { groups[index - 1].split_context_before(group) }; let end = groups .get(index + 1) .map_or(self.lines.len(), |next| group.split_context_before(*next)); self.segment(start, end) })) } /// Returns half-open ranges of contiguous non-context lines. fn change_groups(&self) -> Vec { let mut groups = Vec::new(); let mut current = None; for (index, line) in self.lines.iter().enumerate() { if matches!(line.kind, DiffLineKind::Context) { if let Some(start) = current.take() { groups.push(ChangeGroup { start, end: index }); } } else if current.is_none() { current = Some(index); } } if let Some(start) = current { groups.push(ChangeGroup { start, end: self.lines.len(), }); } groups } /// Returns one hunk segment with line numbers and sizes recomputed. fn segment(&self, start: usize, end: usize) -> Self { let lines = self.lines[start..end].to_vec(); let old_delta = self.lines[..start] .iter() .map(|l| l.kind.old_len()) .sum::(); let new_delta = self.lines[..start] .iter() .map(|l| l.kind.new_len()) .sum::(); let sizes = HunkSizes::from_lines(&lines); Self { id: self.id, header: HunkHeader { old_line_no: self.header.old_line_no.saturating_add(old_delta), old_size: sizes.old, new_line_no: self.header.new_line_no.saturating_add(new_delta), new_size: sizes.new, text: self.header.text.clone(), }, lines, } } /// Returns old-side and new-side body sizes. fn sizes(&self) -> HunkSizes { HunkSizes::from_lines(&self.lines) } /// Returns a copy identifying the change independently of its context. /// /// Context lines are dropped, sizes are recomputed, and the header text is /// cleared, so the same change produces the same patch text even when its /// surrounding context or position drifts. pub fn identity(&self) -> Self { let lines: Vec<_> = self .lines .iter() .filter(|line| !matches!(line.kind, DiffLineKind::Context)) .cloned() .collect(); let sizes = HunkSizes::from_lines(&lines); Self { id: self.id, header: HunkHeader { old_line_no: self.header.old_line_no, old_size: sizes.old, new_line_no: self.header.new_line_no, new_size: sizes.new, text: String::new(), }, lines, } } } /// Old-side and new-side line counts for a hunk body. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] struct HunkSizes { /// Old-side line count. old: u32, /// New-side line count. new: u32, } impl HunkSizes { /// Counts old-side and new-side contributions across diff lines. fn from_lines(lines: &[DiffLine]) -> Self { let mut sizes = Self::default(); for line in lines { sizes.old += line.kind.old_len(); sizes.new += line.kind.new_len(); } sizes } } impl FileDiff { /// Returns the sum of addition and deletion lines across all hunks. pub fn stats(&self) -> FileStats { let mut total = FileStats::default(); for hunk in &self.hunks { let hunk_stats = hunk.stats(); total.additions += hunk_stats.additions; total.deletions += hunk_stats.deletions; } total } /// Returns a copy containing only the hunks at the given indexes. pub fn selected(&self, hunks: impl IntoIterator) -> Self { Self { id: self.id, header: self.header.clone(), hunks: hunks .into_iter() .filter_map(|ix| self.hunks.get(ix).cloned()) .collect(), } } } impl DiffDocument { /// Returns a single-file document with the given hunks, suitable for /// `git apply`. The preamble is dropped. pub fn for_hunks(file: &FileDiff, hunks: impl IntoIterator) -> Self { Self { commit: None, files: vec![FileDiff { id: file.id, header: file.header.clone(), hunks: hunks.into_iter().collect(), }], } } /// Splits multi-change hunks into independently reviewable hunks. /// /// Hunk ids are reassigned sequentially across the whole document, so the /// split must run before any per-hunk state is derived for pieces to keep /// stable identities across reloads. pub fn split_hunks(mut self) -> Self { let mut next = 0; for file in &mut self.files { let mut hunks = Vec::with_capacity(file.hunks.len()); for hunk in std::mem::take(&mut file.hunks) { if let Some(split) = hunk.split() { for mut hunk in split { hunk.id = HunkId::new(next); next += 1; hunks.push(hunk); } } else { let mut hunk = hunk; hunk.id = HunkId::new(next); next += 1; hunks.push(hunk); } } file.hunks = hunks; } self } } /// Half-open range of non-context lines inside a hunk. #[derive(Clone, Copy, Debug)] struct ChangeGroup { /// First changed line index. start: usize, /// One past the final changed line index. end: usize, } impl ChangeGroup { /// Returns the split point in the context before `next`. const fn split_context_before(self, next: Self) -> usize { self.end + (next.start - self.end) / 2 } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; use crate::Decode; fn parse_patch(input: &str) -> DiffDocument { DiffDocument::decode_str(input).unwrap() } const PATCH: &str = "\ diff --git a/a.txt b/a.txt index 7898192789819278981927898192789819278981..6178079617807961780796178079617807961780 100644 --- a/a.txt +++ b/a.txt @@ -1,3 +1,4 @@ one +two three -four +five "; #[test] fn diff_line_kind_counts_old_and_new_contributions() { assert_eq!(DiffLineKind::Context.old_len(), 1); assert_eq!(DiffLineKind::Context.new_len(), 1); assert_eq!(DiffLineKind::Addition.old_len(), 0); assert_eq!(DiffLineKind::Addition.new_len(), 1); assert_eq!(DiffLineKind::Deletion.old_len(), 1); assert_eq!(DiffLineKind::Deletion.new_len(), 0); assert_eq!(DiffLineKind::NoNewline.old_len(), 0); assert_eq!(DiffLineKind::NoNewline.new_len(), 0); } #[test] fn hunk_recomputes_sizes_from_lines() { let doc = parse_patch(PATCH); let hunk = &doc.files[0].hunks[0]; assert_eq!(hunk.old_size(), 3); assert_eq!(hunk.new_size(), 4); assert_eq!(hunk.delta(), 1); } #[test] fn hunk_split_separates_change_groups() { let doc = parse_patch(PATCH); let hunk = &doc.files[0].hunks[0]; let split = hunk.split().unwrap().collect::>(); assert_eq!(split.len(), 2); assert_eq!(split[0].header.old_line_no, 1); assert_eq!(split[0].header.old_size, 1); assert_eq!(split[0].header.new_line_no, 1); assert_eq!(split[0].header.new_size, 2); assert_eq!(split[1].header.old_line_no, 2); assert_eq!(split[1].header.old_size, 2); assert_eq!(split[1].header.new_line_no, 3); assert_eq!(split[1].header.new_size, 2); } #[test] fn hunk_split_returns_none_for_single_change_group() { let doc = parse_patch( "\ diff --git a/a b/a @@ -1 +1,2 @@ one +two ", ); assert!(doc.files[0].hunks[0].split().is_none()); } #[test] fn hunk_header_shifted_moves_line_numbers() { let header = HunkHeader::decode_str("@@ -10,3 +20,3 @@").unwrap(); let shifted = header.shifted(2, -3); assert_eq!(shifted.old_line_no, 12); assert_eq!(shifted.new_line_no, 17); assert_eq!(shifted.old_size, 3); assert_eq!(shifted.new_size, 3); } #[test] fn file_diff_selected_keeps_only_chosen_hunks() { let doc = parse_patch(PATCH); let only = doc.files[0].selected([0]); assert_eq!(only.hunks.len(), 1); assert_eq!(only.id, doc.files[0].id); } #[test] fn document_for_hunks_drops_preamble() { let with_preamble = format!("commit 1234567890abcdef1234567890abcdef12345678\n\n{PATCH}"); let doc = parse_patch(&with_preamble); let single = DiffDocument::for_hunks(&doc.files[0], doc.files[0].hunks.clone()); assert!(single.commit.is_none()); assert_eq!(single.files.len(), 1); assert_eq!(single.files[0].hunks.len(), doc.files[0].hunks.len()); } #[test] fn stats_aggregate_across_hunks_and_files() { let doc = parse_patch(PATCH); let hunk_stats = doc.files[0].hunks[0].stats(); let file_stats = doc.files[0].stats(); let doc_stats = doc.stats(); assert_eq!( hunk_stats, FileStats { additions: 2, deletions: 1 } ); assert_eq!( file_stats, FileStats { additions: 2, deletions: 1 } ); assert_eq!( doc_stats, Stats { files_changed: 1, insertions: 2, deletions: 1, } ); } #[test] fn file_mode_round_trips_through_octal() { for mode in [ FileMode::Blob, FileMode::BlobExecutable, FileMode::Link, FileMode::Commit, FileMode::Tree, FileMode::Other(0o123456), ] { assert_eq!(FileMode::from_octal(mode.as_octal()), mode); assert_eq!(FileMode::parse(&mode.to_string()), Some(mode)); } assert_eq!(FileMode::parse("not-octal"), None); } #[test] fn oid_parses_hexadecimal_text() { let oid = "ABC1230000000000000000000000000000000000" .parse::() .unwrap(); assert_eq!(oid.to_string(), "abc1230000000000000000000000000000000000"); assert_eq!("".parse::(), Err(OidError)); assert_eq!("not-hex".parse::(), Err(OidError)); assert_eq!("ABC123".parse::(), Err(OidError)); } #[test] fn add_delta_saturates_at_zero() { assert_eq!(HunkHeader::add_delta(5, 3), 8); assert_eq!(HunkHeader::add_delta(5, -3), 2); assert_eq!(HunkHeader::add_delta(2, -10), 0); } }