Skip to content

Commit

Permalink
Print warning when we cannot print good diff
Browse files Browse the repository at this point in the history
  • Loading branch information
lemolatoon committed Sep 20, 2022
1 parent 27ee628 commit 92902ce
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
18 changes: 16 additions & 2 deletions pretty_assertions/src/lib.rs
Expand Up @@ -205,8 +205,22 @@ where
TRight: AsRef<str> + ?Sized,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
printer::write_header(f)?;
printer::write_lines(f, self.left.as_ref(), self.right.as_ref())
let left = self.left.as_ref();
let right = self.right.as_ref();
if left != right
&& dbg!(::diff::lines(left, right))
.iter()
.all(|result| matches!(result, ::diff::Result::Both(..)))
{
// If left and right are not the same and all changes are both, then we cannot print good diff.
// We should print the warning here and fallback to the debug output.
writeln!(f, "Warning: values were different, but no line diff was generated. It seems like these values only differ in line endings - falling back to debug output:")?;
printer::write_header(f)?;
printer::write_lines_debug_output_fallback(f, left, right)
} else {
printer::write_header(f)?;
printer::write_lines(f, left, right)
}
}
}

Expand Down
32 changes: 31 additions & 1 deletion pretty_assertions/src/printer.rs
Expand Up @@ -77,7 +77,7 @@ impl<'a> LatentDeletion<'a> {
// https://github.com/johannhof/difference.rs/blob/c5749ad7d82aa3d480c15cb61af9f6baa08f116f/examples/github-style.rs
// Credits johannhof (MIT License)

/// Present the diff output for two mutliline strings in a pretty, colorised manner.
/// Present the diff output for two multiline strings in a pretty, colorised manner.
pub(crate) fn write_lines<TWrite: fmt::Write>(
f: &mut TWrite,
left: &str,
Expand Down Expand Up @@ -123,6 +123,20 @@ pub(crate) fn write_lines<TWrite: fmt::Write>(
Ok(())
}

/// Present the diff output for two multiline strings by debug output.
pub(crate) fn write_lines_debug_output_fallback<TWrite: fmt::Write>(
f: &mut TWrite,
left: &str,
right: &str,
) -> fmt::Result {
writeln!(
f,
r#" left: `{:?}`,
right: `{:?}`"#,
left, right,
)
}

/// Group character styling for an inline diff, to prevent wrapping each single
/// character in terminal styling codes.
///
Expand Down Expand Up @@ -249,6 +263,22 @@ mod test {
assert_eq!(actual, expected);
}

/// Test diffing newlines from different conventions.
///
/// See: https://github.com/colin-kiegel/rust-pretty-assertions/issues/100
#[test]
fn different_newlines() {
// The below inputs caused an output with no visible diff
let left = "Foo\r\n";
let right = "Foo\n";
let expected = r#" left: `"Foo\r\n"`,
right: `"Foo\n"`
"#
.to_string();

check_printer(write_lines_debug_output_fallback, left, right, &expected);
}

#[test]
fn write_inline_diff_empty() {
let left = "";
Expand Down

0 comments on commit 92902ce

Please sign in to comment.