Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 60 additions & 20 deletions src/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ pub struct Params {
quiet: bool,
}

fn usage_error(executable: &str, msg: &str) -> String {
format!("{executable}: {msg}\n{executable}: Try '{executable} --help' for more information.")
}

#[inline]
fn usage_string(executable: &str) -> String {
format!("Usage: {executable} <from> <to>")
Expand Down Expand Up @@ -83,9 +87,10 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
Ok(num) => num,
Err(e) if *e.kind() == std::num::IntErrorKind::PosOverflow => SkipU64::MAX,
Err(_) => {
return Err(format!(
"{executable_str}: invalid --{option} value '{desc}'"
))
return Err(usage_error(
&executable_str,
&format!("invalid --{option} value '{desc}'"),
));
}
};

Expand All @@ -111,8 +116,9 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
"YB" => SkipU64::MAX, // 1_000_000_000_000_000_000_000_000,
"Y" => SkipU64::MAX, // 1_208_925_819_614_629_174_706_176,
_ => {
return Err(format!(
"{executable_str}: invalid --{option} value '{desc}'"
return Err(usage_error(
&executable_str,
&format!("invalid --{option} value '{desc}'"),
));
}
};
Expand All @@ -134,7 +140,14 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
let mut to = None;
let mut skip_pos1 = None;
let mut skip_pos2 = None;

let mut last_arg = params.executable.clone();

while let Some(param) = opts.next() {
if from.is_none() {
last_arg = param.clone();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this clones every argument, probably the 30% regression on the cmp_parser bench.
it only matters while from is none, could you please clone only then?

}

if param == "--" {
break;
}
Expand All @@ -144,7 +157,7 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
} else if to.is_none() {
to = Some(param);
} else {
return Err(usage_string(&executable_str));
return Err(usage_error(&executable_str, "extra operand '-'"));
}
continue;
}
Expand All @@ -166,7 +179,9 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
if param == "-n" || param_str.starts_with("--bytes=") {
let max_bytes = if param == "-n" {
opts.next()
.ok_or_else(|| usage_string(&executable_str))?
.ok_or_else(|| {
usage_error(&executable_str, "option requires an argument -- 'n'")
})?
.to_string_lossy()
.to_string()
} else {
Expand All @@ -179,7 +194,9 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
if param == "-i" || param_str.starts_with("--ignore-initial=") {
let skip_desc = if param == "-i" {
opts.next()
.ok_or_else(|| usage_string(&executable_str))?
.ok_or_else(|| {
usage_error(&executable_str, "option requires an argument -- 'i'")
})?
.to_string_lossy()
.to_string()
} else {
Expand Down Expand Up @@ -208,7 +225,10 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
std::process::exit(0);
}
if param_str.starts_with('-') {
return Err(format!("unrecognized option '{}'", param.to_string_lossy()));
return Err(usage_error(
&executable_str,
&format!("unrecognized option '{}'", param.to_string_lossy()),
));
}
if from.is_none() {
from = Some(param);
Expand All @@ -219,7 +239,10 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
} else if skip_pos2.is_none() {
skip_pos2 = Some(parse_size(&param_str, "ignore-initial", &param_str)?);
} else {
return Err(usage_string(&executable_str));
return Err(usage_error(
&executable_str,
&format!("extra operand '{param_str}'"),
));
}
}

Expand All @@ -233,8 +256,9 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
}

if params.quiet && params.verbose {
return Err(format!(
"{executable_str}: options -l and -s are incompatible"
return Err(usage_error(
&executable_str,
"options -l and -s are incompatible",
));
}

Expand All @@ -243,7 +267,10 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
} else if let Some(param) = opts.next() {
param
} else {
return Err(usage_string(&executable_str));
return Err(usage_error(
&executable_str,
&format!("missing operand after '{}'", last_arg.to_string_lossy()),
));
};
params.to = if let Some(to) = to {
to
Expand All @@ -266,6 +293,13 @@ pub fn parse_params<I: Iterator<Item = OsString>>(mut opts: Peekable<I>) -> Resu
}
}

if let Some(extra) = opts.next() {
return Err(usage_error(
&executable_str,
&format!("extra operand '{}'", extra.to_string_lossy()),
));
}

// Like GNU cmp, use the larger of the -i value and the positional skip.
params.skip_a = params.skip_a.max(skip_pos1);
params.skip_b = params.skip_b.max(skip_pos2);
Expand Down Expand Up @@ -782,7 +816,7 @@ mod tests {

// Bad positional arguments.
assert_eq!(
Err("Usage: cmp <from> <to>".to_string()),
Err("cmp: extra operand '3'\ncmp: Try 'cmp --help' for more information.".to_string()),
parse_params(
[os("cmp"), os("foo"), os("bar"), os("1"), os("2"), os("3")]
.iter()
Expand All @@ -791,7 +825,10 @@ mod tests {
)
);
assert_eq!(
Err("Usage: cmp <from> <to>".to_string()),
Err(
"cmp: missing operand after 'cmp'\ncmp: Try 'cmp --help' for more information."
.to_string()
),
parse_params([os("cmp")].iter().cloned().peekable())
);
}
Expand Down Expand Up @@ -904,7 +941,7 @@ mod tests {

// Some options do not mix.
assert_eq!(
Err("cmp: options -l and -s are incompatible".to_string()),
Err("cmp: options -l and -s are incompatible\ncmp: Try 'cmp --help' for more information.".to_string()),
parse_params(
[os("cmp"), os("-l"), os("-s"), os("foo"), os("bar")]
.iter()
Expand Down Expand Up @@ -987,7 +1024,10 @@ mod tests {

// Failure case
assert_eq!(
Err("cmp: invalid --bytes value '1x'".to_string()),
Err(
"cmp: invalid --bytes value '1x'\ncmp: Try 'cmp --help' for more information."
.to_string()
),
parse_params(
[os("cmp"), os("--bytes=1x"), os("foo"), os("bar")]
.iter()
Expand Down Expand Up @@ -1216,7 +1256,7 @@ mod tests {

// Failure cases
assert_eq!(
Err("cmp: invalid --ignore-initial value '1mb'".to_string()),
Err("cmp: invalid --ignore-initial value '1mb'\ncmp: Try 'cmp --help' for more information.".to_string()),
parse_params(
[os("cmp"), os("--ignore-initial=1mb"), os("foo"), os("bar")]
.iter()
Expand All @@ -1225,7 +1265,7 @@ mod tests {
)
);
assert_eq!(
Err("cmp: invalid --ignore-initial value '1:2:3'".to_string()),
Err("cmp: invalid --ignore-initial value '1:2:3'\ncmp: Try 'cmp --help' for more information.".to_string()),
parse_params(
[
os("cmp"),
Expand All @@ -1239,7 +1279,7 @@ mod tests {
)
);
assert_eq!(
Err("cmp: invalid --ignore-initial value '-1'".to_string()),
Err("cmp: invalid --ignore-initial value '-1'\ncmp: Try 'cmp --help' for more information.".to_string()),
parse_params(
[os("cmp"), os("--ignore-initial=-1"), os("foo"), os("bar")]
.iter()
Expand Down
42 changes: 41 additions & 1 deletion tests/by-util/test_cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn cmp_incompatible_params() {
new_ucmd!()
.args(&["-l", "-s", "/etc/passwd", "/etc/group"])
.fails_with_code(2)
.stderr_str_check(|s| s.ends_with(": options -l and -s are incompatible\n"));
.stderr_str_check(|s| s.contains(": options -l and -s are incompatible\n"));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the description mentions new integration tests but i don't see them.
please add tests here for missing operand, extra operand (also after --), unrecognized option and -n/-i without argument

}

#[rstest]
Expand Down Expand Up @@ -336,3 +336,43 @@ fn cmp_difference_term_follows_messages_locale(
.fails_with_code(1)
.stdout_is(format!("a b differ: {term} 1, line 1\n"));
}

#[rstest]
#[case::missing_operand(
&[],
"cmp: missing operand after 'cmp'\ncmp: Try 'cmp --help' for more information.\n"
)]
#[case::missing_operand_after_flag(
&["-s"],
"cmp: missing operand after '-s'\ncmp: Try 'cmp --help' for more information.\n"
)]
#[case::unrecognized_option(
&["--bogus", "a", "b"],
"cmp: unrecognized option '--bogus'\ncmp: Try 'cmp --help' for more information.\n"
)]
#[case::extra_operand(
&["a", "b", "3", "4", "extra"],
"cmp: extra operand 'extra'\ncmp: Try 'cmp --help' for more information.\n"
)]
#[case::extra_operand_after_dashdash(
&["--", "a", "b", "3", "4", "extra"],
"cmp: extra operand 'extra'\ncmp: Try 'cmp --help' for more information.\n"
)]
#[case::n_requires_argument(
&["a", "b", "-n"],
"cmp: option requires an argument -- 'n'\ncmp: Try 'cmp --help' for more information.\n"
)]
#[case::i_requires_argument(
&["a", "b", "-i"],
"cmp: option requires an argument -- 'i'\ncmp: Try 'cmp --help' for more information.\n"
)]
#[case::extra_dash_operand(
&["a", "b", "1", "2", "-"],
"cmp: extra operand '-'\ncmp: Try 'cmp --help' for more information.\n"
)]
fn cmp_usage_errors_match_gnu(#[case] args: &[&str], #[case] expected_stderr: &str) {
new_ucmd!()
.args(args)
.fails_with_code(2)
.stderr_is(expected_stderr);
}
Loading