From c21c950e010f64343d817b68b51efcc406cc02e9 Mon Sep 17 00:00:00 2001 From: Yunus Ardaguney Date: Thu, 19 Nov 2026 11:57:29 +0300 Subject: [PATCH 1/3] diff: add -D/--ifdef format support --- src/color.rs | 2 +- src/diff.rs | 51 ++++++++--- src/ifdef_diff.rs | 172 +++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 + src/main.rs | 1 + src/params.rs | 12 +++ tests/by-util/test_diff.rs | 59 +++++++++++++ 7 files changed, 284 insertions(+), 15 deletions(-) create mode 100644 src/ifdef_diff.rs diff --git a/src/color.rs b/src/color.rs index cc73c351..1fea56f1 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 55fd30e5..2b555d7d 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; @@ -155,38 +155,61 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { }; // 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), + let (result, differs) = match params.format { + Format::Normal => { + let res = normal_diff::diff(&from_content, &to_content, params); + let differs = !res.is_empty(); + (res, differs) + } + Format::Unified => { + let res = unified_diff::diff(&from_content, &to_content, params); + let differs = !res.is_empty(); + (res, differs) + } + Format::Context => { + let res = context_diff::diff(&from_content, &to_content, params); + let differs = !res.is_empty(); + (res, differs) + } Format::Ed => match ed_diff::diff(&from_content, &to_content, params) { - Ok(result) => result, + Ok(res) => { + let differs = !res.is_empty(); + (res, differs) + } Err(error) => { eprintln!("{error}"); return Outcome::Trouble; } }, + Format::Ifdef => ifdef_diff::diff(&from_content, &to_content, params), // Side by side output is streamed, unless a header may have to come // first. Format::SideBySide => match header { - None => side_diff::diff(&from_content, &to_content, &mut stdout().lock(), params), + None => { + let res = side_diff::diff(&from_content, &to_content, &mut stdout().lock(), params); + let differs = !res.is_empty(); + (res, differs) + } Some(header) => { let mut output = Vec::new(); - let result = side_diff::diff(&from_content, &to_content, &mut output, params); - if !result.is_empty() { + let res = side_diff::diff(&from_content, &to_content, &mut output, params); + let differs = !res.is_empty(); + if !res.is_empty() { output.splice(0..0, header.iter().copied()); } if stdout().write_all(&output).is_err() { return Outcome::Trouble; } - result + (res, differs) } }, }; - if params.brief && !result.is_empty() { - print_files_differ("Files", params); + 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() @@ -210,7 +233,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..227a8f93 --- /dev/null +++ b/src/ifdef_diff.rs @@ -0,0 +1,172 @@ +// 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::io::Write; + +use crate::params::Params; +use crate::utils::do_write_line; + +/// 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().unwrap_or(""); + 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> = Vec::new(); + let mut current_actual: Vec> = Vec::new(); + + let flush = |output: &mut Vec, + current_expected: &mut Vec>, + current_actual: &mut Vec>, + differs: &mut bool| { + if current_expected.is_empty() && current_actual.is_empty() { + return; + } + *differs = true; + match (!current_expected.is_empty(), !current_actual.is_empty()) { + (true, false) => { + writeln!(output, "#ifndef {ifdef_name}").unwrap(); + for line in current_expected.drain(..) { + do_write_line(output, &line, params.expand_tabs, params.tabsize).unwrap(); + output.push(b'\n'); + } + writeln!(output, "#endif /* ! {ifdef_name} */").unwrap(); + } + (false, true) => { + writeln!(output, "#ifdef {ifdef_name}").unwrap(); + for line in current_actual.drain(..) { + do_write_line(output, &line, params.expand_tabs, params.tabsize).unwrap(); + output.push(b'\n'); + } + writeln!(output, "#endif /* {ifdef_name} */").unwrap(); + } + (true, true) => { + writeln!(output, "#ifndef {ifdef_name}").unwrap(); + for line in current_expected.drain(..) { + do_write_line(output, &line, params.expand_tabs, params.tabsize).unwrap(); + output.push(b'\n'); + } + writeln!(output, "#else /* {ifdef_name} */").unwrap(); + for line in current_actual.drain(..) { + do_write_line(output, &line, params.expand_tabs, params.tabsize).unwrap(); + output.push(b'\n'); + } + writeln!(output, "#endif /* {ifdef_name} */").unwrap(); + } + (false, false) => unreachable!(), + } + }; + + for result in diff::slice(&expected_lines, &actual_lines) { + match result { + diff::Result::Left(str) => { + current_expected.push(str.to_vec()); + line_number_expected += 1; + } + diff::Result::Right(str) => { + current_actual.push(str.to_vec()); + line_number_actual += 1; + } + diff::Result::Both(str1, str2) => { + 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(str1.to_vec()); + current_actual.push(str2.to_vec()); + } else { + flush( + &mut output, + &mut current_expected, + &mut current_actual, + &mut differs, + ); + do_write_line(&mut output, str1, params.expand_tabs, params.tabsize).unwrap(); + output.push(b'\n'); + } + line_number_expected += 1; + line_number_actual += 1; + } + } + } + + flush( + &mut output, + &mut current_expected, + &mut current_actual, + &mut differs, + ); + + (output, differs) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_identical() { + let params = Params { + ifdef_name: Some("ZZZ".to_string()), + ..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("ZZZ".to_string()), + ..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("ZZZ".to_string()), + ..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("ZZZ".to_string()), + ..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 73ea45e0..58d0b43c 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 @@ -71,6 +72,7 @@ pub struct Params { pub to_missing: bool, pub from_label: Option, pub to_label: Option, + pub ifdef_name: Option, } impl Params { @@ -115,6 +117,7 @@ impl Default for Params { to_missing: false, from_label: None, to_label: None, + ifdef_name: None, } } } @@ -302,6 +305,15 @@ pub fn parse_params>( format = Some(Format::SideBySide); continue; } + if let Some(argument) = option_argument(¶m, "-D", "--ifdef") { + if format.is_some() && format != Some(Format::Ifdef) { + return Err("Conflicting output style options".to_string()); + } + format = Some(Format::Ifdef); + let val = argument_value(argument, ¶m, &mut opts)?; + params.ifdef_name = Some(val.to_string_lossy().into_owned()); + continue; + } if width_re.is_match(param.to_string_lossy().as_ref()) { let param = param.into_string().unwrap(); let width_str: &str = width_re diff --git a/tests/by-util/test_diff.rs b/tests/by-util/test_diff.rs index 6173c199..a6ba6192 100644 --- a/tests/by-util/test_diff.rs +++ b/tests/by-util/test_diff.rs @@ -1131,3 +1131,62 @@ fn label_errors(#[case] args: &[&str], #[case] error: &str) { .fails_with_code(2) .stderr_contains(error); } + +#[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"); +} From 16371a145ad6e4bf0dc3f2f9eac458b771595af2 Mon Sep 17 00:00:00 2001 From: Yunus Ardaguney Date: Fri, 20 Nov 2026 11:41:27 +0300 Subject: [PATCH 2/3] refactor(diff): address review feedback for -D/--ifdef format - preserve non-UTF-8 macro names using OsString and raw byte parsing - deduplicate diff format matching in compare_files - eliminate line-copy allocations in ifdef diff by storing &[u8] slices - extract helper functions for ifdef directive formatting and line output - add regression tests for non-UTF-8 macro names and missing newlines at EOF --- src/diff.rs | 50 ++++++++------------ src/ifdef_diff.rs | 93 +++++++++++++++++++++----------------- src/params.rs | 41 +++++++++++++---- tests/by-util/test_diff.rs | 45 ++++++++++++++++++ 4 files changed, 148 insertions(+), 81 deletions(-) diff --git a/src/diff.rs b/src/diff.rs index 2b555d7d..857e5677 100644 --- a/src/diff.rs +++ b/src/diff.rs @@ -154,56 +154,46 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { ..params.clone() }; + let mut ifdef_differs = false; // run diff - let (result, differs) = match params.format { - Format::Normal => { - let res = normal_diff::diff(&from_content, &to_content, params); - let differs = !res.is_empty(); - (res, differs) - } - Format::Unified => { - let res = unified_diff::diff(&from_content, &to_content, params); - let differs = !res.is_empty(); - (res, differs) - } - Format::Context => { - let res = context_diff::diff(&from_content, &to_content, params); - let differs = !res.is_empty(); - (res, differs) - } + 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 => match ed_diff::diff(&from_content, &to_content, params) { - Ok(res) => { - let differs = !res.is_empty(); - (res, differs) - } + Ok(result) => result, Err(error) => { eprintln!("{error}"); return Outcome::Trouble; } }, - Format::Ifdef => ifdef_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 { - None => { - let res = side_diff::diff(&from_content, &to_content, &mut stdout().lock(), params); - let differs = !res.is_empty(); - (res, differs) - } + None => side_diff::diff(&from_content, &to_content, &mut stdout().lock(), params), Some(header) => { let mut output = Vec::new(); - let res = side_diff::diff(&from_content, &to_content, &mut output, params); - let differs = !res.is_empty(); - if !res.is_empty() { + let result = side_diff::diff(&from_content, &to_content, &mut output, params); + if !result.is_empty() { output.splice(0..0, header.iter().copied()); } if stdout().write_all(&output).is_err() { return Outcome::Trouble; } - (res, differs) + result } }, }; + let differs = if params.format == Format::Ifdef { + ifdef_differs + } else { + !result.is_empty() + }; if params.brief { if differs { print_files_differ("Files", params); diff --git a/src/ifdef_diff.rs b/src/ifdef_diff.rs index 227a8f93..51f647ce 100644 --- a/src/ifdef_diff.rs +++ b/src/ifdef_diff.rs @@ -3,16 +3,36 @@ // For the full copyright and license information, please view the LICENSE-* // files that was distributed with this source code. -use std::io::Write; +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).unwrap(); + 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'); +} + /// 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().unwrap_or(""); + 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(); @@ -32,12 +52,12 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> (Vec, bool) let mut line_number_actual = 1; let mut differs = false; - let mut current_expected: Vec> = Vec::new(); - let mut current_actual: Vec> = Vec::new(); + let mut current_expected: Vec<&[u8]> = Vec::new(); + let mut current_actual: Vec<&[u8]> = Vec::new(); let flush = |output: &mut Vec, - current_expected: &mut Vec>, - current_actual: &mut Vec>, + current_expected: &mut Vec<&[u8]>, + current_actual: &mut Vec<&[u8]>, differs: &mut bool| { if current_expected.is_empty() && current_actual.is_empty() { return; @@ -45,54 +65,44 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> (Vec, bool) *differs = true; match (!current_expected.is_empty(), !current_actual.is_empty()) { (true, false) => { - writeln!(output, "#ifndef {ifdef_name}").unwrap(); - for line in current_expected.drain(..) { - do_write_line(output, &line, params.expand_tabs, params.tabsize).unwrap(); - output.push(b'\n'); - } - writeln!(output, "#endif /* ! {ifdef_name} */").unwrap(); + write_directive(output, b"#ifndef ", ifdef_name, None); + write_lines(output, current_expected, params.expand_tabs, params.tabsize); + write_directive(output, b"#endif /* ! ", ifdef_name, Some(b" */")); } (false, true) => { - writeln!(output, "#ifdef {ifdef_name}").unwrap(); - for line in current_actual.drain(..) { - do_write_line(output, &line, params.expand_tabs, params.tabsize).unwrap(); - output.push(b'\n'); - } - writeln!(output, "#endif /* {ifdef_name} */").unwrap(); + write_directive(output, b"#ifdef ", ifdef_name, None); + write_lines(output, current_actual, params.expand_tabs, params.tabsize); + write_directive(output, b"#endif /* ", ifdef_name, Some(b" */")); } (true, true) => { - writeln!(output, "#ifndef {ifdef_name}").unwrap(); - for line in current_expected.drain(..) { - do_write_line(output, &line, params.expand_tabs, params.tabsize).unwrap(); - output.push(b'\n'); - } - writeln!(output, "#else /* {ifdef_name} */").unwrap(); - for line in current_actual.drain(..) { - do_write_line(output, &line, params.expand_tabs, params.tabsize).unwrap(); - output.push(b'\n'); - } - writeln!(output, "#endif /* {ifdef_name} */").unwrap(); + write_directive(output, b"#ifndef ", ifdef_name, None); + write_lines(output, current_expected, params.expand_tabs, params.tabsize); + write_directive(output, b"#else /* ", ifdef_name, Some(b" */")); + write_lines(output, current_actual, params.expand_tabs, params.tabsize); + write_directive(output, b"#endif /* ", ifdef_name, Some(b" */")); } (false, false) => unreachable!(), } + current_expected.clear(); + current_actual.clear(); }; for result in diff::slice(&expected_lines, &actual_lines) { match result { - diff::Result::Left(str) => { - current_expected.push(str.to_vec()); + diff::Result::Left(&line) => { + current_expected.push(line); line_number_expected += 1; } - diff::Result::Right(str) => { - current_actual.push(str.to_vec()); + diff::Result::Right(&line) => { + current_actual.push(line); line_number_actual += 1; } - diff::Result::Both(str1, str2) => { + 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(str1.to_vec()); - current_actual.push(str2.to_vec()); + current_expected.push(line1); + current_actual.push(line2); } else { flush( &mut output, @@ -100,7 +110,7 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> (Vec, bool) &mut current_actual, &mut differs, ); - do_write_line(&mut output, str1, params.expand_tabs, params.tabsize).unwrap(); + do_write_line(&mut output, line1, params.expand_tabs, params.tabsize).unwrap(); output.push(b'\n'); } line_number_expected += 1; @@ -122,11 +132,12 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> (Vec, bool) #[cfg(test)] mod tests { use super::*; + use std::ffi::OsString; #[test] fn test_identical() { let params = Params { - ifdef_name: Some("ZZZ".to_string()), + ifdef_name: Some(OsString::from("ZZZ")), ..Default::default() }; let (out, differs) = diff(b"1\n2\n3\n", b"1\n2\n3\n", ¶ms); @@ -137,7 +148,7 @@ mod tests { #[test] fn test_deleted_lines() { let params = Params { - ifdef_name: Some("ZZZ".to_string()), + ifdef_name: Some(OsString::from("ZZZ")), ..Default::default() }; let (out, differs) = diff(b"1\n2\n3\n", b"1\n3\n", ¶ms); @@ -148,7 +159,7 @@ mod tests { #[test] fn test_added_lines() { let params = Params { - ifdef_name: Some("ZZZ".to_string()), + ifdef_name: Some(OsString::from("ZZZ")), ..Default::default() }; let (out, differs) = diff(b"1\n3\n", b"1\n2\n3\n", ¶ms); @@ -159,7 +170,7 @@ mod tests { #[test] fn test_changed_lines() { let params = Params { - ifdef_name: Some("ZZZ".to_string()), + ifdef_name: Some(OsString::from("ZZZ")), ..Default::default() }; let (out, differs) = diff(b"1\n2\n3\n", b"1\nfoo\n3\n", ¶ms); diff --git a/src/params.rs b/src/params.rs index 58d0b43c..2f135c9d 100644 --- a/src/params.rs +++ b/src/params.rs @@ -72,7 +72,7 @@ pub struct Params { pub to_missing: bool, pub from_label: Option, pub to_label: Option, - pub ifdef_name: Option, + pub ifdef_name: Option, } impl Params { @@ -181,6 +181,27 @@ pub fn parse_params>( } continue; } + // -D NAME, -DNAME, --ifdef NAME or --ifdef=NAME + let ifdef = if bytes == b"-D" || bytes == b"--ifdef" { + Some(opts.next().map(|(_, val)| val).ok_or_else(|| { + format!("option '{}' requires an argument", param.to_string_lossy()) + })?) + } else { + bytes + .strip_prefix(b"--ifdef=") + .or_else(|| bytes.strip_prefix(b"-D")) + // 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(name) = 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; @@ -305,15 +326,6 @@ pub fn parse_params>( format = Some(Format::SideBySide); continue; } - if let Some(argument) = option_argument(¶m, "-D", "--ifdef") { - if format.is_some() && format != Some(Format::Ifdef) { - return Err("Conflicting output style options".to_string()); - } - format = Some(Format::Ifdef); - let val = argument_value(argument, ¶m, &mut opts)?; - params.ifdef_name = Some(val.to_string_lossy().into_owned()); - continue; - } if width_re.is_match(param.to_string_lossy().as_ref()) { let param = param.into_string().unwrap(); let width_str: &str = width_re @@ -1271,6 +1283,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"))); } #[test] fn double_dash() { diff --git a/tests/by-util/test_diff.rs b/tests/by-util/test_diff.rs index a6ba6192..b28c5dae 100644 --- a/tests/by-util/test_diff.rs +++ b/tests/by-util/test_diff.rs @@ -1190,3 +1190,48 @@ fn ifdef_diff_conflict_error() { .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" + ); +} From 4831b437f4017962bf339cee2179ca376e5a3878 Mon Sep 17 00:00:00 2001 From: Yunus Ardaguney Date: Fri, 20 Nov 2026 17:49:52 +0300 Subject: [PATCH 3/3] fix(diff): adapt ifdef_diff to upstream do_write_line marker parameter --- src/ifdef_diff.rs | 93 +++++++++++++++++++++++++++-------------------- 1 file changed, 53 insertions(+), 40 deletions(-) diff --git a/src/ifdef_diff.rs b/src/ifdef_diff.rs index 51f647ce..be0044ea 100644 --- a/src/ifdef_diff.rs +++ b/src/ifdef_diff.rs @@ -10,7 +10,7 @@ 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).unwrap(); + do_write_line(output, line, expand_tabs, tabsize, b"").unwrap(); output.push(b'\n'); } } @@ -24,6 +24,42 @@ fn write_directive(output: &mut Vec, prefix: &[u8], name: &[u8], suffix: Opt 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 { + if current_expected.is_empty() && current_actual.is_empty() { + return false; + } + 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) => unreachable!(), + } + 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. @@ -55,38 +91,6 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> (Vec, bool) let mut current_expected: Vec<&[u8]> = Vec::new(); let mut current_actual: Vec<&[u8]> = Vec::new(); - let flush = |output: &mut Vec, - current_expected: &mut Vec<&[u8]>, - current_actual: &mut Vec<&[u8]>, - differs: &mut bool| { - if current_expected.is_empty() && current_actual.is_empty() { - return; - } - *differs = true; - match (!current_expected.is_empty(), !current_actual.is_empty()) { - (true, false) => { - write_directive(output, b"#ifndef ", ifdef_name, None); - write_lines(output, current_expected, params.expand_tabs, params.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, params.expand_tabs, params.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, params.expand_tabs, params.tabsize); - write_directive(output, b"#else /* ", ifdef_name, Some(b" */")); - write_lines(output, current_actual, params.expand_tabs, params.tabsize); - write_directive(output, b"#endif /* ", ifdef_name, Some(b" */")); - } - (false, false) => unreachable!(), - } - current_expected.clear(); - current_actual.clear(); - }; - for result in diff::slice(&expected_lines, &actual_lines) { match result { diff::Result::Left(&line) => { @@ -104,13 +108,18 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> (Vec, bool) current_expected.push(line1); current_actual.push(line2); } else { - flush( + if flush_hunk( &mut output, &mut current_expected, &mut current_actual, - &mut differs, - ); - do_write_line(&mut output, line1, params.expand_tabs, params.tabsize).unwrap(); + ifdef_name, + params.expand_tabs, + params.tabsize, + ) { + differs = true; + } + do_write_line(&mut output, line1, params.expand_tabs, params.tabsize, b"") + .unwrap(); output.push(b'\n'); } line_number_expected += 1; @@ -119,12 +128,16 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> (Vec, bool) } } - flush( + if flush_hunk( &mut output, &mut current_expected, &mut current_actual, - &mut differs, - ); + ifdef_name, + params.expand_tabs, + params.tabsize, + ) { + differs = true; + } (output, differs) }