Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions src/context_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::collections::VecDeque;
use std::io::Write;

use crate::params::Params;
use crate::utils::{comparison_lines, do_write_line, line_prefix};
use crate::utils::{comparison_lines, do_write_line, has_non_blank_lines, line_prefix};
use crate::utils::{
get_modification_time, is_posix_locale, write_file_header, FunctionLineFinder, TimestampStyle,
};
Expand All @@ -19,6 +19,15 @@ pub enum DiffLine {
Add(Vec<u8>),
}

impl DiffLine {
fn changed_bytes(&self) -> Option<&[u8]> {
match self {
Self::Change(l) | Self::Add(l) => Some(l),
Self::Context(_) => None,
}
}
}

#[derive(Debug, PartialEq)]
struct Mismatch {
pub line_number_expected: usize,
Expand Down Expand Up @@ -97,7 +106,7 @@ impl ChangeBlock {
// Produces a diff between the expected output and actual output.
fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<Mismatch> {
let context_size = params.context_count;
let stop_early = params.brief;
let stop_early = params.brief && !params.ignore_blank_lines;
let mut line_number_expected = 1;
let mut line_number_actual = 1;
let mut context_queue: VecDeque<&[u8]> = VecDeque::with_capacity(context_size);
Expand Down Expand Up @@ -334,7 +343,17 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<u8> {
params.to_label.as_deref(),
&to_modified_time,
);
let diff_results = make_diff(expected, actual, params);
let mut diff_results = make_diff(expected, actual, params);
if params.ignore_blank_lines {
diff_results.retain(|m| {
has_non_blank_lines(
m.expected
.iter()
.filter_map(DiffLine::changed_bytes)
.chain(m.actual.iter().filter_map(DiffLine::changed_bytes)),
)
});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

almost the same filter 4 times, could it be a shared helper in utils.rs?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in commit a9e187c: extracted has_non_blank_lines helper in src/utils.rs shared across normal, unified, context, and ed formats.

}
if diff_results.is_empty() {
return Vec::new();
}
Expand Down
9 changes: 6 additions & 3 deletions src/ed_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use std::io::Write;

use crate::params::Params;
use crate::utils::{comparison_lines, do_write_line};
use crate::utils::{comparison_lines, do_write_line, has_non_blank_lines};

#[derive(Debug, PartialEq)]
struct Mismatch {
Expand Down Expand Up @@ -46,7 +46,7 @@ impl Mismatch {

// Produces a diff between the expected output and actual output.
fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Result<Vec<Mismatch>, DiffError> {
let stop_early = params.brief;
let stop_early = params.brief && !params.ignore_blank_lines;
let mut line_number_expected = 1;
let mut line_number_actual = 1;
let mut results = Vec::new();
Expand Down Expand Up @@ -113,7 +113,10 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Result<Vec<Mism

pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Result<Vec<u8>, DiffError> {
let mut output = Vec::new();
let diff_results = make_diff(expected, actual, params)?;
let mut diff_results = make_diff(expected, actual, params)?;
if params.ignore_blank_lines {
diff_results.retain(|m| has_non_blank_lines(m.expected.iter().chain(&m.actual)));
}
if params.brief && !diff_results.is_empty() {
write!(&mut output, "\0").unwrap();
return Ok(output);
Expand Down
9 changes: 6 additions & 3 deletions src/normal_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use std::io::Write;

use crate::params::Params;
use crate::utils::{comparison_lines, do_write_line, line_prefix};
use crate::utils::{comparison_lines, do_write_line, has_non_blank_lines, line_prefix};

#[derive(Debug, PartialEq)]
struct Mismatch {
Expand All @@ -33,7 +33,7 @@ impl Mismatch {

// Produces a diff between the expected output and actual output.
fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<Mismatch> {
let stop_early = params.brief;
let stop_early = params.brief && !params.ignore_blank_lines;
let mut line_number_expected = 1;
let mut line_number_actual = 1;
let mut results = Vec::new();
Expand Down Expand Up @@ -122,7 +122,10 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<u8> {
// See https://www.gnu.org/software/diffutils/manual/html_node/Detailed-Normal.html
// for details on the syntax of the normal format.
let mut output = Vec::new();
let diff_results = make_diff(expected, actual, params);
let mut diff_results = make_diff(expected, actual, params);
if params.ignore_blank_lines {
diff_results.retain(|m| has_non_blank_lines(m.expected.iter().chain(&m.actual)));
}
if params.brief && !diff_results.is_empty() {
write!(&mut output, "\0").unwrap();
return output;
Expand Down
19 changes: 19 additions & 0 deletions src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ pub struct Params {
/// (`-S`).
pub starting_file: Option<OsString>,
pub ignore_file_name_case: bool,
pub ignore_blank_lines: bool,
pub no_dereference: bool,
/// Set when `from` did not exist and was compared as an empty file.
pub from_missing: bool,
Expand Down Expand Up @@ -112,6 +113,7 @@ impl Default for Params {
recursive: false,
starting_file: None,
ignore_file_name_case: false,
ignore_blank_lines: false,
no_dereference: false,
from_missing: false,
to_missing: false,
Expand Down Expand Up @@ -259,6 +261,10 @@ pub fn parse_params<I: Iterator<Item = OsString>>(
params.ignore_file_name_case = true;
continue;
}
if param == "-B" || param == "--ignore-blank-lines" {
params.ignore_blank_lines = true;
continue;
}
if param == "--no-ignore-file-name-case" {
params.ignore_file_name_case = false;
continue;
Expand Down Expand Up @@ -1537,4 +1543,17 @@ mod tests {
assert_eq!(params.ignore_file_name_case, expected);
}
}

#[test]
fn ignore_blank_lines() {
for arg in ["-B", "--ignore-blank-lines"] {
let params = parse_params(
[os("diff"), os(arg), os("foo"), os("bar")]
.into_iter()
.peekable(),
)
.unwrap();
assert!(params.ignore_blank_lines);
}
}
}
27 changes: 23 additions & 4 deletions src/side_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{io::Write, vec};
use unicode_width::UnicodeWidthStr;

use crate::params::Params;
use crate::utils::comparison_lines_inclusive;
use crate::utils::{comparison_lines_inclusive, is_blank_line};

const GUTTER_WIDTH_MIN: usize = 3;

Expand Down Expand Up @@ -351,19 +351,38 @@ pub fn diff<T: Write>(
More studies are needed to cover GNU diff side by side with 100% accuracy, which is one of
the goals of this project : )
*/
let mut differs = false;
for result in diff::slice(&left_lines, &right_lines) {
match result {
Result::Left(left_ln) => push_output(left_ln.raw, b"", b'<', output, &config).unwrap(),
Result::Left(left_ln) => {
let is_blank = params.ignore_blank_lines
&& is_blank_line(left_ln.raw.strip_suffix(b"\n").unwrap_or(left_ln.raw));
if !is_blank {
differs = true;
}
let symbol = if is_blank { b'(' } else { b'<' };
push_output(left_ln.raw, b"", symbol, output, &config).unwrap();
}
Result::Right(right_ln) => {
push_output(b"", right_ln.raw, b'>', output, &config).unwrap()
let is_blank = params.ignore_blank_lines
&& is_blank_line(right_ln.raw.strip_suffix(b"\n").unwrap_or(right_ln.raw));
if !is_blank {
differs = true;
}
let symbol = if is_blank { b')' } else { b'>' };
push_output(b"", right_ln.raw, symbol, output, &config).unwrap();
}
Result::Both(left_ln, right_ln) => {
push_output(left_ln.raw, right_ln.raw, b' ', output, &config).unwrap()
}
}
}

vec![]
if differs {
vec![1]
} else {
vec![]
}
}

#[cfg(test)]
Expand Down
19 changes: 16 additions & 3 deletions src/unified_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::collections::VecDeque;
use std::io::Write;

use crate::params::Params;
use crate::utils::{comparison_lines, do_write_line, line_prefix};
use crate::utils::{comparison_lines, do_write_line, has_non_blank_lines, line_prefix};
use crate::utils::{get_modification_time, write_file_header, FunctionLineFinder, TimestampStyle};

#[derive(Debug, PartialEq)]
Expand All @@ -18,6 +18,15 @@ pub enum DiffLine {
MissingNL,
}

impl DiffLine {
fn changed_bytes(&self) -> Option<&[u8]> {
match self {
Self::Expected(l) | Self::Actual(l) => Some(l),
Self::Context(_) | Self::MissingNL => None,
}
}
}

#[derive(Debug, PartialEq)]
struct Mismatch {
pub line_number_expected: u32,
Expand All @@ -38,7 +47,7 @@ impl Mismatch {
// Produces a diff between the expected output and actual output.
fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<Mismatch> {
let context_size = params.context_count;
let stop_early = params.brief;
let stop_early = params.brief && !params.ignore_blank_lines;
let mut line_number_expected = 1;
let mut line_number_actual = 1;
let mut context_queue: VecDeque<&[u8]> = VecDeque::with_capacity(context_size);
Expand Down Expand Up @@ -259,7 +268,11 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<u8> {
params.to_label.as_deref(),
&to_modified_time,
);
let diff_results = make_diff(expected, actual, params);
let mut diff_results = make_diff(expected, actual, params);
if params.ignore_blank_lines {
diff_results
.retain(|m| has_non_blank_lines(m.lines.iter().filter_map(DiffLine::changed_bytes)));
}
if diff_results.is_empty() {
return Vec::new();
}
Expand Down
29 changes: 29 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,24 @@ pub fn line_prefix<'a>(prefix: &'a [u8], line: &[u8], params: &Params) -> &'a [u
}
}

/// Returns true if a line is empty.
///
/// In GNU diff, `-B`/`--ignore-blank-lines` only ignores lines that are completely
/// empty unless space-ignoring options (like `-b` or `-w`) are also active.
#[inline]
pub fn is_blank_line(line: &[u8]) -> bool {
line.is_empty()
}

/// Returns true if any line in the given iterator is non-blank.
pub fn has_non_blank_lines<I, T>(lines: I) -> bool
where
I: IntoIterator<Item = T>,
T: AsRef<[u8]>,
{
lines.into_iter().any(|l| !is_blank_line(l.as_ref()))
}

/// Quotes a file name for the headers of the diff output: a name containing
/// spaces, double quotes, backslashes, control characters or non-ASCII bytes
/// is written between double quotes with C-style escapes, other names are
Expand Down Expand Up @@ -677,6 +695,17 @@ mod tests {
assert_line_written("foo bar\tbaz", false, 8, "foo bar\tbaz");
assert_line_written("foo bar\tbaz", true, 8, "foo bar baz");
}

#[test]
fn blank_lines() {
assert!(is_blank_line(b""));
assert!(!is_blank_line(b"\r"));
assert!(!is_blank_line(b" "));
assert!(!is_blank_line(b"\t"));
assert!(!is_blank_line(b" \t \r"));
assert!(!is_blank_line(b"a"));
assert!(!is_blank_line(b" a "));
}
}

mod modification_time {
Expand Down
Loading
Loading