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
11 changes: 9 additions & 2 deletions src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,15 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome {
}
}
if result.is_empty() {
maybe_report_identical_files();
Outcome::Identical
if params.format == Format::Normal
&& !params.ignore_matching_lines.is_empty()
&& from_content != to_content
{
Outcome::Different
} else {
maybe_report_identical_files();
Outcome::Identical
}
} else {
Outcome::Different
}
Expand Down
62 changes: 62 additions & 0 deletions src/normal_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use std::io::Write;

use crate::bre::Bre;
use crate::params::Params;
use crate::utils::do_write_line;

Expand All @@ -31,6 +32,20 @@ impl Mismatch {
}
}

impl Mismatch {
/// Whether every inserted and deleted line matches at least one `-I`
/// pattern. A mismatch with no changed lines is never ignored.
fn is_ignored(&self, patterns: &[Bre]) -> bool {
if patterns.is_empty() {
return false;
}
self.expected
.iter()
.chain(self.actual.iter())
.all(|line| patterns.iter().any(|pattern| pattern.is_match(line)))
}
}

// Produces a diff between the expected output and actual output.
fn make_diff(expected: &[u8], actual: &[u8], stop_early: bool) -> Vec<Mismatch> {
let mut line_number_expected = 1;
Expand Down Expand Up @@ -127,6 +142,9 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<u8> {
return output;
}
for result in diff_results {
if result.is_ignored(&params.ignore_matching_lines) {
continue;
}
let line_number_expected = result.line_number_expected;
let line_number_actual = result.line_number_actual;
let expected_count = result.expected.len();
Expand Down Expand Up @@ -606,4 +624,48 @@ mod tests {
);
assert!(nodiff_brief.is_empty());
}

#[test]
fn test_ignore_matching_lines() {
use crate::bre::Bre;
use crate::params::Params;

let params = |patterns: &[&str]| Params {
ignore_matching_lines: patterns
.iter()
.map(|pattern| Bre::new(pattern).unwrap())
.collect(),
..Default::default()
};

let from = b"1a\n2\n3a\n";
let to = b"1b\n2\n3b\n";

// No -I: both hunks.
assert_eq!(
diff(from, to, &Params::default()),
b"1c1\n< 1a\n---\n> 1b\n3c3\n< 3a\n---\n> 3b\n".to_vec()
);

// -I 3: only the first hunk, because 3a/3b match 3.
assert_eq!(
diff(from, to, &params(&["3"])),
b"1c1\n< 1a\n---\n> 1b\n".to_vec()
);

// -I 1: only the second hunk.
assert_eq!(
diff(from, to, &params(&["1"])),
b"3c3\n< 3a\n---\n> 3b\n".to_vec()
);

// Multiple patterns are ORed: 1a/1b match 1, 3a/3b match 3.
assert_eq!(diff(from, to, &params(&["1", "3"])), Vec::<u8>::new());

// A hunk with one non-matching changed line is kept.
assert_eq!(
diff(from, to, &params(&["3", "x"])),
b"1c1\n< 1a\n---\n> 1b\n".to_vec()
);
}
}
65 changes: 65 additions & 0 deletions src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub struct Params {
/// Basic regular expressions matching the lines shown after hunk
/// headers (`-F` and `-p`).
pub function_line_patterns: Vec<Bre>,
pub ignore_matching_lines: Vec<Bre>,
pub recursive: bool,
/// The name from which to start comparing the top-level directories
/// (`-S`).
Expand Down Expand Up @@ -105,6 +106,7 @@ impl Default for Params {
palette: None,
presume_output_tty: false,
function_line_patterns: Vec::new(),
ignore_matching_lines: Vec::new(),
recursive: false,
starting_file: None,
ignore_file_name_case: false,
Expand Down Expand Up @@ -247,6 +249,11 @@ pub fn parse_params<I: Iterator<Item = OsString>>(
push_function_line_pattern(&mut params, &pattern.to_string_lossy())?;
continue;
}
if let Some(argument) = option_argument(&param, "-I", "--ignore-matching-lines") {
let pattern = argument_value(argument, &param, &mut opts)?;
push_ignore_matching_line(&mut params, &pattern.to_string_lossy())?;
continue;
}
if param == "--no-dereference" {
params.no_dereference = true;
continue;
Expand Down Expand Up @@ -515,6 +522,13 @@ fn push_function_line_pattern(params: &mut Params, pattern: &str) -> Result<(),
Ok(())
}

/// Validates and records an `-I` pattern.
fn push_ignore_matching_line(params: &mut Params, pattern: &str) -> Result<(), String> {
let bre = Bre::new(pattern).map_err(|error| format!("'{pattern}': {error}"))?;
params.ignore_matching_lines.push(bre);
Ok(())
}

struct DiffStyleMatch {
is_match: bool,
context_count: Option<usize>,
Expand Down Expand Up @@ -1436,6 +1450,57 @@ mod tests {
);
}

#[test]
fn ignore_matching_lines() {
let patterns = |patterns: &[&str]| -> Vec<Bre> {
patterns
.iter()
.map(|pattern| Bre::new(pattern).unwrap())
.collect()
};
let parse = |args: &[&str]| {
let args = std::iter::once("diff")
.chain(args.iter().copied())
.chain(["foo", "bar"]);
parse_params(args.map(os).peekable())
};

assert_eq!(
parse(&["-I", "3"]).unwrap().ignore_matching_lines,
patterns(&["3"])
);
assert_eq!(
parse(&["-I3"]).unwrap().ignore_matching_lines,
patterns(&["3"])
);
assert_eq!(
parse(&["--ignore-matching-lines", "3"])
.unwrap()
.ignore_matching_lines,
patterns(&["3"])
);
assert_eq!(
parse(&["--ignore-matching-lines=3"])
.unwrap()
.ignore_matching_lines,
patterns(&["3"])
);

// Repeatable.
assert_eq!(
parse(&["-Ix", "-I", "y", "--ignore-matching-lines=z"])
.unwrap()
.ignore_matching_lines,
patterns(&["x", "y", "z"])
);

// Invalid BRE is a usage error.
assert_eq!(
parse(&["-Ix", "-I\\"]),
Err("'\\': Trailing backslash".to_string())
);
}

#[test]
fn option_arguments() {
let options = |args: &[&str]| {
Expand Down
43 changes: 43 additions & 0 deletions tests/by-util/test_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,49 @@ fn function_lines() {
.stderr_is("'\\(': Unmatched ( or \\(\n");
}

#[rstest]
fn ignore_matching_lines(
#[values(
&["-I", "3"][..],
&["-I3"],
&["--ignore-matching-lines", "3"],
&["--ignore-matching-lines=3"]
)]
args: &[&str],
) {
let (at, ts) = at_and_ts!();
at.write("a", "1a\n2\n3a\n");
at.write("b", "1b\n2\n3b\n");
ts.ucmd()
.args(args)
.args(&["a", "b"])
.fails_with_code(1)
.stdout_is("1c1\n< 1a\n---\n> 1b\n");
}

#[test]
fn ignore_matching_lines_invalid_re() {
let (at, ts) = at_and_ts!();
at.write("a", "1a\n2\n3a\n");
at.write("b", "1b\n2\n3b\n");
ts.ucmd()
.args(&["-Ix", "-I\\", "a", "b"])
.fails_with_code(2)
.no_stdout()
.stderr_contains("'\\': Trailing backslash");
}

#[test]
fn ignore_matching_lines_all_filtered() {
let (at, ts) = at_and_ts!();
at.write("a", "1a\n2\n3a\n");
at.write("b", "1b\n2\n3b\n");
ts.ucmd()
.args(&["-I", "1", "-I", "3", "a", "b"])
.fails_with_code(1)
.no_stdout();
}

// A function line is cut at 40 bytes, even inside a multi-byte character.
#[test]
fn function_line_is_cut_at_40_bytes() {
Expand Down
Loading