diff --git a/src/color.rs b/src/color.rs index 64276f60..e36d5e22 100644 --- a/src/color.rs +++ b/src/color.rs @@ -137,7 +137,7 @@ pub fn colorize(output: &[u8], format: Format, palette: &Palette) -> Vec { LineKind::Plain } } - Format::Ed | Format::SideBySide => LineKind::Plain, + Format::Ed | Format::SideBySide | Format::Ifdef => LineKind::Plain, }; let sgr = match kind { LineKind::Plain => { diff --git a/src/diff.rs b/src/diff.rs index 7931d4c1..9e237cf4 100644 --- a/src/diff.rs +++ b/src/diff.rs @@ -6,7 +6,7 @@ use crate::color::{colorize, ColorWhen, Palette, PaletteError}; use crate::params::{parse_params, Format, MissingFile, Params}; use crate::utils::report_failure_to_read_input_file; -use crate::{context_diff, dir_diff, ed_diff, normal_diff, side_diff, unified_diff}; +use crate::{context_diff, dir_diff, ed_diff, ifdef_diff, normal_diff, side_diff, unified_diff}; use std::env::ArgsOs; use std::ffi::OsString; use std::fs; @@ -154,12 +154,18 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { ..params.clone() }; + let mut ifdef_differs = false; // run diff let result: Vec = match params.format { Format::Normal => normal_diff::diff(&from_content, &to_content, params), Format::Unified => unified_diff::diff(&from_content, &to_content, params), Format::Context => context_diff::diff(&from_content, &to_content, params), Format::Ed => ed_diff::diff(&from_content, &to_content, params), + Format::Ifdef => { + let (res, differs) = ifdef_diff::diff(&from_content, &to_content, params); + ifdef_differs = differs; + res + } // Side by side output is streamed, unless a header may have to come // first. Format::SideBySide => match header { @@ -167,7 +173,8 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { Some(header) => { let mut output = Vec::new(); let result = side_diff::diff(&from_content, &to_content, &mut output, params); - if !result.is_empty() { + let differs = !result.is_empty(); + if differs { output.splice(0..0, header.iter().copied()); } if stdout().write_all(&output).is_err() { @@ -177,10 +184,17 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { } }, }; - if params.brief && !result.is_empty() { - print_files_differ("Files", params); + let differs = if params.format == Format::Ifdef { + ifdef_differs + } else { + !result.is_empty() + }; + if params.brief { + if differs { + print_files_differ("Files", params); + } } else if params.format != Format::SideBySide { - let header = if result.is_empty() { + let header = if !differs { &[][..] } else { header.unwrap_or_default() @@ -223,7 +237,7 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { return Outcome::Trouble; } } - if result.is_empty() { + if !differs { maybe_report_identical_files(); Outcome::Identical } else { diff --git a/src/ifdef_diff.rs b/src/ifdef_diff.rs new file mode 100644 index 00000000..d7fa8781 --- /dev/null +++ b/src/ifdef_diff.rs @@ -0,0 +1,193 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +use std::ffi::OsStr; + +use crate::params::Params; +use crate::utils::do_write_line; + +fn write_lines(output: &mut Vec, lines: &[&[u8]], expand_tabs: bool, tabsize: usize) { + for &line in lines { + do_write_line(output, line, expand_tabs, tabsize, b"").expect("write to Vec is infallible"); + output.push(b'\n'); + } +} + +fn write_directive(output: &mut Vec, prefix: &[u8], name: &[u8], suffix: Option<&[u8]>) { + output.extend_from_slice(prefix); + output.extend_from_slice(name); + if let Some(s) = suffix { + output.extend_from_slice(s); + } + output.push(b'\n'); +} + +fn flush_hunk( + output: &mut Vec, + current_expected: &mut Vec<&[u8]>, + current_actual: &mut Vec<&[u8]>, + ifdef_name: &[u8], + expand_tabs: bool, + tabsize: usize, +) -> bool { + match (!current_expected.is_empty(), !current_actual.is_empty()) { + (true, false) => { + write_directive(output, b"#ifndef ", ifdef_name, None); + write_lines(output, current_expected, expand_tabs, tabsize); + write_directive(output, b"#endif /* ! ", ifdef_name, Some(b" */")); + } + (false, true) => { + write_directive(output, b"#ifdef ", ifdef_name, None); + write_lines(output, current_actual, expand_tabs, tabsize); + write_directive(output, b"#endif /* ", ifdef_name, Some(b" */")); + } + (true, true) => { + write_directive(output, b"#ifndef ", ifdef_name, None); + write_lines(output, current_expected, expand_tabs, tabsize); + write_directive(output, b"#else /* ", ifdef_name, Some(b" */")); + write_lines(output, current_actual, expand_tabs, tabsize); + write_directive(output, b"#endif /* ", ifdef_name, Some(b" */")); + } + (false, false) => return false, + } + current_expected.clear(); + current_actual.clear(); + true +} + +/// Produces a merged output with preprocessor `#ifdef` / `#ifndef` / `#else` / `#endif` blocks. +/// +/// Returns `(output_bytes, differs)` where `differs` is true if any difference was found between the files. +pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> (Vec, bool) { + let ifdef_name = params + .ifdef_name + .as_deref() + .map(OsStr::as_encoded_bytes) + .unwrap_or(b""); + let mut output = Vec::new(); + + let mut expected_lines: Vec<&[u8]> = expected.split(|&c| c == b'\n').collect(); + let mut actual_lines: Vec<&[u8]> = actual.split(|&c| c == b'\n').collect(); + + let expected_lines_count = expected_lines.len() - 1; + let actual_lines_count = actual_lines.len() - 1; + + if expected_lines.last() == Some(&&b""[..]) { + expected_lines.pop(); + } + if actual_lines.last() == Some(&&b""[..]) { + actual_lines.pop(); + } + + let mut line_number_expected = 1; + let mut line_number_actual = 1; + let mut differs = false; + + let mut current_expected: Vec<&[u8]> = Vec::new(); + let mut current_actual: Vec<&[u8]> = Vec::new(); + + for result in diff::slice(&expected_lines, &actual_lines) { + match result { + diff::Result::Left(&line) => { + current_expected.push(line); + line_number_expected += 1; + } + diff::Result::Right(&line) => { + current_actual.push(line); + line_number_actual += 1; + } + diff::Result::Both(&line1, &line2) => { + let exp_missing_nl = line_number_expected > expected_lines_count; + let act_missing_nl = line_number_actual > actual_lines_count; + if exp_missing_nl != act_missing_nl { + current_expected.push(line1); + current_actual.push(line2); + } else { + if flush_hunk( + &mut output, + &mut current_expected, + &mut current_actual, + ifdef_name, + params.expand_tabs, + params.tabsize, + ) { + differs = true; + } + do_write_line(&mut output, line1, params.expand_tabs, params.tabsize, b"") + .expect("write to Vec is infallible"); + output.push(b'\n'); + } + line_number_expected += 1; + line_number_actual += 1; + } + } + } + + if flush_hunk( + &mut output, + &mut current_expected, + &mut current_actual, + ifdef_name, + params.expand_tabs, + params.tabsize, + ) { + differs = true; + } + + (output, differs) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsString; + + #[test] + fn test_identical() { + let params = Params { + ifdef_name: Some(OsString::from("ZZZ")), + ..Default::default() + }; + let (out, differs) = diff(b"1\n2\n3\n", b"1\n2\n3\n", ¶ms); + assert!(!differs); + assert_eq!(out, b"1\n2\n3\n"); + } + + #[test] + fn test_deleted_lines() { + let params = Params { + ifdef_name: Some(OsString::from("ZZZ")), + ..Default::default() + }; + let (out, differs) = diff(b"1\n2\n3\n", b"1\n3\n", ¶ms); + assert!(differs); + assert_eq!(out, b"1\n#ifndef ZZZ\n2\n#endif /* ! ZZZ */\n3\n"); + } + + #[test] + fn test_added_lines() { + let params = Params { + ifdef_name: Some(OsString::from("ZZZ")), + ..Default::default() + }; + let (out, differs) = diff(b"1\n3\n", b"1\n2\n3\n", ¶ms); + assert!(differs); + assert_eq!(out, b"1\n#ifdef ZZZ\n2\n#endif /* ZZZ */\n3\n"); + } + + #[test] + fn test_changed_lines() { + let params = Params { + ifdef_name: Some(OsString::from("ZZZ")), + ..Default::default() + }; + let (out, differs) = diff(b"1\n2\n3\n", b"1\nfoo\n3\n", ¶ms); + assert!(differs); + assert_eq!( + out, + b"1\n#ifndef ZZZ\n2\n#else /* ZZZ */\nfoo\n#endif /* ZZZ */\n3\n" + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index e1e43b6e..a06100c7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ pub mod cmp; pub mod color; pub mod context_diff; pub mod ed_diff; +pub mod ifdef_diff; pub mod macros; pub mod normal_diff; pub mod params; @@ -13,6 +14,7 @@ pub mod utils; // Re-export the public functions/types you need pub use context_diff::diff as context_diff; pub use ed_diff::diff as ed_diff; +pub use ifdef_diff::diff as ifdef_diff; pub use normal_diff::diff as normal_diff; pub use side_diff::diff as side_by_side_diff; pub use unified_diff::diff as unified_diff; diff --git a/src/main.rs b/src/main.rs index 2be28099..f4017b57 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,7 @@ mod context_diff; mod diff; mod dir_diff; mod ed_diff; +mod ifdef_diff; mod macros; mod normal_diff; mod params; diff --git a/src/params.rs b/src/params.rs index 84d2c7a5..925b0320 100644 --- a/src/params.rs +++ b/src/params.rs @@ -22,6 +22,7 @@ pub enum Format { Context, Ed, SideBySide, + Ifdef, } /// How to handle an operand that does not exist (`-N` and @@ -72,6 +73,7 @@ pub struct Params { pub to_missing: bool, pub from_label: Option, pub to_label: Option, + pub ifdef_name: Option, } impl Params { @@ -117,6 +119,7 @@ impl Default for Params { to_missing: false, from_label: None, to_label: None, + ifdef_name: None, } } } @@ -156,19 +159,7 @@ pub fn parse_params>( // the from-file in headers and messages, the second the to-file. // The label may be any bytes, so match on those, not on a str. let bytes = param.as_encoded_bytes(); - let label = if bytes == b"-L" || bytes == b"--label" { - Some(opts.next().map(|(_, label)| label).ok_or_else(|| { - format!("option '{}' requires an argument", param.to_string_lossy()) - })?) - } else { - bytes - .strip_prefix(b"--label=") - .or_else(|| bytes.strip_prefix(b"-L")) - // SAFETY: the bytes come from an OsStr and are split right - // after an ASCII prefix. - .map(|rest| unsafe { OsStr::from_encoded_bytes_unchecked(rest) }.to_os_string()) - }; - if let Some(label) = label { + if let Some(label) = option_os_value(bytes, ¶m, &mut opts, b"-L", b"--label")? { if params.from_label.is_none() { params.from_label = Some(label); } else if params.to_label.is_none() { @@ -178,6 +169,15 @@ pub fn parse_params>( } continue; } + // -D NAME, -DNAME, --ifdef NAME or --ifdef=NAME + if let Some(name) = option_os_value(bytes, ¶m, &mut opts, b"-D", b"--ifdef")? { + if format.is_some() && format != Some(Format::Ifdef) { + return Err("Conflicting output style options".to_string()); + } + format = Some(Format::Ifdef); + params.ifdef_name = Some(name); + continue; + } let next_param = opts.peek().map(|(_, next_param)| next_param); if param == "--" { break; @@ -456,6 +456,32 @@ fn directory_entry(dir: &Path, name: &OsStr, params: &Params) -> OsString { name.to_os_string() } +/// Parses `-X VALUE`, `-XVALUE`, `--long VALUE` or `--long=VALUE`. +/// The value is kept as an `OsString` so a non-UTF-8 name is not mangled. +fn option_os_value( + bytes: &[u8], + param: &OsStr, + opts: &mut impl Iterator, + short: &[u8], + long: &[u8], +) -> Result, String> { + if bytes == short || bytes == long { + return Ok(Some(opts.next().map(|(_, value)| value).ok_or_else( + || format!("option '{}' requires an argument", param.to_string_lossy()), + )?)); + } + + let attached = bytes + .strip_prefix(long) + .and_then(|rest| rest.strip_prefix(b"=")) + .or_else(|| bytes.strip_prefix(short)); + Ok(attached.map(|rest| { + // SAFETY: the bytes come from an OsStr and are split right + // after an ASCII prefix. + unsafe { OsStr::from_encoded_bytes_unchecked(rest) }.to_os_string() + })) +} + /// How the argument of an option is given. enum OptionArgument<'a> { /// In the same command line argument, as in `-Fx` or `--show-function-line=x`. @@ -890,6 +916,15 @@ mod tests { assert_eq!(params.to_label, Some(bytes(b"\xfenew"))); assert_eq!(params.from, os("foo")); assert_eq!(params.to, os("bar")); + + let params = parse_params( + [os("diff"), bytes(b"-D\xffmacro"), os("foo"), os("bar")] + .iter() + .cloned() + .peekable(), + ) + .unwrap(); + assert_eq!(params.ifdef_name, Some(bytes(b"\xffmacro"))); } #[rstest] diff --git a/tests/by-util/test_diff.rs b/tests/by-util/test_diff.rs index 5879b50a..120787d4 100644 --- a/tests/by-util/test_diff.rs +++ b/tests/by-util/test_diff.rs @@ -1336,3 +1336,107 @@ fn ignore_tab_expansion_with_differing_files() { .fails_with_code(1) .stdout_contains(" header\t1\n-old line\n+new line\n footer\t2\n"); } + +#[rstest] +#[case::separate(&["-D", "FOO"])] +#[case::joined(&["-DFOO"])] +#[case::long(&["--ifdef=FOO"])] +fn ifdef_diff_basic(#[case] flag: &[&str]) { + let (at, ts) = at_and_ts!(); + at.write("file1", "a\nb\nc\n"); + at.write("file2", "a\nx\nc\n"); + ts.ucmd() + .args(flag) + .args(&["file1", "file2"]) + .fails_with_code(1) + .stdout_is("a\n#ifndef FOO\nb\n#else /* FOO */\nx\n#endif /* FOO */\nc\n"); +} + +#[test] +fn ifdef_diff_identical() { + let (at, ts) = at_and_ts!(); + at.write("file1", "a\nb\nc\n"); + at.write("file2", "a\nb\nc\n"); + ts.ucmd() + .args(&["-D", "FOO", "file1", "file2"]) + .succeeds() + .stdout_is("a\nb\nc\n"); +} + +#[test] +fn ifdef_diff_identical_report() { + let (at, ts) = at_and_ts!(); + at.write("file1", "a\nb\nc\n"); + at.write("file2", "a\nb\nc\n"); + ts.ucmd() + .args(&["-DFOO", "-s", "file1", "file2"]) + .succeeds() + .stdout_is("a\nb\nc\nFiles file1 and file2 are identical\n"); +} + +#[test] +fn ifdef_diff_brief() { + let (at, ts) = at_and_ts!(); + at.write("file1", "a\nb\n"); + at.write("file2", "a\nx\n"); + ts.ucmd() + .args(&["--ifdef=FOO", "-q", "file1", "file2"]) + .fails_with_code(1) + .stdout_is("Files file1 and file2 differ\n"); +} + +#[test] +fn ifdef_diff_conflict_error() { + let (at, ts) = at_and_ts!(); + at.write("file1", "a\n"); + at.write("file2", "b\n"); + ts.ucmd() + .args(&["-D", "FOO", "-u", "file1", "file2"]) + .fails_with_code(2) + .stderr_contains("Conflicting output style options"); +} + +#[test] +fn ifdef_diff_missing_newline() { + let (at, ts) = at_and_ts!(); + // Identical files without trailing newline: GNU diff outputs with newline. + at.write("f_nonl1", "a\nb"); + at.write("f_nonl2", "a\nb"); + ts.ucmd() + .args(&["-DFOO", "f_nonl1", "f_nonl2"]) + .succeeds() + .stdout_is("a\nb\n"); + + // One side missing trailing newline, one side with newline. + at.write("f_nl", "a\nb\n"); + ts.ucmd() + .args(&["-DFOO", "f_nonl1", "f_nl"]) + .fails_with_code(1) + .stdout_is("a\n#ifndef FOO\nb\n#else /* FOO */\nb\n#endif /* FOO */\n"); + + // Both sides missing trailing newline, diff at EOF. + at.write("f_nonl3", "a\nc"); + ts.ucmd() + .args(&["-DFOO", "f_nonl1", "f_nonl3"]) + .fails_with_code(1) + .stdout_is("a\n#ifndef FOO\nb\n#else /* FOO */\nc\n#endif /* FOO */\n"); +} + +#[cfg(unix)] +#[test] +fn ifdef_diff_non_utf8_macro() { + use std::os::unix::ffi::OsStringExt; + let (at, ts) = at_and_ts!(); + at.write("file1", "a\nb\n"); + at.write("file2", "a\nx\n"); + let macro_arg = std::ffi::OsString::from_vec(b"-DFOO\xffBAR".to_vec()); + let res = ts + .ucmd() + .arg(macro_arg) + .args(&["file1", "file2"]) + .fails_with_code(1); + assert_eq!( + res.stdout(), + b"a\n#ifndef FOO\xffBAR\nb\n#else /* FOO\xffBAR */\nx\n#endif /* FOO\xffBAR */\n" + ); +}