userland: search and exec tools, spawn library (T14)
rg (ripgrep 15.2), grep (ours, on ripgrep's regex crates), find and xargs (ours), sed (uutils 0.3 wrapper), diff and cmp (uutils diffutils 0.6 with -r), fd 10.5, jaq 2.3, env and timeout. userland/spawn is a small Command-like client of the process interface. search-test.nu: 42 cases match native tools.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,998 @@
|
||||
// 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::collections::VecDeque;
|
||||
use std::io::Write;
|
||||
|
||||
use crate::params::Params;
|
||||
use crate::utils::do_write_line;
|
||||
use crate::utils::get_modification_time;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum DiffLine {
|
||||
Context(Vec<u8>),
|
||||
Change(Vec<u8>),
|
||||
Add(Vec<u8>),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Mismatch {
|
||||
pub line_number_expected: usize,
|
||||
pub line_number_actual: usize,
|
||||
pub expected: Vec<DiffLine>,
|
||||
pub actual: Vec<DiffLine>,
|
||||
pub expected_missing_nl: bool,
|
||||
pub actual_missing_nl: bool,
|
||||
pub expected_all_context: bool,
|
||||
pub actual_all_context: bool,
|
||||
}
|
||||
|
||||
impl Mismatch {
|
||||
fn new(line_number_expected: usize, line_number_actual: usize) -> Mismatch {
|
||||
Mismatch {
|
||||
line_number_expected,
|
||||
line_number_actual,
|
||||
expected: Vec::new(),
|
||||
actual: Vec::new(),
|
||||
expected_missing_nl: false,
|
||||
actual_missing_nl: false,
|
||||
expected_all_context: false,
|
||||
actual_all_context: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of changed lines with no common line between them.
|
||||
struct ChangeBlock {
|
||||
expected_start: usize,
|
||||
actual_start: usize,
|
||||
deletes: bool,
|
||||
inserts: bool,
|
||||
}
|
||||
|
||||
impl ChangeBlock {
|
||||
fn new(mismatch: &Mismatch) -> Self {
|
||||
Self {
|
||||
expected_start: mismatch.expected.len(),
|
||||
actual_start: mismatch.actual.len(),
|
||||
deletes: false,
|
||||
inserts: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a block at the end of `mismatch` if none is open, and records
|
||||
/// whether it deletes or inserts lines.
|
||||
fn mark(block: &mut Option<Self>, mismatch: &Mismatch, deletes: bool, inserts: bool) {
|
||||
let block = block.get_or_insert_with(|| Self::new(mismatch));
|
||||
block.deletes |= deletes;
|
||||
block.inserts |= inserts;
|
||||
}
|
||||
|
||||
fn close(block: &mut Option<Self>, mismatch: &mut Mismatch) {
|
||||
if let Some(block) = block.take() {
|
||||
block.finish(mismatch);
|
||||
}
|
||||
}
|
||||
|
||||
/// Like GNU diff, a block that both deletes and inserts lines marks all of
|
||||
/// them as changed (`!`), not only as many as pair up.
|
||||
fn finish(self, mismatch: &mut Mismatch) {
|
||||
if !(self.deletes && self.inserts) {
|
||||
return;
|
||||
}
|
||||
let expected = mismatch.expected[self.expected_start..].iter_mut();
|
||||
let actual = mismatch.actual[self.actual_start..].iter_mut();
|
||||
for line in expected.chain(actual) {
|
||||
if let DiffLine::Add(content) = line {
|
||||
*line = DiffLine::Change(std::mem::take(content));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Produces a diff between the expected output and actual output.
|
||||
fn make_diff(
|
||||
expected: &[u8],
|
||||
actual: &[u8],
|
||||
context_size: usize,
|
||||
stop_early: bool,
|
||||
) -> Vec<Mismatch> {
|
||||
let mut line_number_expected = 1;
|
||||
let mut line_number_actual = 1;
|
||||
let mut context_queue: VecDeque<&[u8]> = VecDeque::with_capacity(context_size);
|
||||
// Like GNU diff, keep changes in one hunk while at most twice the context
|
||||
// size of unchanged lines separates them.
|
||||
let max_gap = 2 * context_size;
|
||||
let mut lines_since_mismatch = max_gap + 1;
|
||||
let mut results = Vec::new();
|
||||
let mut mismatch = Mismatch::new(0, 0);
|
||||
|
||||
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();
|
||||
|
||||
debug_assert_eq!(b"".split(|&c| c == b'\n').count(), 1);
|
||||
// ^ means that underflow here is impossible
|
||||
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 block: Option<ChangeBlock> = None;
|
||||
|
||||
for result in diff::slice(&expected_lines, &actual_lines) {
|
||||
match result {
|
||||
diff::Result::Left(str) => {
|
||||
if lines_since_mismatch > max_gap {
|
||||
results.push(mismatch);
|
||||
mismatch = Mismatch::new(
|
||||
line_number_expected - context_queue.len(),
|
||||
line_number_actual - context_queue.len(),
|
||||
);
|
||||
}
|
||||
|
||||
while let Some(line) = context_queue.pop_front() {
|
||||
mismatch.expected.push(DiffLine::Context(line.to_vec()));
|
||||
mismatch.actual.push(DiffLine::Context(line.to_vec()));
|
||||
}
|
||||
|
||||
ChangeBlock::mark(&mut block, &mismatch, true, false);
|
||||
mismatch.expected.push(DiffLine::Add(str.to_vec()));
|
||||
if line_number_expected > expected_lines_count {
|
||||
mismatch.expected_missing_nl = true;
|
||||
}
|
||||
line_number_expected += 1;
|
||||
lines_since_mismatch = 0;
|
||||
}
|
||||
diff::Result::Right(str) => {
|
||||
if lines_since_mismatch > max_gap {
|
||||
results.push(mismatch);
|
||||
mismatch = Mismatch::new(
|
||||
line_number_expected - context_queue.len(),
|
||||
line_number_actual - context_queue.len(),
|
||||
);
|
||||
}
|
||||
|
||||
while let Some(line) = context_queue.pop_front() {
|
||||
mismatch.expected.push(DiffLine::Context(line.to_vec()));
|
||||
mismatch.actual.push(DiffLine::Context(line.to_vec()));
|
||||
}
|
||||
|
||||
ChangeBlock::mark(&mut block, &mismatch, false, true);
|
||||
mismatch.actual.push(DiffLine::Add(str.to_vec()));
|
||||
if line_number_actual > actual_lines_count {
|
||||
mismatch.actual_missing_nl = true;
|
||||
}
|
||||
line_number_actual += 1;
|
||||
lines_since_mismatch = 0;
|
||||
}
|
||||
diff::Result::Both(str, _) => {
|
||||
// if one of them is missing a newline and the other isn't, then they don't actually match
|
||||
if (line_number_actual > actual_lines_count)
|
||||
&& (line_number_expected > expected_lines_count)
|
||||
{
|
||||
ChangeBlock::close(&mut block, &mut mismatch);
|
||||
if context_queue.len() < context_size {
|
||||
while let Some(line) = context_queue.pop_front() {
|
||||
mismatch.expected.push(DiffLine::Context(line.to_vec()));
|
||||
mismatch.actual.push(DiffLine::Context(line.to_vec()));
|
||||
}
|
||||
if lines_since_mismatch < context_size {
|
||||
mismatch.expected.push(DiffLine::Context(str.to_vec()));
|
||||
mismatch.actual.push(DiffLine::Context(str.to_vec()));
|
||||
mismatch.expected_missing_nl = true;
|
||||
mismatch.actual_missing_nl = true;
|
||||
}
|
||||
}
|
||||
lines_since_mismatch = 0;
|
||||
} else if line_number_actual > actual_lines_count {
|
||||
if lines_since_mismatch > max_gap {
|
||||
results.push(mismatch);
|
||||
mismatch = Mismatch::new(
|
||||
line_number_expected - context_queue.len(),
|
||||
line_number_actual - context_queue.len(),
|
||||
);
|
||||
}
|
||||
while let Some(line) = context_queue.pop_front() {
|
||||
mismatch.expected.push(DiffLine::Context(line.to_vec()));
|
||||
mismatch.actual.push(DiffLine::Context(line.to_vec()));
|
||||
}
|
||||
ChangeBlock::mark(&mut block, &mismatch, true, true);
|
||||
mismatch.expected.push(DiffLine::Change(str.to_vec()));
|
||||
mismatch.actual.push(DiffLine::Change(str.to_vec()));
|
||||
mismatch.actual_missing_nl = true;
|
||||
lines_since_mismatch = 0;
|
||||
} else if line_number_expected > expected_lines_count {
|
||||
if lines_since_mismatch > max_gap {
|
||||
results.push(mismatch);
|
||||
mismatch = Mismatch::new(
|
||||
line_number_expected - context_queue.len(),
|
||||
line_number_actual - context_queue.len(),
|
||||
);
|
||||
}
|
||||
while let Some(line) = context_queue.pop_front() {
|
||||
mismatch.expected.push(DiffLine::Context(line.to_vec()));
|
||||
mismatch.actual.push(DiffLine::Context(line.to_vec()));
|
||||
}
|
||||
ChangeBlock::mark(&mut block, &mismatch, true, true);
|
||||
mismatch.expected.push(DiffLine::Change(str.to_vec()));
|
||||
mismatch.expected_missing_nl = true;
|
||||
mismatch.actual.push(DiffLine::Change(str.to_vec()));
|
||||
lines_since_mismatch = 0;
|
||||
} else {
|
||||
ChangeBlock::close(&mut block, &mut mismatch);
|
||||
debug_assert!(context_queue.len() <= context_size);
|
||||
if context_queue.len() >= context_size {
|
||||
let _ = context_queue.pop_front();
|
||||
}
|
||||
if lines_since_mismatch < context_size {
|
||||
mismatch.expected.push(DiffLine::Context(str.to_vec()));
|
||||
mismatch.actual.push(DiffLine::Context(str.to_vec()));
|
||||
} else if context_size > 0 {
|
||||
context_queue.push_back(str);
|
||||
}
|
||||
lines_since_mismatch += 1;
|
||||
}
|
||||
line_number_expected += 1;
|
||||
line_number_actual += 1;
|
||||
}
|
||||
}
|
||||
if stop_early && !results.is_empty() {
|
||||
// Optimization: stop analyzing the files as soon as there are any differences
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(block) = block {
|
||||
block.finish(&mut mismatch);
|
||||
}
|
||||
results.push(mismatch);
|
||||
results.remove(0);
|
||||
|
||||
if results.is_empty() && expected_lines_count != actual_lines_count {
|
||||
let mut mismatch = Mismatch::new(expected_lines.len(), actual_lines.len());
|
||||
// empty diff and only expected lines has a missing line at end
|
||||
if expected_lines_count != expected_lines.len() {
|
||||
mismatch.expected.push(DiffLine::Change(
|
||||
expected_lines
|
||||
.pop()
|
||||
.expect("can't be empty; produced by split()")
|
||||
.to_vec(),
|
||||
));
|
||||
mismatch.expected_missing_nl = true;
|
||||
mismatch.actual.push(DiffLine::Change(
|
||||
actual_lines
|
||||
.pop()
|
||||
.expect("can't be empty; produced by split()")
|
||||
.to_vec(),
|
||||
));
|
||||
results.push(mismatch);
|
||||
} else if actual_lines_count != actual_lines.len() {
|
||||
mismatch.expected.push(DiffLine::Change(
|
||||
expected_lines
|
||||
.pop()
|
||||
.expect("can't be empty; produced by split()")
|
||||
.to_vec(),
|
||||
));
|
||||
mismatch.actual.push(DiffLine::Change(
|
||||
actual_lines
|
||||
.pop()
|
||||
.expect("can't be empty; produced by split()")
|
||||
.to_vec(),
|
||||
));
|
||||
mismatch.actual_missing_nl = true;
|
||||
results.push(mismatch);
|
||||
}
|
||||
}
|
||||
|
||||
// hunks with pure context lines get truncated to empty
|
||||
for mismatch in &mut results {
|
||||
if !mismatch
|
||||
.expected
|
||||
.iter()
|
||||
.any(|x| !matches!(&x, DiffLine::Context(_)))
|
||||
{
|
||||
mismatch.expected_all_context = true;
|
||||
}
|
||||
if !mismatch
|
||||
.actual
|
||||
.iter()
|
||||
.any(|x| !matches!(&x, DiffLine::Context(_)))
|
||||
{
|
||||
mismatch.actual_all_context = true;
|
||||
}
|
||||
}
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<u8> {
|
||||
let from_modified_time = get_modification_time(¶ms.from.to_string_lossy());
|
||||
let to_modified_time = get_modification_time(¶ms.to.to_string_lossy());
|
||||
let mut output = format!(
|
||||
"*** {0}\t{1}\n--- {2}\t{3}\n",
|
||||
params.from.to_string_lossy(),
|
||||
from_modified_time,
|
||||
params.to.to_string_lossy(),
|
||||
to_modified_time
|
||||
)
|
||||
.into_bytes();
|
||||
let diff_results = make_diff(expected, actual, params.context_count, params.brief);
|
||||
if diff_results.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
if params.brief {
|
||||
return output;
|
||||
}
|
||||
for result in diff_results {
|
||||
let mut line_number_expected = result.line_number_expected;
|
||||
let mut line_number_actual = result.line_number_actual;
|
||||
let mut expected_count = result.expected.len();
|
||||
let mut actual_count = result.actual.len();
|
||||
if expected_count == 0 {
|
||||
line_number_expected -= 1;
|
||||
expected_count = 1;
|
||||
}
|
||||
if actual_count == 0 {
|
||||
line_number_actual -= 1;
|
||||
actual_count = 1;
|
||||
}
|
||||
let end_line_number_expected = expected_count + line_number_expected - 1;
|
||||
let end_line_number_actual = actual_count + line_number_actual - 1;
|
||||
let exp_start = if end_line_number_expected == line_number_expected {
|
||||
String::new()
|
||||
} else {
|
||||
format!("{line_number_expected},")
|
||||
};
|
||||
let act_start = if end_line_number_actual == line_number_actual {
|
||||
String::new()
|
||||
} else {
|
||||
format!("{line_number_actual},")
|
||||
};
|
||||
writeln!(
|
||||
output,
|
||||
"***************\n*** {exp_start}{end_line_number_expected} ****"
|
||||
)
|
||||
.expect("write to Vec is infallible");
|
||||
if !result.expected_all_context {
|
||||
for line in result.expected {
|
||||
match line {
|
||||
DiffLine::Context(e) => {
|
||||
write!(output, " ").expect("write to Vec is infallible");
|
||||
do_write_line(&mut output, &e, params.expand_tabs, params.tabsize)
|
||||
.expect("write to Vec is infallible");
|
||||
writeln!(output).unwrap();
|
||||
}
|
||||
DiffLine::Change(e) => {
|
||||
write!(output, "! ").expect("write to Vec is infallible");
|
||||
do_write_line(&mut output, &e, params.expand_tabs, params.tabsize)
|
||||
.expect("write to Vec is infallible");
|
||||
writeln!(output).unwrap();
|
||||
}
|
||||
DiffLine::Add(e) => {
|
||||
write!(output, "- ").expect("write to Vec is infallible");
|
||||
do_write_line(&mut output, &e, params.expand_tabs, params.tabsize)
|
||||
.expect("write to Vec is infallible");
|
||||
writeln!(output).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
if result.expected_missing_nl {
|
||||
writeln!(output, r"\ No newline at end of file")
|
||||
.expect("write to Vec is infallible");
|
||||
}
|
||||
}
|
||||
writeln!(output, "--- {act_start}{end_line_number_actual} ----")
|
||||
.expect("write to Vec is infallible");
|
||||
if !result.actual_all_context {
|
||||
for line in result.actual {
|
||||
match line {
|
||||
DiffLine::Context(e) => {
|
||||
write!(output, " ").expect("write to Vec is infallible");
|
||||
do_write_line(&mut output, &e, params.expand_tabs, params.tabsize)
|
||||
.expect("write to Vec is infallible");
|
||||
writeln!(output).unwrap();
|
||||
}
|
||||
DiffLine::Change(e) => {
|
||||
write!(output, "! ").expect("write to Vec is infallible");
|
||||
do_write_line(&mut output, &e, params.expand_tabs, params.tabsize)
|
||||
.expect("write to Vec is infallible");
|
||||
writeln!(output).unwrap();
|
||||
}
|
||||
DiffLine::Add(e) => {
|
||||
write!(output, "+ ").expect("write to Vec is infallible");
|
||||
do_write_line(&mut output, &e, params.expand_tabs, params.tabsize)
|
||||
.expect("write to Vec is infallible");
|
||||
writeln!(output).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
if result.actual_missing_nl {
|
||||
writeln!(output, r"\ No newline at end of file")
|
||||
.expect("write to Vec is infallible");
|
||||
}
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use crate::utils::testcmds::PATCH_CMD;
|
||||
|
||||
#[test]
|
||||
fn test_permutations() {
|
||||
// test all possible six-line files.
|
||||
let target = "target/context-diff/";
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"a\n" } else { b"b\n" })
|
||||
.unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"c\n" } else { b"d\n" })
|
||||
.unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"e\n" } else { b"f\n" })
|
||||
.unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"g\n" } else { b"h\n" })
|
||||
.unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"h\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"i\n" } else { b"j\n" })
|
||||
.unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"j\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"k\n" } else { b"l\n" })
|
||||
.unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"l\n").unwrap();
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let patched = &format!("{target}/alef");
|
||||
let diff = diff(
|
||||
&alef,
|
||||
&bet,
|
||||
&Params {
|
||||
from: patched.into(),
|
||||
to: patched.into(),
|
||||
context_count: 2,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
File::create(format!("{target}/ab.diff"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alef")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/bet")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
let output = PATCH_CMD
|
||||
.new()
|
||||
.arg("-p0")
|
||||
.arg("--context")
|
||||
.stdin(File::open(format!("{target}/ab.diff")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = fs::read(format!("{target}/alef")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations_empty_lines() {
|
||||
let target = "target/context-diff/";
|
||||
// test all possible six-line files with missing newlines.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"\n" } else { b"b\n" }).unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"\n" } else { b"d\n" }).unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"\n" } else { b"f\n" }).unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"\n" } else { b"h\n" }).unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"h\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"\n" } else { b"j\n" }).unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"j\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"\n" } else { b"l\n" }).unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"l\n").unwrap();
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let patched = &format!("{target}/alef_");
|
||||
let diff = diff(
|
||||
&alef,
|
||||
&bet,
|
||||
&Params {
|
||||
from: patched.into(),
|
||||
to: patched.into(),
|
||||
context_count: 2,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
File::create(format!("{target}/ab_.diff"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alef_")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/bet_")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
let output = PATCH_CMD
|
||||
.new()
|
||||
.arg("-p0")
|
||||
.arg("--context")
|
||||
.stdin(File::open(format!("{target}/ab_.diff")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = fs::read(format!("{target}/alef_")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations_missing_lines() {
|
||||
let target = "target/context-diff/";
|
||||
// test all possible six-line files.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"a\n" } else { b"" }).unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"c\n" } else { b"" }).unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"e\n" } else { b"" }).unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"g\n" } else { b"" }).unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"h\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"i\n" } else { b"" }).unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"j\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"k\n" } else { b"" }).unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"l\n").unwrap();
|
||||
}
|
||||
if alef.is_empty() && bet.is_empty() {
|
||||
continue;
|
||||
};
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let patched = &format!("{target}/alefx");
|
||||
let diff = diff(
|
||||
&alef,
|
||||
&bet,
|
||||
&Params {
|
||||
from: patched.into(),
|
||||
to: patched.into(),
|
||||
context_count: 2,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
File::create(format!("{target}/abx.diff"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alefx")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/betx")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
let output = PATCH_CMD
|
||||
.new()
|
||||
.arg("-p0")
|
||||
.arg("--context")
|
||||
.stdin(File::open(format!("{target}/abx.diff")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = fs::read(format!("{target}/alefx")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations_reverse() {
|
||||
let target = "target/context-diff/";
|
||||
// test all possible six-line files.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"a\n" } else { b"f\n" })
|
||||
.unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"a\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"b\n" } else { b"e\n" })
|
||||
.unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"c\n" } else { b"d\n" })
|
||||
.unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"c\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"d\n" } else { b"c\n" })
|
||||
.unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"e\n" } else { b"b\n" })
|
||||
.unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"e\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"f\n" } else { b"a\n" })
|
||||
.unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let alefr_path = &format!("{target}/alefr");
|
||||
let diff = diff(
|
||||
&alef,
|
||||
&bet,
|
||||
&Params {
|
||||
from: alefr_path.into(),
|
||||
to: alefr_path.into(),
|
||||
context_count: 2,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
File::create(format!("{target}/abr.diff"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alefr")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/betr")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
let output = PATCH_CMD
|
||||
.new()
|
||||
.arg("-p0")
|
||||
.arg("--context")
|
||||
.stdin(File::open(format!("{target}/abr.diff")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = fs::read(format!("{target}/alefr")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stop_early() {
|
||||
use crate::assert_diff_eq;
|
||||
|
||||
let from_filename = "foo";
|
||||
let from = ["a", "b", "c", ""].join("\n");
|
||||
let to_filename = "bar";
|
||||
let to = ["a", "d", "c", ""].join("\n");
|
||||
|
||||
let diff_full = diff(
|
||||
from.as_bytes(),
|
||||
to.as_bytes(),
|
||||
&Params {
|
||||
from: from_filename.into(),
|
||||
to: to_filename.into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
let expected_full = [
|
||||
"*** foo\tTIMESTAMP",
|
||||
"--- bar\tTIMESTAMP",
|
||||
"***************",
|
||||
"*** 1,3 ****",
|
||||
" a",
|
||||
"! b",
|
||||
" c",
|
||||
"--- 1,3 ----",
|
||||
" a",
|
||||
"! d",
|
||||
" c",
|
||||
"",
|
||||
]
|
||||
.join("\n");
|
||||
assert_diff_eq!(diff_full, expected_full);
|
||||
|
||||
let diff_brief = diff(
|
||||
from.as_bytes(),
|
||||
to.as_bytes(),
|
||||
&Params {
|
||||
from: from_filename.into(),
|
||||
to: to_filename.into(),
|
||||
brief: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
let expected_brief = ["*** foo\tTIMESTAMP", "--- bar\tTIMESTAMP", ""].join("\n");
|
||||
assert_diff_eq!(diff_brief, expected_brief);
|
||||
|
||||
let nodiff_full = diff(
|
||||
from.as_bytes(),
|
||||
from.as_bytes(),
|
||||
&Params {
|
||||
from: from_filename.into(),
|
||||
to: to_filename.into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert!(nodiff_full.is_empty());
|
||||
|
||||
let nodiff_brief = diff(
|
||||
from.as_bytes(),
|
||||
from.as_bytes(),
|
||||
&Params {
|
||||
from: from_filename.into(),
|
||||
to: to_filename.into(),
|
||||
brief: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert!(nodiff_brief.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_change_block_lines_all_changed() {
|
||||
use crate::assert_diff_eq;
|
||||
|
||||
let params = Params {
|
||||
from: "foo".into(),
|
||||
to: "bar".into(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Two lines replaced by one: both old lines are changed, not one deleted.
|
||||
let from = ["a", "b", "c", "d", ""].join("\n");
|
||||
let to = ["a", "x", "d", ""].join("\n");
|
||||
let expected = [
|
||||
"*** foo\tTIMESTAMP",
|
||||
"--- bar\tTIMESTAMP",
|
||||
"***************",
|
||||
"*** 1,4 ****",
|
||||
" a",
|
||||
"! b",
|
||||
"! c",
|
||||
" d",
|
||||
"--- 1,3 ----",
|
||||
" a",
|
||||
"! x",
|
||||
" d",
|
||||
"",
|
||||
]
|
||||
.join("\n");
|
||||
let output = diff(from.as_bytes(), to.as_bytes(), ¶ms);
|
||||
assert_diff_eq!(output, expected);
|
||||
|
||||
// One line replaced by three: all three new lines are changed.
|
||||
let from = ["a", "b", ""].join("\n");
|
||||
let to = ["a", "x", "y", "z", ""].join("\n");
|
||||
let expected = [
|
||||
"*** foo\tTIMESTAMP",
|
||||
"--- bar\tTIMESTAMP",
|
||||
"***************",
|
||||
"*** 1,2 ****",
|
||||
" a",
|
||||
"! b",
|
||||
"--- 1,4 ----",
|
||||
" a",
|
||||
"! x",
|
||||
"! y",
|
||||
"! z",
|
||||
"",
|
||||
]
|
||||
.join("\n");
|
||||
let output = diff(from.as_bytes(), to.as_bytes(), ¶ms);
|
||||
assert_diff_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hunk_merging() {
|
||||
use crate::assert_diff_eq;
|
||||
|
||||
let params = Params {
|
||||
from: "foo".into(),
|
||||
to: "bar".into(),
|
||||
context_count: 1,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Changes separated by up to twice the context size share one hunk.
|
||||
let from = ["a", "b", "c", "d", "e", "f", ""].join("\n");
|
||||
let to = ["a", "B", "c", "d", "E", "f", ""].join("\n");
|
||||
let expected = [
|
||||
"*** foo\tTIMESTAMP",
|
||||
"--- bar\tTIMESTAMP",
|
||||
"***************",
|
||||
"*** 1,6 ****",
|
||||
" a",
|
||||
"! b",
|
||||
" c",
|
||||
" d",
|
||||
"! e",
|
||||
" f",
|
||||
"--- 1,6 ----",
|
||||
" a",
|
||||
"! B",
|
||||
" c",
|
||||
" d",
|
||||
"! E",
|
||||
" f",
|
||||
"",
|
||||
]
|
||||
.join("\n");
|
||||
let output = diff(from.as_bytes(), to.as_bytes(), ¶ms);
|
||||
assert_diff_eq!(output, expected);
|
||||
|
||||
// One more unchanged line between them splits the hunk.
|
||||
let from = ["a", "b", "c", "d", "e", "f", "g", ""].join("\n");
|
||||
let to = ["a", "B", "c", "d", "e", "F", "g", ""].join("\n");
|
||||
let expected = [
|
||||
"*** foo\tTIMESTAMP",
|
||||
"--- bar\tTIMESTAMP",
|
||||
"***************",
|
||||
"*** 1,3 ****",
|
||||
" a",
|
||||
"! b",
|
||||
" c",
|
||||
"--- 1,3 ----",
|
||||
" a",
|
||||
"! B",
|
||||
" c",
|
||||
"***************",
|
||||
"*** 5,7 ****",
|
||||
" e",
|
||||
"! f",
|
||||
" g",
|
||||
"--- 5,7 ----",
|
||||
" e",
|
||||
"! F",
|
||||
" g",
|
||||
"",
|
||||
]
|
||||
.join("\n");
|
||||
let output = diff(from.as_bytes(), to.as_bytes(), ¶ms);
|
||||
assert_diff_eq!(output, expected);
|
||||
|
||||
// An insertion before a nearby change gives the two sides different
|
||||
// line counts; the hunks must still be merged (issue #268).
|
||||
let from = ["milk", "eggs", "bread", "butter", "apples", ""].join("\n");
|
||||
let to = ["milk", "eggs", "yogurt", "bread", "honey", "apples", ""].join("\n");
|
||||
let expected = [
|
||||
"*** foo\tTIMESTAMP",
|
||||
"--- bar\tTIMESTAMP",
|
||||
"***************",
|
||||
"*** 2,5 ****",
|
||||
" eggs",
|
||||
" bread",
|
||||
"! butter",
|
||||
" apples",
|
||||
"--- 2,6 ----",
|
||||
" eggs",
|
||||
"+ yogurt",
|
||||
" bread",
|
||||
"! honey",
|
||||
" apples",
|
||||
"",
|
||||
]
|
||||
.join("\n");
|
||||
let output = diff(from.as_bytes(), to.as_bytes(), ¶ms);
|
||||
assert_diff_eq!(output, expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// 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 crate::params::{parse_params, Format};
|
||||
use crate::utils::report_failure_to_read_input_file;
|
||||
use crate::{context_diff, ed_diff, normal_diff, side_diff, unified_diff};
|
||||
use std::env::ArgsOs;
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::io::{self, stdout, Read, Write};
|
||||
use std::iter::Peekable;
|
||||
use std::process::{exit, ExitCode};
|
||||
|
||||
// Exit codes are documented at
|
||||
// https://www.gnu.org/software/diffutils/manual/html_node/Invoking-diff.html.
|
||||
// An exit status of 0 means no differences were found,
|
||||
// 1 means some differences were found,
|
||||
// and 2 means trouble.
|
||||
pub fn main(opts: Peekable<ArgsOs>) -> ExitCode {
|
||||
let params = parse_params(opts).unwrap_or_else(|error| {
|
||||
eprintln!("{error}");
|
||||
exit(2);
|
||||
});
|
||||
if params.recursive {
|
||||
return recursive(¶ms).unwrap_or_else(|error| {
|
||||
eprintln!("diff: {error}");
|
||||
ExitCode::from(2)
|
||||
});
|
||||
}
|
||||
compare(¶ms)
|
||||
}
|
||||
|
||||
/// Compare directory entries in lexical order, with GNU diff's recursive output.
|
||||
fn recursive(params: &crate::params::Params) -> io::Result<ExitCode> {
|
||||
let from = std::path::Path::new(¶ms.from);
|
||||
let to = std::path::Path::new(¶ms.to);
|
||||
if !from.is_dir() || !to.is_dir() {
|
||||
if fs::read(from)? != fs::read(to)? {
|
||||
println!("diff -r {} {}", from.display(), to.display());
|
||||
}
|
||||
return Ok(compare(params));
|
||||
}
|
||||
let mut names = std::collections::BTreeSet::new();
|
||||
for dir in [from, to] {
|
||||
for entry in fs::read_dir(dir)? { names.insert(entry?.file_name()); }
|
||||
}
|
||||
let mut status = ExitCode::SUCCESS;
|
||||
for name in names {
|
||||
let left = from.join(&name);
|
||||
let right = to.join(&name);
|
||||
let result = if !left.exists() || !right.exists() {
|
||||
let parent = if left.exists() { from } else { to };
|
||||
println!("Only in {}: {}", parent.display(), name.to_string_lossy());
|
||||
ExitCode::from(1)
|
||||
} else if left.is_dir() != right.is_dir() {
|
||||
println!("File {} is a {} while file {} is a {}", left.display(),
|
||||
if left.is_dir() { "directory" } else { "regular file" }, right.display(),
|
||||
if right.is_dir() { "directory" } else { "regular file" });
|
||||
ExitCode::from(1)
|
||||
} else {
|
||||
let mut child = params.clone();
|
||||
child.from = left.into_os_string();
|
||||
child.to = right.into_os_string();
|
||||
recursive(&child)?
|
||||
};
|
||||
if result == ExitCode::from(2) { status = result; }
|
||||
else if result == ExitCode::from(1) && status == ExitCode::SUCCESS { status = result; }
|
||||
}
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
fn compare(params: &crate::params::Params) -> ExitCode {
|
||||
// if from and to are the same file, no need to perform any comparison
|
||||
let maybe_report_identical_files = || {
|
||||
if params.report_identical_files {
|
||||
println!(
|
||||
"Files {} and {} are identical",
|
||||
params.from.to_string_lossy(),
|
||||
params.to.to_string_lossy(),
|
||||
);
|
||||
}
|
||||
};
|
||||
if params.from == "-" && params.to == "-"
|
||||
|| same_file::is_same_file(¶ms.from, ¶ms.to).unwrap_or(false)
|
||||
{
|
||||
maybe_report_identical_files();
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
// read files
|
||||
fn read_file_contents(filepath: &OsString) -> io::Result<Vec<u8>> {
|
||||
if filepath == "-" {
|
||||
let mut content = Vec::new();
|
||||
io::stdin().read_to_end(&mut content).and(Ok(content))
|
||||
} else {
|
||||
fs::read(filepath)
|
||||
}
|
||||
}
|
||||
let mut io_error = false;
|
||||
let from_content = match read_file_contents(¶ms.from) {
|
||||
Ok(from_content) => from_content,
|
||||
Err(e) => {
|
||||
report_failure_to_read_input_file(¶ms.executable, ¶ms.from, &e);
|
||||
io_error = true;
|
||||
vec![]
|
||||
}
|
||||
};
|
||||
let to_content = match read_file_contents(¶ms.to) {
|
||||
Ok(to_content) => to_content,
|
||||
Err(e) => {
|
||||
report_failure_to_read_input_file(¶ms.executable, ¶ms.to, &e);
|
||||
io_error = true;
|
||||
vec![]
|
||||
}
|
||||
};
|
||||
if io_error {
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
|
||||
// run diff
|
||||
let result: Vec<u8> = match params.format {
|
||||
Format::Normal => normal_diff::diff(&from_content, &to_content, ¶ms),
|
||||
Format::Unified => unified_diff::diff(&from_content, &to_content, ¶ms),
|
||||
Format::Context => context_diff::diff(&from_content, &to_content, ¶ms),
|
||||
Format::Ed => ed_diff::diff(&from_content, &to_content, ¶ms).unwrap_or_else(|error| {
|
||||
eprintln!("{error}");
|
||||
exit(2);
|
||||
}),
|
||||
Format::SideBySide => {
|
||||
let mut output = stdout().lock();
|
||||
side_diff::diff(&from_content, &to_content, &mut output, ¶ms)
|
||||
}
|
||||
};
|
||||
if params.brief && !result.is_empty() {
|
||||
println!(
|
||||
"Files {} and {} differ",
|
||||
params.from.to_string_lossy(),
|
||||
params.to.to_string_lossy()
|
||||
);
|
||||
} else {
|
||||
io::stdout().write_all(&result).unwrap();
|
||||
}
|
||||
if result.is_empty() {
|
||||
maybe_report_identical_files();
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
// 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;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Mismatch {
|
||||
pub line_number_expected: usize,
|
||||
pub line_number_actual: usize,
|
||||
pub expected: Vec<Vec<u8>>,
|
||||
pub actual: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum DiffError {
|
||||
MissingNL,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DiffError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
|
||||
std::fmt::Display::fmt("No newline at end of file", f)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DiffError> for String {
|
||||
fn from(_: DiffError) -> String {
|
||||
"No newline at end of file".into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Mismatch {
|
||||
fn new(line_number_expected: usize, line_number_actual: usize) -> Mismatch {
|
||||
Mismatch {
|
||||
line_number_expected,
|
||||
line_number_actual,
|
||||
expected: Vec::new(),
|
||||
actual: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Produces a diff between the expected output and actual output.
|
||||
fn make_diff(expected: &[u8], actual: &[u8], stop_early: bool) -> Result<Vec<Mismatch>, DiffError> {
|
||||
let mut line_number_expected = 1;
|
||||
let mut line_number_actual = 1;
|
||||
let mut results = Vec::new();
|
||||
let mut mismatch = Mismatch::new(line_number_expected, line_number_actual);
|
||||
|
||||
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();
|
||||
|
||||
debug_assert_eq!(b"".split(|&c| c == b'\n').count(), 1);
|
||||
// ^ means that underflow here is impossible
|
||||
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();
|
||||
} else {
|
||||
return Err(DiffError::MissingNL);
|
||||
}
|
||||
|
||||
if actual_lines.last() == Some(&&b""[..]) {
|
||||
actual_lines.pop();
|
||||
} else {
|
||||
return Err(DiffError::MissingNL);
|
||||
}
|
||||
|
||||
for result in diff::slice(&expected_lines, &actual_lines) {
|
||||
match result {
|
||||
diff::Result::Left(str) => {
|
||||
if !mismatch.actual.is_empty() {
|
||||
results.push(mismatch);
|
||||
mismatch = Mismatch::new(line_number_expected, line_number_actual);
|
||||
}
|
||||
mismatch.expected.push(str.to_vec());
|
||||
line_number_expected += 1;
|
||||
}
|
||||
diff::Result::Right(str) => {
|
||||
mismatch.actual.push(str.to_vec());
|
||||
line_number_actual += 1;
|
||||
}
|
||||
diff::Result::Both(_str, _) => {
|
||||
line_number_expected += 1;
|
||||
line_number_actual += 1;
|
||||
if !mismatch.actual.is_empty() || !mismatch.expected.is_empty() {
|
||||
results.push(mismatch);
|
||||
mismatch = Mismatch::new(line_number_expected, line_number_actual);
|
||||
} else {
|
||||
mismatch.line_number_expected = line_number_expected;
|
||||
mismatch.line_number_actual = line_number_actual;
|
||||
}
|
||||
}
|
||||
}
|
||||
if stop_early && !results.is_empty() {
|
||||
// Optimization: stop analyzing the files as soon as there are any differences
|
||||
return Ok(results);
|
||||
}
|
||||
}
|
||||
|
||||
if !mismatch.actual.is_empty() || !mismatch.expected.is_empty() {
|
||||
results.push(mismatch);
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Result<Vec<u8>, DiffError> {
|
||||
let mut output = Vec::new();
|
||||
let diff_results = make_diff(expected, actual, params.brief)?;
|
||||
if params.brief && !diff_results.is_empty() {
|
||||
write!(&mut output, "\0").unwrap();
|
||||
return Ok(output);
|
||||
}
|
||||
let mut lines_offset = 0;
|
||||
for result in diff_results {
|
||||
let line_number_expected: isize = result.line_number_expected as isize + lines_offset;
|
||||
let _line_number_actual: isize = result.line_number_actual as isize + lines_offset;
|
||||
let expected_count: isize = result.expected.len() as isize;
|
||||
let actual_count: isize = result.actual.len() as isize;
|
||||
match (expected_count, actual_count) {
|
||||
(0, 0) => unreachable!(),
|
||||
(0, _) => writeln!(&mut output, "{}a", line_number_expected - 1).unwrap(),
|
||||
(_, 0) => writeln!(
|
||||
&mut output,
|
||||
"{},{}d",
|
||||
line_number_expected,
|
||||
expected_count + line_number_expected - 1
|
||||
)
|
||||
.unwrap(),
|
||||
(1, _) => writeln!(&mut output, "{line_number_expected}c").unwrap(),
|
||||
_ => writeln!(
|
||||
&mut output,
|
||||
"{},{}c",
|
||||
line_number_expected,
|
||||
expected_count + line_number_expected - 1
|
||||
)
|
||||
.unwrap(),
|
||||
}
|
||||
lines_offset += actual_count - expected_count;
|
||||
if actual_count != 0 {
|
||||
for actual in &result.actual {
|
||||
if actual == b"." {
|
||||
writeln!(&mut output, "..\n.\ns/.//\na").unwrap();
|
||||
} else {
|
||||
do_write_line(&mut output, actual, params.expand_tabs, params.tabsize).unwrap();
|
||||
writeln!(&mut output).unwrap();
|
||||
}
|
||||
}
|
||||
writeln!(&mut output, ".").unwrap();
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use crate::utils::testcmds::ED_CMD;
|
||||
|
||||
pub fn diff_w(expected: &[u8], actual: &[u8], filename: &str) -> Result<Vec<u8>, DiffError> {
|
||||
let mut output = diff(expected, actual, &Params::default())?;
|
||||
writeln!(&mut output, "w {filename}").unwrap();
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_basic() {
|
||||
let from = b"a\n";
|
||||
let to = b"b\n";
|
||||
let diff = diff(from, to, &Params::default()).unwrap();
|
||||
let expected = ["1c", "b", ".", ""].join("\n");
|
||||
assert_eq!(diff, expected.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations() {
|
||||
let target = "target/ed-diff/";
|
||||
// test all possible six-line files.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"a\n" } else { b"b\n" })
|
||||
.unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"c\n" } else { b"d\n" })
|
||||
.unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"e\n" } else { b"f\n" })
|
||||
.unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"g\n" } else { b"h\n" })
|
||||
.unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"h\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"i\n" } else { b"j\n" })
|
||||
.unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"j\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"k\n" } else { b"l\n" })
|
||||
.unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"l\n").unwrap();
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let diff = diff_w(&alef, &bet, &format!("{target}/alef")).unwrap();
|
||||
File::create(format!("{target}/ab.ed"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alef")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/bet")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
#[cfg(not(windows))] // there's no ed on windows
|
||||
{
|
||||
let output = ED_CMD
|
||||
.new()
|
||||
.arg(format!("{target}/alef"))
|
||||
.stdin(File::open(format!("{target}/ab.ed")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = std::fs::read(format!("{target}/alef")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations_empty_lines() {
|
||||
let target = "target/ed-diff/";
|
||||
// test all possible six-line files with missing newlines.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"\n" } else { b"b\n" }).unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"\n" } else { b"d\n" }).unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"\n" } else { b"f\n" }).unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"\n" } else { b"h\n" }).unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"h\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"\n" } else { b"j\n" }).unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"j\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"\n" } else { b"l\n" }).unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"l\n").unwrap();
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let diff = diff_w(&alef, &bet, &format!("{target}/alef_")).unwrap();
|
||||
File::create(format!("{target}/ab_.ed"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alef_")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/bet_")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
#[cfg(not(windows))] // there's no ed on windows
|
||||
{
|
||||
let output = ED_CMD
|
||||
.new()
|
||||
.arg(format!("{target}/alef_"))
|
||||
.stdin(File::open(format!("{target}/ab_.ed")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = std::fs::read(format!("{target}/alef_")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations_reverse() {
|
||||
let target = "target/ed-diff/";
|
||||
// test all possible six-line files.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"a\n" } else { b"f\n" })
|
||||
.unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"a\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"b\n" } else { b"e\n" })
|
||||
.unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"c\n" } else { b"d\n" })
|
||||
.unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"c\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"d\n" } else { b"c\n" })
|
||||
.unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"e\n" } else { b"b\n" })
|
||||
.unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"e\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"f\n" } else { b"a\n" })
|
||||
.unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let diff = diff_w(&alef, &bet, &format!("{target}/alefr")).unwrap();
|
||||
File::create(format!("{target}/abr.ed"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alefr")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/betr")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
#[cfg(not(windows))] // there's no ed on windows
|
||||
{
|
||||
let output = ED_CMD
|
||||
.new()
|
||||
.arg(format!("{target}/alefr"))
|
||||
.stdin(File::open(format!("{target}/abr.ed")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = std::fs::read(format!("{target}/alefr")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stop_early() {
|
||||
let from = ["a", "b", "c", ""].join("\n");
|
||||
let to = ["a", "d", "c", ""].join("\n");
|
||||
|
||||
let diff_full = diff(from.as_bytes(), to.as_bytes(), &Params::default()).unwrap();
|
||||
let expected_full = ["2c", "d", ".", ""].join("\n");
|
||||
assert_eq!(diff_full, expected_full.as_bytes());
|
||||
|
||||
let diff_brief = diff(
|
||||
from.as_bytes(),
|
||||
to.as_bytes(),
|
||||
&Params {
|
||||
brief: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let expected_brief = "\0".as_bytes();
|
||||
assert_eq!(diff_brief, expected_brief);
|
||||
|
||||
let nodiff_full = diff(from.as_bytes(), from.as_bytes(), &Params::default()).unwrap();
|
||||
assert!(nodiff_full.is_empty());
|
||||
|
||||
let nodiff_brief = diff(
|
||||
from.as_bytes(),
|
||||
from.as_bytes(),
|
||||
&Params {
|
||||
brief: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(nodiff_brief.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
pub mod cmp;
|
||||
pub mod context_diff;
|
||||
pub mod ed_diff;
|
||||
pub mod macros;
|
||||
pub mod normal_diff;
|
||||
pub mod params;
|
||||
pub mod side_diff;
|
||||
pub mod unified_diff;
|
||||
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 normal_diff::diff as normal_diff;
|
||||
pub use side_diff::diff as side_by_side_diff;
|
||||
pub use unified_diff::diff as unified_diff;
|
||||
@@ -0,0 +1,25 @@
|
||||
// asserts equality of the actual diff and expected diff
|
||||
// considering datetime varitations
|
||||
//
|
||||
// It replaces the modification time in the actual diff
|
||||
// with placeholder "TIMESTAMP" and then asserts the equality
|
||||
//
|
||||
// For eg.
|
||||
// let brief = "*** fruits_old.txt\t2024-03-24 23:43:05.189597645 +0530\n
|
||||
// --- fruits_new.txt\t2024-03-24 23:35:08.922581904 +0530\n";
|
||||
//
|
||||
// replaced = "*** fruits_old.txt\tTIMESTAMP\n
|
||||
// --- fruits_new.txt\tTIMESTAMP\n";
|
||||
#[macro_export]
|
||||
macro_rules! assert_diff_eq {
|
||||
($actual:expr, $expected:expr) => {{
|
||||
use regex::Regex;
|
||||
use std::str;
|
||||
|
||||
let diff = str::from_utf8(&$actual).unwrap();
|
||||
let re = Regex::new(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+ [+-]\d{4}").unwrap();
|
||||
let actual = re.replacen(diff, 2, "TIMESTAMP");
|
||||
|
||||
assert_eq!(actual, $expected);
|
||||
}};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// 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::{
|
||||
env::ArgsOs,
|
||||
ffi::{OsStr, OsString},
|
||||
iter::Peekable,
|
||||
path::{Path, PathBuf},
|
||||
process::ExitCode,
|
||||
};
|
||||
|
||||
mod cmp;
|
||||
mod context_diff;
|
||||
mod diff;
|
||||
mod ed_diff;
|
||||
mod macros;
|
||||
mod normal_diff;
|
||||
mod params;
|
||||
mod side_diff;
|
||||
mod unified_diff;
|
||||
mod utils;
|
||||
|
||||
/// # Panics
|
||||
/// Panics if the binary path cannot be determined
|
||||
fn binary_path(args: &mut Peekable<ArgsOs>) -> PathBuf {
|
||||
match args.peek() {
|
||||
Some(ref s) if !s.is_empty() => PathBuf::from(s),
|
||||
_ => std::env::current_exe().unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
/// #Panics
|
||||
/// Panics if path has no UTF-8 valid name
|
||||
fn name(binary_path: &Path) -> &OsStr {
|
||||
binary_path.file_stem().unwrap()
|
||||
}
|
||||
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
fn usage(name: &str) {
|
||||
println!("{name} {VERSION} (multi-call binary)\n");
|
||||
println!("Usage: {name} [function [arguments...]]\n");
|
||||
println!("Currently defined functions:\n");
|
||||
println!(" cmp, diff\n");
|
||||
}
|
||||
|
||||
fn second_arg_error(name: &OsStr) -> ! {
|
||||
eprintln!("Expected utility name as second argument, got nothing.");
|
||||
usage(&name.to_string_lossy());
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args = std::env::args_os().peekable();
|
||||
|
||||
let exe_path = binary_path(&mut args);
|
||||
let exe_name = name(&exe_path);
|
||||
|
||||
let util_name = if exe_name.as_encoded_bytes().ends_with(b"diffutils") {
|
||||
// Discard the item we peeked.
|
||||
let _ = args.next();
|
||||
|
||||
args.peek()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| second_arg_error(exe_name))
|
||||
} else {
|
||||
OsString::from(exe_name)
|
||||
};
|
||||
|
||||
match util_name.as_encoded_bytes() {
|
||||
name if name.ends_with(b"diff") => diff::main(args),
|
||||
name if name.ends_with(b"cmp") => cmp::main(args),
|
||||
name => {
|
||||
use std::io::{stderr, Write as _};
|
||||
let _ = writeln!(
|
||||
stderr(),
|
||||
"{}: utility not supported",
|
||||
String::from_utf8_lossy(name)
|
||||
);
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,586 @@
|
||||
// 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;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Mismatch {
|
||||
pub line_number_expected: usize,
|
||||
pub line_number_actual: usize,
|
||||
pub expected: Vec<Vec<u8>>,
|
||||
pub actual: Vec<Vec<u8>>,
|
||||
pub expected_missing_nl: bool,
|
||||
pub actual_missing_nl: bool,
|
||||
}
|
||||
|
||||
impl Mismatch {
|
||||
fn new(line_number_expected: usize, line_number_actual: usize) -> Mismatch {
|
||||
Mismatch {
|
||||
line_number_expected,
|
||||
line_number_actual,
|
||||
expected: Vec::new(),
|
||||
actual: Vec::new(),
|
||||
expected_missing_nl: false,
|
||||
actual_missing_nl: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Produces a diff between the expected output and actual output.
|
||||
fn make_diff(expected: &[u8], actual: &[u8], stop_early: bool) -> Vec<Mismatch> {
|
||||
let mut line_number_expected = 1;
|
||||
let mut line_number_actual = 1;
|
||||
let mut results = Vec::new();
|
||||
let mut mismatch = Mismatch::new(line_number_expected, line_number_actual);
|
||||
|
||||
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();
|
||||
|
||||
debug_assert_eq!(b"".split(|&c| c == b'\n').count(), 1);
|
||||
// ^ means that underflow here is impossible
|
||||
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();
|
||||
}
|
||||
|
||||
for result in diff::slice(&expected_lines, &actual_lines) {
|
||||
match result {
|
||||
diff::Result::Left(str) => {
|
||||
if !mismatch.actual.is_empty() && !mismatch.actual_missing_nl {
|
||||
results.push(mismatch);
|
||||
mismatch = Mismatch::new(line_number_expected, line_number_actual);
|
||||
}
|
||||
mismatch.expected.push(str.to_vec());
|
||||
mismatch.expected_missing_nl = line_number_expected > expected_lines_count;
|
||||
line_number_expected += 1;
|
||||
}
|
||||
diff::Result::Right(str) => {
|
||||
mismatch.actual.push(str.to_vec());
|
||||
mismatch.actual_missing_nl = line_number_actual > actual_lines_count;
|
||||
line_number_actual += 1;
|
||||
}
|
||||
diff::Result::Both(str, _) => {
|
||||
match (
|
||||
line_number_expected > expected_lines_count,
|
||||
line_number_actual > actual_lines_count,
|
||||
) {
|
||||
(true, false) => {
|
||||
line_number_expected += 1;
|
||||
line_number_actual += 1;
|
||||
mismatch.expected.push(str.to_vec());
|
||||
mismatch.expected_missing_nl = true;
|
||||
mismatch.actual.push(str.to_vec());
|
||||
}
|
||||
(false, true) => {
|
||||
line_number_expected += 1;
|
||||
line_number_actual += 1;
|
||||
mismatch.actual.push(str.to_vec());
|
||||
mismatch.actual_missing_nl = true;
|
||||
mismatch.expected.push(str.to_vec());
|
||||
}
|
||||
(true, true) | (false, false) => {
|
||||
line_number_expected += 1;
|
||||
line_number_actual += 1;
|
||||
if !mismatch.actual.is_empty() || !mismatch.expected.is_empty() {
|
||||
results.push(mismatch);
|
||||
mismatch = Mismatch::new(line_number_expected, line_number_actual);
|
||||
} else {
|
||||
mismatch.line_number_expected = line_number_expected;
|
||||
mismatch.line_number_actual = line_number_actual;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if stop_early && !results.is_empty() {
|
||||
// Optimization: stop analyzing the files as soon as there are any differences
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
if !mismatch.actual.is_empty() || !mismatch.expected.is_empty() {
|
||||
results.push(mismatch);
|
||||
}
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<u8> {
|
||||
// See https://www.gnu.org/software/diffutils/manual/html_node/Detailed-Normal.html
|
||||
// for details on the syntax of the normal format.
|
||||
let mut output = Vec::new();
|
||||
let diff_results = make_diff(expected, actual, params.brief);
|
||||
if params.brief && !diff_results.is_empty() {
|
||||
write!(&mut output, "\0").unwrap();
|
||||
return output;
|
||||
}
|
||||
for result in diff_results {
|
||||
let line_number_expected = result.line_number_expected;
|
||||
let line_number_actual = result.line_number_actual;
|
||||
let expected_count = result.expected.len();
|
||||
let actual_count = result.actual.len();
|
||||
match (expected_count, actual_count) {
|
||||
(0, 0) => unreachable!(),
|
||||
(0, _) => writeln!(
|
||||
// 'a' stands for "Add lines"
|
||||
&mut output,
|
||||
"{}a{},{}",
|
||||
line_number_expected - 1,
|
||||
line_number_actual,
|
||||
line_number_actual + actual_count - 1
|
||||
)
|
||||
.unwrap(),
|
||||
(_, 0) => writeln!(
|
||||
// 'd' stands for "Delete lines"
|
||||
&mut output,
|
||||
"{},{}d{}",
|
||||
line_number_expected,
|
||||
expected_count + line_number_expected - 1,
|
||||
line_number_actual - 1
|
||||
)
|
||||
.unwrap(),
|
||||
(1, 1) => writeln!(
|
||||
// 'c' stands for "Change lines"
|
||||
// exactly one line replaced by one line
|
||||
&mut output,
|
||||
"{line_number_expected}c{line_number_actual}"
|
||||
)
|
||||
.unwrap(),
|
||||
(1, _) => writeln!(
|
||||
// one line replaced by multiple lines
|
||||
&mut output,
|
||||
"{}c{},{}",
|
||||
line_number_expected,
|
||||
line_number_actual,
|
||||
actual_count + line_number_actual - 1
|
||||
)
|
||||
.unwrap(),
|
||||
(_, 1) => writeln!(
|
||||
// multiple lines replaced by one line
|
||||
&mut output,
|
||||
"{},{}c{}",
|
||||
line_number_expected,
|
||||
expected_count + line_number_expected - 1,
|
||||
line_number_actual
|
||||
)
|
||||
.unwrap(),
|
||||
_ => writeln!(
|
||||
// general case: multiple lines replaced by multiple lines
|
||||
&mut output,
|
||||
"{},{}c{},{}",
|
||||
line_number_expected,
|
||||
expected_count + line_number_expected - 1,
|
||||
line_number_actual,
|
||||
actual_count + line_number_actual - 1
|
||||
)
|
||||
.unwrap(),
|
||||
}
|
||||
for expected in &result.expected {
|
||||
write!(&mut output, "< ").unwrap();
|
||||
do_write_line(&mut output, expected, params.expand_tabs, params.tabsize).unwrap();
|
||||
writeln!(&mut output).unwrap();
|
||||
}
|
||||
if result.expected_missing_nl {
|
||||
writeln!(&mut output, r"\ No newline at end of file").unwrap();
|
||||
}
|
||||
if expected_count != 0 && actual_count != 0 {
|
||||
writeln!(&mut output, "---").unwrap();
|
||||
}
|
||||
for actual in &result.actual {
|
||||
write!(&mut output, "> ").unwrap();
|
||||
do_write_line(&mut output, actual, params.expand_tabs, params.tabsize).unwrap();
|
||||
writeln!(&mut output).unwrap();
|
||||
}
|
||||
if result.actual_missing_nl {
|
||||
writeln!(&mut output, r"\ No newline at end of file").unwrap();
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use crate::utils::testcmds::PATCH_CMD;
|
||||
|
||||
#[test]
|
||||
fn test_basic() {
|
||||
let mut a = Vec::new();
|
||||
a.write_all(b"a\n").unwrap();
|
||||
let mut b = Vec::new();
|
||||
b.write_all(b"b\n").unwrap();
|
||||
let diff = diff(&a, &b, &Params::default());
|
||||
let expected = b"1c1\n< a\n---\n> b\n".to_vec();
|
||||
assert_eq!(diff, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations() {
|
||||
let target = "target/normal-diff/";
|
||||
// test all possible six-line files.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"a\n" } else { b"b\n" })
|
||||
.unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"c\n" } else { b"d\n" })
|
||||
.unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"e\n" } else { b"f\n" })
|
||||
.unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"g\n" } else { b"h\n" })
|
||||
.unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"h\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"i\n" } else { b"j\n" })
|
||||
.unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"j\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"k\n" } else { b"l\n" })
|
||||
.unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"l\n").unwrap();
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let diff = diff(&alef, &bet, &Params::default());
|
||||
File::create(format!("{target}/ab.diff"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alef")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/bet")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
let output = PATCH_CMD
|
||||
.new()
|
||||
.arg("-p0")
|
||||
.arg(format!("{target}/alef"))
|
||||
.stdin(File::open(format!("{target}/ab.diff")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = fs::read(format!("{target}/alef")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations_missing_line_ending() {
|
||||
let target = "target/normal-diff/";
|
||||
// test all possible six-line files with missing newlines.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
for &g in &[0, 1, 2] {
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"a\n" } else { b"b\n" })
|
||||
.unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"c\n" } else { b"d\n" })
|
||||
.unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"e\n" } else { b"f\n" })
|
||||
.unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"g\n" } else { b"h\n" })
|
||||
.unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"h\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"i\n" } else { b"j\n" })
|
||||
.unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"j\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"k\n" } else { b"l\n" })
|
||||
.unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"l\n").unwrap();
|
||||
}
|
||||
match g {
|
||||
0 => {
|
||||
alef.pop();
|
||||
}
|
||||
1 => {
|
||||
bet.pop();
|
||||
}
|
||||
2 => {
|
||||
alef.pop();
|
||||
bet.pop();
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let diff = diff(&alef, &bet, &Params::default());
|
||||
File::create(format!("{target}/abn.diff"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alefn")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/betn")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
let output = PATCH_CMD
|
||||
.new()
|
||||
.arg("-p0")
|
||||
.arg("--normal")
|
||||
.arg(format!("{target}/alefn"))
|
||||
.stdin(File::open(format!("{target}/abn.diff")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = fs::read(format!("{target}/alefn")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations_empty_lines() {
|
||||
let target = "target/normal-diff/";
|
||||
// test all possible six-line files with missing newlines.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"\n" } else { b"b\n" }).unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"\n" } else { b"d\n" }).unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"\n" } else { b"f\n" }).unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"\n" } else { b"h\n" }).unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"h\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"\n" } else { b"j\n" }).unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"j\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"\n" } else { b"l\n" }).unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"l\n").unwrap();
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let diff = diff(&alef, &bet, &Params::default());
|
||||
File::create(format!("{target}/ab_.diff"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alef_")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/bet_")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
let output = PATCH_CMD
|
||||
.new()
|
||||
.arg("-p0")
|
||||
.arg(format!("{target}/alef_"))
|
||||
.stdin(File::open(format!("{target}/ab_.diff")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = fs::read(format!("{target}/alef_")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_permutations_reverse() {
|
||||
let target = "target/normal-diff/";
|
||||
// test all possible six-line files.
|
||||
let _ = std::fs::create_dir(target);
|
||||
for &a in &[0, 1, 2] {
|
||||
for &b in &[0, 1, 2] {
|
||||
for &c in &[0, 1, 2] {
|
||||
for &d in &[0, 1, 2] {
|
||||
for &e in &[0, 1, 2] {
|
||||
for &f in &[0, 1, 2] {
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
let mut alef = Vec::new();
|
||||
let mut bet = Vec::new();
|
||||
alef.write_all(if a == 0 { b"a\n" } else { b"f\n" })
|
||||
.unwrap();
|
||||
if a != 2 {
|
||||
bet.write_all(b"a\n").unwrap();
|
||||
}
|
||||
alef.write_all(if b == 0 { b"b\n" } else { b"e\n" })
|
||||
.unwrap();
|
||||
if b != 2 {
|
||||
bet.write_all(b"b\n").unwrap();
|
||||
}
|
||||
alef.write_all(if c == 0 { b"c\n" } else { b"d\n" })
|
||||
.unwrap();
|
||||
if c != 2 {
|
||||
bet.write_all(b"c\n").unwrap();
|
||||
}
|
||||
alef.write_all(if d == 0 { b"d\n" } else { b"c\n" })
|
||||
.unwrap();
|
||||
if d != 2 {
|
||||
bet.write_all(b"d\n").unwrap();
|
||||
}
|
||||
alef.write_all(if e == 0 { b"e\n" } else { b"b\n" })
|
||||
.unwrap();
|
||||
if e != 2 {
|
||||
bet.write_all(b"e\n").unwrap();
|
||||
}
|
||||
alef.write_all(if f == 0 { b"f\n" } else { b"a\n" })
|
||||
.unwrap();
|
||||
if f != 2 {
|
||||
bet.write_all(b"f\n").unwrap();
|
||||
}
|
||||
// This test diff is intentionally reversed.
|
||||
// We want it to turn the alef into bet.
|
||||
let diff = diff(&alef, &bet, &Params::default());
|
||||
File::create(format!("{target}/abr.diff"))
|
||||
.unwrap()
|
||||
.write_all(&diff)
|
||||
.unwrap();
|
||||
let mut fa = File::create(format!("{target}/alefr")).unwrap();
|
||||
fa.write_all(&alef[..]).unwrap();
|
||||
let mut fb = File::create(format!("{target}/betr")).unwrap();
|
||||
fb.write_all(&bet[..]).unwrap();
|
||||
let _ = fa;
|
||||
let _ = fb;
|
||||
let output = PATCH_CMD
|
||||
.new()
|
||||
.arg("-p0")
|
||||
.arg(format!("{target}/alefr"))
|
||||
.stdin(File::open(format!("{target}/abr.diff")).unwrap())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
//println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||
//println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
let alef = fs::read(format!("{target}/alefr")).unwrap();
|
||||
assert_eq!(alef, bet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stop_early() {
|
||||
let from = ["a", "b", "c"].join("\n");
|
||||
let to = ["a", "d", "c"].join("\n");
|
||||
|
||||
let diff_full = diff(from.as_bytes(), to.as_bytes(), &Params::default());
|
||||
let expected_full = ["2c2", "< b", "---", "> d", ""].join("\n");
|
||||
assert_eq!(diff_full, expected_full.as_bytes());
|
||||
|
||||
let diff_brief = diff(
|
||||
from.as_bytes(),
|
||||
to.as_bytes(),
|
||||
&Params {
|
||||
brief: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let expected_brief = "\0".as_bytes();
|
||||
assert_eq!(diff_brief, expected_brief);
|
||||
|
||||
let nodiff_full = diff(from.as_bytes(), from.as_bytes(), &Params::default());
|
||||
assert!(nodiff_full.is_empty());
|
||||
|
||||
let nodiff_brief = diff(
|
||||
from.as_bytes(),
|
||||
from.as_bytes(),
|
||||
&Params {
|
||||
brief: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert!(nodiff_brief.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,975 @@
|
||||
use std::ffi::OsString;
|
||||
use std::iter::Peekable;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub enum Format {
|
||||
#[default]
|
||||
Normal,
|
||||
Unified,
|
||||
Context,
|
||||
Ed,
|
||||
SideBySide,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct Params {
|
||||
pub executable: OsString,
|
||||
pub from: OsString,
|
||||
pub to: OsString,
|
||||
pub format: Format,
|
||||
pub context_count: usize,
|
||||
pub report_identical_files: bool,
|
||||
pub brief: bool,
|
||||
pub recursive: bool,
|
||||
pub expand_tabs: bool,
|
||||
pub tabsize: usize,
|
||||
pub width: usize,
|
||||
}
|
||||
|
||||
impl Default for Params {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
executable: OsString::default(),
|
||||
from: OsString::default(),
|
||||
to: OsString::default(),
|
||||
format: Format::default(),
|
||||
context_count: 3,
|
||||
report_identical_files: false,
|
||||
brief: false,
|
||||
recursive: false,
|
||||
expand_tabs: false,
|
||||
tabsize: 8,
|
||||
width: 130,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Result<Params, String> {
|
||||
// parse CLI
|
||||
|
||||
let Some(executable) = opts.next() else {
|
||||
return Err("Usage: <exe> <from> <to>".to_string());
|
||||
};
|
||||
let mut params = Params {
|
||||
executable,
|
||||
..Default::default()
|
||||
};
|
||||
let mut from = None;
|
||||
let mut to = None;
|
||||
let mut format = None;
|
||||
let mut context = None;
|
||||
let tabsize_re = Regex::new(r"^--tabsize=(?<num>\d+)$").unwrap();
|
||||
let width_re = Regex::new(r"^--width=(?P<long>\d+)$").unwrap();
|
||||
while let Some(param) = opts.next() {
|
||||
let next_param = opts.peek();
|
||||
if param == "--" {
|
||||
break;
|
||||
}
|
||||
if param == "-" {
|
||||
if from.is_none() {
|
||||
from = Some(param);
|
||||
} else if to.is_none() {
|
||||
to = Some(param);
|
||||
} else {
|
||||
return Err(format!(
|
||||
"Usage: {} <from> <to>",
|
||||
params.executable.to_string_lossy()
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if param == "-r" || param == "--recursive" {
|
||||
params.recursive = true;
|
||||
continue;
|
||||
}
|
||||
if param == "-s" || param == "--report-identical-files" {
|
||||
params.report_identical_files = true;
|
||||
continue;
|
||||
}
|
||||
if param == "-q" || param == "--brief" {
|
||||
params.brief = true;
|
||||
continue;
|
||||
}
|
||||
if param == "-t" || param == "--expand-tabs" {
|
||||
params.expand_tabs = true;
|
||||
continue;
|
||||
}
|
||||
if param == "--normal" {
|
||||
if format.is_some() && format != Some(Format::Normal) {
|
||||
return Err("Conflicting output style options".to_string());
|
||||
}
|
||||
format = Some(Format::Normal);
|
||||
continue;
|
||||
}
|
||||
if param == "-e" || param == "--ed" {
|
||||
if format.is_some() && format != Some(Format::Ed) {
|
||||
return Err("Conflicting output style options".to_string());
|
||||
}
|
||||
format = Some(Format::Ed);
|
||||
continue;
|
||||
}
|
||||
if param == "-y" || param == "--side-by-side" {
|
||||
if format.is_some() && format != Some(Format::SideBySide) {
|
||||
return Err("Conflicting output style option".to_string());
|
||||
}
|
||||
format = Some(Format::SideBySide);
|
||||
continue;
|
||||
}
|
||||
if width_re.is_match(param.to_string_lossy().as_ref()) {
|
||||
let param = param.into_string().unwrap();
|
||||
let width_str: &str = width_re
|
||||
.captures(param.as_str())
|
||||
.unwrap()
|
||||
.name("long")
|
||||
.unwrap()
|
||||
.as_str();
|
||||
|
||||
params.width = match width_str.parse::<usize>() {
|
||||
Ok(num) => {
|
||||
if num == 0 {
|
||||
return Err("invalid width «0»".to_string());
|
||||
}
|
||||
|
||||
num
|
||||
}
|
||||
Err(_) => return Err(format!("invalid width «{width_str}»")),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
if tabsize_re.is_match(param.to_string_lossy().as_ref()) {
|
||||
// Because param matches the regular expression,
|
||||
// it is safe to assume it is valid UTF-8.
|
||||
let param = param.into_string().unwrap();
|
||||
let tabsize_str = tabsize_re
|
||||
.captures(param.as_str())
|
||||
.unwrap()
|
||||
.name("num")
|
||||
.unwrap()
|
||||
.as_str();
|
||||
params.tabsize = match tabsize_str.parse::<usize>() {
|
||||
Ok(num) => {
|
||||
if num == 0 {
|
||||
return Err("invalid tabsize «0»".to_string());
|
||||
}
|
||||
|
||||
num
|
||||
}
|
||||
Err(_) => return Err(format!("invalid tabsize «{tabsize_str}»")),
|
||||
};
|
||||
|
||||
continue;
|
||||
}
|
||||
match match_context_diff_params(¶m, next_param, format) {
|
||||
Ok(DiffStyleMatch {
|
||||
is_match,
|
||||
context_count,
|
||||
next_param_consumed,
|
||||
}) => {
|
||||
if is_match {
|
||||
format = Some(Format::Context);
|
||||
if context_count.is_some() {
|
||||
context = context_count;
|
||||
}
|
||||
if next_param_consumed {
|
||||
opts.next();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
match match_unified_diff_params(¶m, next_param, format) {
|
||||
Ok(DiffStyleMatch {
|
||||
is_match,
|
||||
context_count,
|
||||
next_param_consumed,
|
||||
}) => {
|
||||
if is_match {
|
||||
format = Some(Format::Unified);
|
||||
if context_count.is_some() {
|
||||
context = context_count;
|
||||
}
|
||||
if next_param_consumed {
|
||||
opts.next();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
if param.to_string_lossy().starts_with('-') {
|
||||
return Err(format!("unrecognized option '{}'", param.to_string_lossy()));
|
||||
}
|
||||
if from.is_none() {
|
||||
from = Some(param);
|
||||
} else if to.is_none() {
|
||||
to = Some(param);
|
||||
} else {
|
||||
return Err(format!(
|
||||
"Usage: {} <from> <to>",
|
||||
params.executable.to_string_lossy()
|
||||
));
|
||||
}
|
||||
}
|
||||
params.from = if let Some(from) = from {
|
||||
from
|
||||
} else if let Some(param) = opts.next() {
|
||||
param
|
||||
} else {
|
||||
return Err(format!(
|
||||
"Usage: {} <from> <to>",
|
||||
params.executable.to_string_lossy()
|
||||
));
|
||||
};
|
||||
params.to = if let Some(to) = to {
|
||||
to
|
||||
} else if let Some(param) = opts.next() {
|
||||
param
|
||||
} else {
|
||||
return Err(format!(
|
||||
"Usage: {} <from> <to>",
|
||||
params.executable.to_string_lossy()
|
||||
));
|
||||
};
|
||||
|
||||
// diff DIRECTORY FILE => diff DIRECTORY/FILE FILE
|
||||
// diff FILE DIRECTORY => diff FILE DIRECTORY/FILE
|
||||
let mut from_path: PathBuf = PathBuf::from(¶ms.from);
|
||||
let mut to_path: PathBuf = PathBuf::from(¶ms.to);
|
||||
|
||||
if from_path.is_dir() && to_path.is_file() {
|
||||
from_path.push(to_path.file_name().unwrap());
|
||||
params.from = from_path.into_os_string();
|
||||
} else if from_path.is_file() && to_path.is_dir() {
|
||||
to_path.push(from_path.file_name().unwrap());
|
||||
params.to = to_path.into_os_string();
|
||||
}
|
||||
|
||||
params.format = format.unwrap_or(Format::default());
|
||||
if let Some(context_count) = context {
|
||||
params.context_count = context_count;
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
|
||||
struct DiffStyleMatch {
|
||||
is_match: bool,
|
||||
context_count: Option<usize>,
|
||||
next_param_consumed: bool,
|
||||
}
|
||||
|
||||
fn match_context_diff_params(
|
||||
param: &OsString,
|
||||
next_param: Option<&OsString>,
|
||||
format: Option<Format>,
|
||||
) -> Result<DiffStyleMatch, String> {
|
||||
const CONTEXT_RE: &str = r"^(-[cC](?<num1>\d*)|--context(=(?<num2>\d*))?|-(?<num3>\d+)c)$";
|
||||
let regex = Regex::new(CONTEXT_RE).unwrap();
|
||||
let is_match = regex.is_match(param.to_string_lossy().as_ref());
|
||||
let mut context_count = None;
|
||||
let mut next_param_consumed = false;
|
||||
if is_match {
|
||||
if format.is_some() && format != Some(Format::Context) {
|
||||
return Err("Conflicting output style options".to_string());
|
||||
}
|
||||
let captures = regex.captures(param.to_str().unwrap()).unwrap();
|
||||
let num = captures
|
||||
.name("num1")
|
||||
.or(captures.name("num2"))
|
||||
.or(captures.name("num3"));
|
||||
if let Some(numvalue) = num {
|
||||
if !numvalue.as_str().is_empty() {
|
||||
context_count = Some(numvalue.as_str().parse::<usize>().unwrap());
|
||||
}
|
||||
}
|
||||
if param == "-C" {
|
||||
if let Some(p) = next_param {
|
||||
let size_str = p.to_string_lossy();
|
||||
match size_str.parse::<usize>() {
|
||||
Ok(context_size) => {
|
||||
context_count = Some(context_size);
|
||||
next_param_consumed = true;
|
||||
}
|
||||
Err(_) => return Err(format!("invalid context length '{size_str}'")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(DiffStyleMatch {
|
||||
is_match,
|
||||
context_count,
|
||||
next_param_consumed,
|
||||
})
|
||||
}
|
||||
|
||||
fn match_unified_diff_params(
|
||||
param: &OsString,
|
||||
next_param: Option<&OsString>,
|
||||
format: Option<Format>,
|
||||
) -> Result<DiffStyleMatch, String> {
|
||||
const UNIFIED_RE: &str = r"^(-[uU](?<num1>\d*)|--unified(=(?<num2>\d*))?|-(?<num3>\d+)u)$";
|
||||
let regex = Regex::new(UNIFIED_RE).unwrap();
|
||||
let is_match = regex.is_match(param.to_string_lossy().as_ref());
|
||||
let mut context_count = None;
|
||||
let mut next_param_consumed = false;
|
||||
if is_match {
|
||||
if format.is_some() && format != Some(Format::Unified) {
|
||||
return Err("Conflicting output style options".to_string());
|
||||
}
|
||||
let captures = regex.captures(param.to_str().unwrap()).unwrap();
|
||||
let num = captures
|
||||
.name("num1")
|
||||
.or(captures.name("num2"))
|
||||
.or(captures.name("num3"));
|
||||
if let Some(numvalue) = num {
|
||||
if !numvalue.as_str().is_empty() {
|
||||
context_count = Some(numvalue.as_str().parse::<usize>().unwrap());
|
||||
}
|
||||
}
|
||||
if param == "-U" {
|
||||
if let Some(p) = next_param {
|
||||
let size_str = p.to_string_lossy();
|
||||
match size_str.parse::<usize>() {
|
||||
Ok(context_size) => {
|
||||
context_count = Some(context_size);
|
||||
next_param_consumed = true;
|
||||
}
|
||||
Err(_) => return Err(format!("invalid context length '{size_str}'")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(DiffStyleMatch {
|
||||
is_match,
|
||||
context_count,
|
||||
next_param_consumed,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn os(s: &str) -> OsString {
|
||||
OsString::from(s)
|
||||
}
|
||||
#[test]
|
||||
fn basics() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("--normal"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn basics_ed() {
|
||||
for arg in ["-e", "--ed"] {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
format: Format::Ed,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os(arg), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn context_valid() {
|
||||
for args in [vec!["-c"], vec!["--context"], vec!["--context="]] {
|
||||
let mut params = vec!["diff"];
|
||||
params.extend(args);
|
||||
params.extend(["foo", "bar"]);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
format: Format::Context,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(params.iter().map(|x| os(x)).peekable())
|
||||
);
|
||||
}
|
||||
for args in [
|
||||
vec!["-c42"],
|
||||
vec!["-C42"],
|
||||
vec!["-C", "42"],
|
||||
vec!["--context=42"],
|
||||
vec!["-42c"],
|
||||
] {
|
||||
let mut params = vec!["diff"];
|
||||
params.extend(args);
|
||||
params.extend(["foo", "bar"]);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
format: Format::Context,
|
||||
context_count: 42,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(params.iter().map(|x| os(x)).peekable())
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn context_invalid() {
|
||||
for args in [
|
||||
vec!["-c", "42"],
|
||||
vec!["-c=42"],
|
||||
vec!["-c="],
|
||||
vec!["-C"],
|
||||
vec!["-C=42"],
|
||||
vec!["-C="],
|
||||
vec!["--context42"],
|
||||
vec!["--context", "42"],
|
||||
vec!["-42C"],
|
||||
] {
|
||||
let mut params = vec!["diff"];
|
||||
params.extend(args);
|
||||
params.extend(["foo", "bar"]);
|
||||
assert!(parse_params(params.iter().map(|x| os(x)).peekable()).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn unified_valid() {
|
||||
for args in [vec!["-u"], vec!["--unified"], vec!["--unified="]] {
|
||||
let mut params = vec!["diff"];
|
||||
params.extend(args);
|
||||
params.extend(["foo", "bar"]);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
format: Format::Unified,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(params.iter().map(|x| os(x)).peekable())
|
||||
);
|
||||
}
|
||||
for args in [
|
||||
vec!["-u42"],
|
||||
vec!["-U42"],
|
||||
vec!["-U", "42"],
|
||||
vec!["--unified=42"],
|
||||
vec!["-42u"],
|
||||
] {
|
||||
let mut params = vec!["diff"];
|
||||
params.extend(args);
|
||||
params.extend(["foo", "bar"]);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
format: Format::Unified,
|
||||
context_count: 42,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(params.iter().map(|x| os(x)).peekable())
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn unified_invalid() {
|
||||
for args in [
|
||||
vec!["-u", "42"],
|
||||
vec!["-u=42"],
|
||||
vec!["-u="],
|
||||
vec!["-U"],
|
||||
vec!["-U=42"],
|
||||
vec!["-U="],
|
||||
vec!["--unified42"],
|
||||
vec!["--unified", "42"],
|
||||
vec!["-42U"],
|
||||
] {
|
||||
let mut params = vec!["diff"];
|
||||
params.extend(args);
|
||||
params.extend(["foo", "bar"]);
|
||||
assert!(parse_params(params.iter().map(|x| os(x)).peekable()).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn context_count() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
format: Format::Unified,
|
||||
context_count: 54,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("-u54"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
format: Format::Unified,
|
||||
context_count: 54,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("-U54"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
format: Format::Unified,
|
||||
context_count: 54,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("-U"), os("54"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
format: Format::Context,
|
||||
context_count: 54,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("-c54"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn report_identical_files() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
report_identical_files: true,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("-s"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
report_identical_files: true,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[
|
||||
os("diff"),
|
||||
os("--report-identical-files"),
|
||||
os("foo"),
|
||||
os("bar"),
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn brief() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
brief: true,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("-q"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
brief: true,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("--brief"), os("foo"), os("bar"),]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn expand_tabs() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
for option in ["-t", "--expand-tabs"] {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
expand_tabs: true,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os(option), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn tabsize() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
tabsize: 1,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("--tabsize=1"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
tabsize: 42,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("--tabsize=42"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
assert!(parse_params(
|
||||
[os("diff"), os("--tabsize"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
assert!(parse_params(
|
||||
[os("diff"), os("--tabsize="), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
assert!(parse_params(
|
||||
[os("diff"), os("--tabsize=r2"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
assert!(parse_params(
|
||||
[os("diff"), os("--tabsize=-1"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
assert!(parse_params(
|
||||
[os("diff"), os("--tabsize=r2"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
assert!(parse_params(
|
||||
[
|
||||
os("diff"),
|
||||
os("--tabsize=92233720368547758088"),
|
||||
os("foo"),
|
||||
os("bar")
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
#[test]
|
||||
fn width() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("bar"),
|
||||
width: 100,
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("--width=100"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn width_suffix_is_an_operand() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("xyz--width=5"),
|
||||
to: os("foo"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("xyz--width=5"), os("foo")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn width_non_utf8_is_not_an_option() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
// used to panic in into_string().unwrap()
|
||||
let bad = OsString::from_vec(b"\xff--width=5".to_vec());
|
||||
let params = parse_params(
|
||||
[os("diff"), bad.clone(), os("foo")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(params.from, bad);
|
||||
}
|
||||
#[test]
|
||||
fn double_dash() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("-g"),
|
||||
to: os("-h"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params(
|
||||
[os("diff"), os("--"), os("-g"), os("-h")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn default_to_stdin() {
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("foo"),
|
||||
to: os("-"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params([os("diff"), os("foo"), os("-")].iter().cloned().peekable())
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("-"),
|
||||
to: os("bar"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params([os("diff"), os("-"), os("bar")].iter().cloned().peekable())
|
||||
);
|
||||
assert_eq!(
|
||||
Ok(Params {
|
||||
executable: os("diff"),
|
||||
from: os("-"),
|
||||
to: os("-"),
|
||||
..Default::default()
|
||||
}),
|
||||
parse_params([os("diff"), os("-"), os("-")].iter().cloned().peekable())
|
||||
);
|
||||
assert!(parse_params(
|
||||
[os("diff"), os("foo"), os("bar"), os("-")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
assert!(parse_params(
|
||||
[os("diff"), os("-"), os("-"), os("-")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
#[test]
|
||||
fn missing_arguments() {
|
||||
assert!(parse_params([os("diff")].iter().cloned().peekable()).is_err());
|
||||
assert!(parse_params([os("diff"), os("foo")].iter().cloned().peekable()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn unknown_argument() {
|
||||
assert!(parse_params(
|
||||
[os("diff"), os("-g"), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
assert!(
|
||||
parse_params([os("diff"), os("-g"), os("bar")].iter().cloned().peekable()).is_err()
|
||||
);
|
||||
assert!(parse_params([os("diff"), os("-g")].iter().cloned().peekable()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn empty() {
|
||||
assert!(parse_params([].iter().cloned().peekable()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn conflicting_output_styles() {
|
||||
for (arg1, arg2) in [
|
||||
("-u", "-c"),
|
||||
("-u", "-e"),
|
||||
("-c", "-u"),
|
||||
("-c", "-U42"),
|
||||
("-u", "--normal"),
|
||||
("--normal", "-e"),
|
||||
("--context", "--normal"),
|
||||
] {
|
||||
assert!(parse_params(
|
||||
[os("diff"), os(arg1), os(arg2), os("foo"), os("bar")]
|
||||
.iter()
|
||||
.cloned()
|
||||
.peekable()
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,300 @@
|
||||
// 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 regex::Regex;
|
||||
use std::{ffi::OsString, io::Write};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// Replace tabs by spaces in the input line.
|
||||
/// Correctly handle multi-bytes characters.
|
||||
/// This assumes that line does not contain any line breaks (if it does, the result is undefined).
|
||||
#[must_use]
|
||||
pub fn do_expand_tabs(line: &[u8], tabsize: usize) -> Vec<u8> {
|
||||
let tab = b'\t';
|
||||
let ntabs = line.iter().filter(|c| **c == tab).count();
|
||||
if ntabs == 0 {
|
||||
return line.to_vec();
|
||||
}
|
||||
let mut result = Vec::with_capacity(line.len() + ntabs * (tabsize - 1));
|
||||
let mut offset = 0;
|
||||
|
||||
let mut iter = line.split(|c| *c == tab).peekable();
|
||||
while let Some(chunk) = iter.next() {
|
||||
match String::from_utf8(chunk.to_vec()) {
|
||||
Ok(s) => offset += UnicodeWidthStr::width(s.as_str()),
|
||||
Err(_) => offset += chunk.len(),
|
||||
}
|
||||
result.extend_from_slice(chunk);
|
||||
if iter.peek().is_some() {
|
||||
result.resize(result.len() + tabsize - offset % tabsize, b' ');
|
||||
offset = 0;
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Write a single line to an output stream, expanding tabs to space if necessary.
|
||||
/// This assumes that line does not contain any line breaks
|
||||
/// (if it does and tabs are to be expanded to spaces, the result is undefined).
|
||||
pub fn do_write_line(
|
||||
output: &mut Vec<u8>,
|
||||
line: &[u8],
|
||||
expand_tabs: bool,
|
||||
tabsize: usize,
|
||||
) -> std::io::Result<()> {
|
||||
if expand_tabs {
|
||||
output.write_all(do_expand_tabs(line, tabsize).as_slice())
|
||||
} else {
|
||||
output.write_all(line)
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the modification time of the input file specified by file path
|
||||
/// If an error occurs, it returns the current system time
|
||||
pub fn get_modification_time(file_path: &str) -> String {
|
||||
use chrono::{DateTime, Local};
|
||||
use std::fs;
|
||||
use std::time::SystemTime;
|
||||
|
||||
let modification_time: SystemTime = fs::metadata(file_path)
|
||||
.and_then(|m| m.modified())
|
||||
.unwrap_or(SystemTime::now());
|
||||
|
||||
let modification_time: DateTime<Local> = modification_time.into();
|
||||
let modification_time: String = modification_time
|
||||
.format("%Y-%m-%d %H:%M:%S%.9f %z")
|
||||
.to_string();
|
||||
|
||||
modification_time
|
||||
}
|
||||
|
||||
pub fn format_failure_to_read_input_file(
|
||||
executable: &OsString,
|
||||
filepath: &OsString,
|
||||
error: &std::io::Error,
|
||||
) -> String {
|
||||
// std::io::Error's display trait outputs "{detail} (os error {code})"
|
||||
// but we want only the {detail} (error string) part
|
||||
let error_code_re = Regex::new(r"\ \(os\ error\ \d+\)$").unwrap();
|
||||
format!(
|
||||
"{}: {}: {}",
|
||||
executable.to_string_lossy(),
|
||||
filepath.to_string_lossy(),
|
||||
error_code_re.replace(error.to_string().as_str(), ""),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn report_failure_to_read_input_file(
|
||||
executable: &OsString,
|
||||
filepath: &OsString,
|
||||
error: &std::io::Error,
|
||||
) {
|
||||
eprintln!(
|
||||
"{}",
|
||||
format_failure_to_read_input_file(executable, filepath, error)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod testcmds {
|
||||
// Command construction wrapper that provides some validation and non-obscure, "fail fast"
|
||||
// feedback and error messages.
|
||||
use std::any::Any;
|
||||
use std::io::Write;
|
||||
use std::panic::catch_unwind;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
pub struct CmdFactory {
|
||||
cmd: &'static str,
|
||||
validated_once: LazyLock<Result<(), String>>,
|
||||
validate: fn(&CmdFactory) -> (),
|
||||
}
|
||||
|
||||
impl CmdFactory {
|
||||
pub fn new(&self) -> Command {
|
||||
match &*self.validated_once {
|
||||
Ok(()) => Command::new(self.cmd),
|
||||
Err(errmsg) => panic!(
|
||||
"'{}' validation failed in earlier thread/test: {}",
|
||||
self.cmd, errmsg
|
||||
),
|
||||
}
|
||||
}
|
||||
// "self" is not compatible with static initialization
|
||||
fn try_catch_validate(cmd: &CmdFactory) -> Result<(), String> {
|
||||
// Note catch_unwind() does _not_ hide error messages, stack traces, etc.
|
||||
catch_unwind(|| {
|
||||
let _ = (cmd.validate)(cmd);
|
||||
})
|
||||
.map_err(find_panic_message)
|
||||
}
|
||||
}
|
||||
|
||||
fn find_panic_message(payload: Box<dyn Any + Send>) -> String {
|
||||
// https://github.com/rust-lang/rust/blob/1.95.0/library/std/src/panicking.rs#L771
|
||||
if let Some(&s) = payload.downcast_ref::<&'static str>() {
|
||||
String::from(s)
|
||||
} else if let Some(s) = payload.downcast_ref::<String>() {
|
||||
s.clone()
|
||||
} else {
|
||||
format!(
|
||||
"Unusual panic payload type {:?}, look for the first thread/test that failed",
|
||||
payload.type_id(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub static PATCH_CMD: CmdFactory = CmdFactory {
|
||||
cmd: if cfg!(target_os = "macos") {
|
||||
"gpatch" // brew install gpatch
|
||||
} else {
|
||||
"patch"
|
||||
},
|
||||
validated_once: LazyLock::new(|| CmdFactory::try_catch_validate(&PATCH_CMD)),
|
||||
|
||||
validate: (|myself| {
|
||||
let output = Command::new(myself.cmd)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.expect(format!("`{} --version` failed", myself.cmd).as_str());
|
||||
// Non-GNU versions have subtle differences. When some newlines are missing in some test
|
||||
// patches, the macOS version can even stall the whole test run.
|
||||
assert!(output.stdout.starts_with(b"GNU patch"));
|
||||
assert!(output.status.success());
|
||||
}),
|
||||
};
|
||||
|
||||
pub static ED_CMD: CmdFactory = CmdFactory {
|
||||
cmd: "ed",
|
||||
validated_once: LazyLock::new(|| CmdFactory::try_catch_validate(&ED_CMD)),
|
||||
|
||||
validate: (|myself| {
|
||||
let mut child = Command::new(myself.cmd)
|
||||
.arg("!echo hello_ed")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("Failed to start 'ed' command");
|
||||
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
writeln!(stdin, "1p\nq").expect("Failed to send command to 'ed'");
|
||||
|
||||
let output = child
|
||||
.wait_with_output()
|
||||
.expect("Failed to read 'ed' stdout");
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout), "9\nhello_ed\n");
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
mod expand_tabs {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn assert_tab_expansion(line: &str, tabsize: usize, expected: &str) {
|
||||
assert_eq!(
|
||||
do_expand_tabs(line.as_bytes(), tabsize),
|
||||
expected.as_bytes()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basics() {
|
||||
assert_tab_expansion("foo barr baz", 8, "foo barr baz");
|
||||
assert_tab_expansion("foo\tbarr\tbaz", 8, "foo barr baz");
|
||||
assert_tab_expansion("foo\tbarr\tbaz", 5, "foo barr baz");
|
||||
assert_tab_expansion("foo\tbarr\tbaz", 2, "foo barr baz");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multibyte_chars() {
|
||||
assert_tab_expansion("foo\tépée\tbaz", 8, "foo épée baz");
|
||||
assert_tab_expansion("foo\t😉\tbaz", 5, "foo 😉 baz");
|
||||
|
||||
// Note: The Woman Scientist emoji (👩🔬) is a ZWJ sequence combining
|
||||
// the Woman emoji (👩) and the Microscope emoji (🔬). On supported platforms
|
||||
// it is displayed as a single emoji and has a print size of 2 columns.
|
||||
// Terminal emulators tend to not support this, and display the two emojis
|
||||
// side by side, thus accounting for a print size of 4 columns, but the
|
||||
// unicode_width crate reports a correct size of 2.
|
||||
assert_tab_expansion("foo\t👩🔬\tbaz", 6, "foo 👩🔬 baz");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8() {
|
||||
// [240, 240, 152, 137] is an invalid UTF-8 sequence, so it is handled as 4 bytes
|
||||
assert_eq!(
|
||||
do_expand_tabs(&[240, 240, 152, 137, 9, 102, 111, 111], 8),
|
||||
&[240, 240, 152, 137, 32, 32, 32, 32, 102, 111, 111]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
mod write_line {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn assert_line_written(line: &str, expand_tabs: bool, tabsize: usize, expected: &str) {
|
||||
let mut output: Vec<u8> = Vec::new();
|
||||
assert!(do_write_line(&mut output, line.as_bytes(), expand_tabs, tabsize).is_ok());
|
||||
assert_eq!(output, expected.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basics() {
|
||||
assert_line_written("foo bar baz", false, 8, "foo bar baz");
|
||||
assert_line_written("foo bar\tbaz", false, 8, "foo bar\tbaz");
|
||||
assert_line_written("foo bar\tbaz", true, 8, "foo bar baz");
|
||||
}
|
||||
}
|
||||
|
||||
mod modification_time {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn set_time() {
|
||||
use chrono::{DateTime, Local};
|
||||
use std::time::SystemTime;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
let temp = NamedTempFile::new().unwrap();
|
||||
// set file modification time equal to current time
|
||||
let current = SystemTime::now();
|
||||
let _ = temp.as_file().set_modified(current);
|
||||
|
||||
// format current time
|
||||
let current: DateTime<Local> = current.into();
|
||||
let current: String = current.format("%Y-%m-%d %H:%M:%S%.9f %z").to_string();
|
||||
|
||||
// verify
|
||||
assert_eq!(
|
||||
current,
|
||||
get_modification_time(&temp.path().to_string_lossy())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_file() {
|
||||
use chrono::{DateTime, Local};
|
||||
use std::time::SystemTime;
|
||||
|
||||
let invalid_file = "target/utils/invalid-file";
|
||||
|
||||
// store current time before calling `get_modification_time`
|
||||
// Because the file is invalid, it will return SystemTime::now()
|
||||
// which will be greater than previously saved time
|
||||
let current_time: DateTime<Local> = SystemTime::now().into();
|
||||
let m_time: DateTime<Local> = get_modification_time(invalid_file).parse().unwrap();
|
||||
|
||||
assert!(m_time > current_time);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user