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
2 changes: 1 addition & 1 deletion src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ pub fn colorize(output: &[u8], format: Format, palette: &Palette) -> Vec<u8> {
LineKind::Plain
}
}
Format::Ed | Format::SideBySide => LineKind::Plain,
Format::Ed | Format::SideBySide | Format::Ifdef => LineKind::Plain,
};
let sgr = match kind {
LineKind::Plain => {
Expand Down
26 changes: 20 additions & 6 deletions src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -154,20 +154,27 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome {
..params.clone()
};

let mut ifdef_differs = false;
// run diff
let result: Vec<u8> = 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 {
None => side_diff::diff(&from_content, &to_content, &mut stdout().lock(), params),
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() {
Expand All @@ -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()
Expand Down Expand Up @@ -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 {
Expand Down
193 changes: 193 additions & 0 deletions src/ifdef_diff.rs
Original file line number Diff line number Diff line change
@@ -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<u8>, 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<u8>, 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<u8>,
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<u8>, 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');

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.

this always adds a '\n', so identical files a\nb (no final newline) give a\nb\n.
GNU keeps the file as is, no?
please add a test with a missing newline at EOF, on one side and on both

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.

I checked GNU diff 3.10 on this. diff -D FOO on identical files whose last line has no newline (a\nb) writes a\nb\n and exits 0 — it does not keep the raw missing-newline bytes. The same extra newline is used when both sides lack a newline but the last lines differ. When only one side has a newline, GNU wraps that last line in #ifndef / #else, and ifdef_diff_missing_newline covers all three cases.

}
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", &params);
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", &params);
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", &params);
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", &params);
assert!(differs);
assert_eq!(
out,
b"1\n#ifndef ZZZ\n2\n#else /* ZZZ */\nfoo\n#endif /* ZZZ */\n3\n"
);
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading