use std::fmt;
use std::io;
use std::num::ParseIntError;
use std::path::PathBuf;
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct FileId(usize);
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct HunkId(usize);
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RowId(usize);
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Oid(String);
impl FileId {
pub const fn new(index: usize) -> Self {
Self(index)
}
}
impl HunkId {
pub const fn new(index: usize) -> Self {
Self(index)
}
}
impl RowId {
pub const fn new(index: usize) -> Self {
Self(index)
}
}
impl Oid {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for Oid {
type Err = OidError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
if input.is_empty() {
return Err(OidError);
}
if !input.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(OidError);
}
Ok(Self(input.to_owned()))
}
}
impl fmt::Display for Oid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OidError;
impl fmt::Display for OidError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("object id must be non-empty hexadecimal text")
}
}
impl std::error::Error for OidError {}
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
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DiffDocument {
pub commit: Option<crate::Commit>,
pub files: Vec<FileDiff>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FileDiff {
pub id: FileId,
pub header: FileHeader,
pub hunks: Vec<Hunk>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FileHeader {
pub kind: FileKind,
pub old_path: Option<PathBuf>,
pub new_path: Option<PathBuf>,
pub old_mode: Option<FileMode>,
pub new_mode: Option<FileMode>,
pub old_oid: Option<Oid>,
pub new_oid: Option<Oid>,
pub raw: Vec<String>,
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum FileMode {
Blob,
BlobExecutable,
Link,
Commit,
Tree,
Other(u32),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileKind {
Modified,
Added,
Deleted,
Renamed,
Copied,
ModeChanged,
Binary,
}
impl FileKind {
pub const fn marker(self) -> char {
match self {
Self::Added => '⊕',
Self::Deleted => '⊖',
Self::Renamed => '↦',
Self::Copied => '⇉',
Self::Modified | Self::ModeChanged | Self::Binary => '⊙',
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct FileStats {
pub additions: usize,
pub deletions: usize,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Stats {
pub files_changed: usize,
pub insertions: usize,
pub deletions: usize,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Hunk {
pub id: HunkId,
pub header: HunkHeader,
pub lines: Vec<DiffLine>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct HunkHeader {
pub old_line_no: u32,
pub old_size: u32,
pub new_line_no: u32,
pub new_size: u32,
pub text: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DiffLine {
pub id: RowId,
pub kind: DiffLineKind,
pub text: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiffLineKind {
Context,
Addition,
Deletion,
NoNewline,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DecodeError {
pub line: usize,
pub message: String,
is_eof: bool,
}
impl DiffDocument {
pub fn is_empty(&self) -> bool {
self.files.is_empty()
}
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 {
pub fn display_path(&self) -> Option<&PathBuf> {
self.new_path.as_ref().or(self.old_path.as_ref())
}
}
impl FileMode {
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,
}
}
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),
}
}
pub fn parse(input: &str) -> Option<Self> {
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 {
pub fn new(line: usize, message: impl Into<String>) -> Self {
Self {
line,
message: message.into(),
is_eof: false,
}
}
pub fn eof() -> Self {
Self {
line: 0,
message: "unexpected end of file".to_owned(),
is_eof: true,
}
}
pub fn is_eof(&self) -> bool {
self.is_eof
}
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<ParseIntError> for DecodeError {
fn from(error: ParseIntError) -> Self {
Self::new(0, error.to_string())
}
}
impl From<io::Error> 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 {
pub const fn old_len(self) -> u32 {
match self {
Self::Context | Self::Deletion => 1,
Self::Addition | Self::NoNewline => 0,
}
}
pub const fn new_len(self) -> u32 {
match self {
Self::Context | Self::Addition => 1,
Self::Deletion | Self::NoNewline => 0,
}
}
}
impl HunkHeader {
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()
}
}
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 {
pub fn old_size(&self) -> u32 {
self.sizes().old
}
pub fn new_size(&self) -> u32 {
self.sizes().new
}
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
}
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
}
pub fn split(&self) -> Option<impl Iterator<Item = Self> + '_> {
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)
}))
}
fn change_groups(&self) -> Vec<ChangeGroup> {
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
}
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::<u32>();
let new_delta = self.lines[..start]
.iter()
.map(|l| l.kind.new_len())
.sum::<u32>();
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,
}
}
fn sizes(&self) -> HunkSizes {
HunkSizes::from_lines(&self.lines)
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct HunkSizes {
old: u32,
new: u32,
}
impl HunkSizes {
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 {
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
}
pub fn selected(&self, hunks: impl IntoIterator<Item = usize>) -> Self {
Self {
id: self.id,
header: self.header.clone(),
hunks: hunks
.into_iter()
.filter_map(|ix| self.hunks.get(ix).cloned())
.collect(),
}
}
}
impl DiffDocument {
pub fn for_hunks(file: &FileDiff, hunks: impl IntoIterator<Item = Hunk>) -> Self {
Self {
commit: None,
files: vec![FileDiff {
id: file.id,
header: file.header.clone(),
hunks: hunks.into_iter().collect(),
}],
}
}
}
#[derive(Clone, Copy, Debug)]
struct ChangeGroup {
start: usize,
end: usize,
}
impl ChangeGroup {
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 7898192..6178079 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::<Vec<_>>();
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 abc\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 = Oid::from_str("ABC123").unwrap();
assert_eq!(oid.as_str(), "ABC123");
assert_eq!(oid.to_string(), "ABC123");
assert_eq!("".parse::<Oid>(), Err(OidError));
assert_eq!("not-hex".parse::<Oid>(), 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);
}
}