From 256829dd7d64abc76bc8f26d5817e3e4e0793f33 Mon Sep 17 00:00:00 2001 From: Julien Rouhaud Date: Sun, 11 Jul 2021 12:34:02 +0800 Subject: [PATCH] Add a new without_no_newline_at_eof in PatchFormatter. Setting this option will prevent emitting "\ No newline at end of file" messages. Fixes: #8 --- src/diff/tests.rs | 30 ++++++++++++++++++++++++++++++ src/patch/format.rs | 16 ++++++++++++++-- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/diff/tests.rs b/src/diff/tests.rs index 9ac8fa7..f4cab0b 100644 --- a/src/diff/tests.rs +++ b/src/diff/tests.rs @@ -3,6 +3,7 @@ use crate::{ apply::apply, diff::{Diff, DiffRange}, patch::Patch, + PatchFormatter, range::Range, }; @@ -518,6 +519,35 @@ fn no_newline_at_eof() { assert_patch!(old, new, expected); } +#[test] +fn without_no_newline_at_eof() { + let old = "old line"; + let new = "new line"; + let expected = "\ +--- original ++++ modified +@@ -1 +1 @@ +-old line ++new line +"; + + let f = PatchFormatter::new().without_missing_newline_message(); + let patch = create_patch(old, new); + let bpatch = create_patch_bytes(old.as_bytes(), new.as_bytes()); + let patch_str = format!("{}", f.fmt_patch(&patch)); + let mut patch_bytes = Vec::new(); + f.write_patch_into(&bpatch, &mut patch_bytes).unwrap(); + + assert_eq!(patch_str, expected); + assert_eq!(patch_bytes, patch_str.as_bytes()); + assert_eq!(patch_bytes, expected.as_bytes()); + assert_eq!(apply(old, &patch).unwrap(), new); + assert_eq!( + crate::apply_bytes(old.as_bytes(), &bpatch).unwrap(), + new.as_bytes() + ); +} + #[test] fn myers_diffy_vs_git() { let original = "\ diff --git a/src/patch/format.rs b/src/patch/format.rs index 7a51450..94815be 100644 --- a/src/patch/format.rs +++ b/src/patch/format.rs @@ -9,6 +9,7 @@ use std::{ #[derive(Debug)] pub struct PatchFormatter { with_color: bool, + without_missing_newline_message: bool, context: Style, delete: Style, @@ -23,6 +24,7 @@ impl PatchFormatter { pub fn new() -> Self { Self { with_color: false, + without_missing_newline_message: false, context: Style::new(), delete: Color::Red.normal(), @@ -39,6 +41,12 @@ impl PatchFormatter { self } + /// Enable formatting a patch without a "No newline at end of file" message + pub fn without_missing_newline_message(mut self) -> Self { + self.without_missing_newline_message = true; + self + } + /// Returns a `Display` impl which can be used to print a Patch pub fn fmt_patch<'a>(&'a self, patch: &'a Patch<'a, str>) -> impl Display + 'a { PatchDisplay { f: self, patch } @@ -238,7 +246,9 @@ impl + ?Sized> LineDisplay<'_, T> { if !line.ends_with(b"\n") { writeln!(w)?; - writeln!(w, "{}", NO_NEWLINE_AT_EOF)?; + if !self.f.without_missing_newline_message { + writeln!(w, "{}", NO_NEWLINE_AT_EOF)?; + } } Ok(()) @@ -269,7 +279,9 @@ impl Display for LineDisplay<'_, str> { if !line.ends_with('\n') { writeln!(f)?; - writeln!(f, "{}", NO_NEWLINE_AT_EOF)?; + if !self.f.without_missing_newline_message { + writeln!(f, "{}", NO_NEWLINE_AT_EOF)?; + } } Ok(())