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
187 changes: 187 additions & 0 deletions src/ifdef_diff.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
// 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 {
differs |= flush_hunk(
&mut output,
&mut current_expected,
&mut current_actual,
ifdef_name,
params.expand_tabs,
params.tabsize,
);
write_lines(&mut output, &[line1], params.expand_tabs, params.tabsize);
}
line_number_expected += 1;
line_number_actual += 1;
}
}
}

differs |= flush_hunk(
&mut output,
&mut current_expected,
&mut current_actual,
ifdef_name,
params.expand_tabs,
params.tabsize,
);

(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
61 changes: 48 additions & 13 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 @@ -72,6 +73,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 @@ -117,6 +119,7 @@ impl Default for Params {
to_missing: false,
from_label: None,
to_label: None,
ifdef_name: None,
}
}
}
Expand Down Expand Up @@ -156,19 +159,7 @@ pub fn parse_params<I: Iterator<Item = OsString>>(
// 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, &param, &mut opts, b"-L", b"--label")? {
if params.from_label.is_none() {
params.from_label = Some(label);
} else if params.to_label.is_none() {
Expand All @@ -178,6 +169,15 @@ pub fn parse_params<I: Iterator<Item = OsString>>(
}
continue;
}
// -D NAME, -DNAME, --ifdef NAME or --ifdef=NAME
if let Some(name) = option_os_value(bytes, &param, &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;
Expand Down Expand Up @@ -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<Item = (usize, OsString)>,
short: &[u8],
long: &[u8],
) -> Result<Option<OsString>, 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`.
Expand Down Expand Up @@ -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]
Expand Down
Loading
Loading