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
23 changes: 18 additions & 5 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,6 +154,7 @@ 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),
Expand All @@ -166,6 +167,11 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome {
return Outcome::Trouble;
}
},
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 {
Expand All @@ -183,10 +189,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 All @@ -210,7 +223,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
196 changes: 196 additions & 0 deletions src/ifdef_diff.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
// 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"").unwrap();
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 {
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.
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"")
.unwrap();
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

}
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
33 changes: 33 additions & 0 deletions src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub enum Format {
Context,
Ed,
SideBySide,
Ifdef,
}

/// How to handle an operand that does not exist (`-N` and
Expand Down Expand Up @@ -71,6 +72,7 @@ pub struct Params {
pub to_missing: bool,
pub from_label: Option<OsString>,
pub to_label: Option<OsString>,
pub ifdef_name: Option<OsString>,
}

impl Params {
Expand Down Expand Up @@ -115,6 +117,7 @@ impl Default for Params {
to_missing: false,
from_label: None,
to_label: None,
ifdef_name: None,
}
}
}
Expand Down Expand Up @@ -178,6 +181,27 @@ pub fn parse_params<I: Iterator<Item = OsString>>(
}
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;
Expand Down Expand Up @@ -1259,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() {
Expand Down
Loading