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
159 changes: 81 additions & 78 deletions src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,6 @@ pub fn parse_params<I: Iterator<Item = OsString>>(
let mut format = None;
let mut context = None;
let mut show_c_function = false;
let tabsize_re = Regex::new(r"^--tabsize=(?<num>\d+)$").unwrap();
let width_re = Regex::new(r"^--width=(?P<long>\d+)$").unwrap();
while let Some((position, param)) = opts.next() {
// -L LABEL, -LLABEL, --label LABEL or --label=LABEL: the first names
// the from-file in headers and messages, the second the to-file.
Expand Down Expand Up @@ -244,7 +242,7 @@ pub fn parse_params<I: Iterator<Item = OsString>>(
push_function_line_pattern(&mut params, C_FUNCTION_PATTERN)?;
continue;
}
if let Some(argument) = option_argument(&param, "-F", "--show-function-line") {
if let Some(argument) = option_argument(&param, Some("-F"), "--show-function-line") {
let pattern = argument_value(argument, &param, &mut opts)?;
push_function_line_pattern(&mut params, &pattern.to_string_lossy())?;
continue;
Expand All @@ -261,7 +259,7 @@ pub fn parse_params<I: Iterator<Item = OsString>>(
params.ignore_file_name_case = false;
continue;
}
if let Some(argument) = option_argument(&param, "-S", "--starting-file") {
if let Some(argument) = option_argument(&param, Some("-S"), "--starting-file") {
params.starting_file = Some(argument_value(argument, &param, &mut opts)?);
continue;
}
Expand Down Expand Up @@ -302,42 +300,22 @@ pub fn parse_params<I: Iterator<Item = OsString>>(
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();

if let Some(argument) = option_argument(&param, Some("-W"), "--width") {
let width_value = argument_value(argument, &param, &mut opts)?;
let width_str = width_value.to_string_lossy();
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}»")),
Ok(num) if num > 0 => num,
_ => 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();
if let Some(argument) = option_argument(&param, None, "--tabsize") {
let tabsize_value = argument_value(argument, &param, &mut opts)?;
let tabsize_str = tabsize_value.to_string_lossy();
params.tabsize = match tabsize_str.parse::<usize>() {
Ok(num) if num != 0 && num <= MAX_TABSIZE => num,
Ok(num) if num > 0 && num <= MAX_TABSIZE => num,
_ => return Err(format!("invalid tabsize «{tabsize_str}»")),
};

continue;
}
match match_context_diff_params(&param, next_param, format) {
Expand Down Expand Up @@ -486,16 +464,24 @@ enum OptionArgument<'a> {

/// Returns how the argument of the option named `short` (like `-F`) or
/// `long` is given, if `param` is that option.
fn option_argument<'a>(param: &'a OsStr, short: &str, long: &str) -> Option<OptionArgument<'a>> {
if param == short || param == long {
fn option_argument<'a>(
param: &'a OsStr,
short: Option<&str>,
long: &str,
) -> Option<OptionArgument<'a>> {
if short.is_some_and(|s| param == s) || param == long {
return Some(OptionArgument::Separate);
}
let param = param.to_str()?;
param
.strip_prefix(long)
.and_then(|rest| rest.strip_prefix('='))
.or_else(|| param.strip_prefix(short).filter(|value| !value.is_empty()))
.map(OptionArgument::Attached)
if let Some(rest) = param.strip_prefix(long).and_then(|r| r.strip_prefix('=')) {
return Some(OptionArgument::Attached(rest));
}
if let Some(short) = short {
if let Some(rest) = param.strip_prefix(short).filter(|value| !value.is_empty()) {
return Some(OptionArgument::Attached(rest));
}
}
None
}

/// Returns the value of the argument of the option `param`, taking the next
Expand Down Expand Up @@ -1030,31 +1016,25 @@ mod tests {
.peekable()
)
);
for args in [&["--tabsize", "42"][..], &["--tabsize=42"]] {
let cmd_args = std::iter::once("diff")
.chain(args.iter().copied())
.chain(["foo", "bar"]);
assert_eq!(
Ok(Params {
executable: os("diff"),
from: os("foo"),
to: os("bar"),
tabsize: 42,
..Default::default()
}),
parse_params(cmd_args.map(os).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()
}),
Err("option '--tabsize' requires an argument".to_string()),
parse_params(
[os("diff"), os("--tabsize=42"), os("foo"), os("bar")]
[os("diff"), os("foo"), os("bar"), os("--tabsize")]
.iter()
.cloned()
.peekable()
Expand Down Expand Up @@ -1146,21 +1126,44 @@ mod tests {
}
#[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()
)
);
for args in [
&["-W", "100"][..],
&["-W100"],
&["--width", "100"],
&["--width=100"],
] {
let cmd_args = std::iter::once("diff")
.chain(args.iter().copied())
.chain(["foo", "bar"]);
assert_eq!(
Ok(Params {
executable: os("diff"),
from: os("foo"),
to: os("bar"),
width: 100,
..Default::default()
}),
parse_params(cmd_args.map(os).peekable())
);
}
for (args, error) in [
(&["-W"][..], "option '-W' requires an argument"),
(&["--width"], "option '--width' requires an argument"),
(&["-W", "0"], "invalid width «0»"),
(&["-W0"], "invalid width «0»"),
(&["--width=0"], "invalid width «0»"),
(&["--width", "0"], "invalid width «0»"),
(&["-W", "abc"], "invalid width «abc»"),
(&["--width=abc"], "invalid width «abc»"),
] {
let cmd_args = std::iter::once("diff")
.chain(["foo", "bar"])
.chain(args.iter().copied());
assert_eq!(
Err(error.to_string()),
parse_params(cmd_args.map(os).peekable())
);
}
}
#[test]
fn labels() {
Expand Down
42 changes: 42 additions & 0 deletions tests/by-util/test_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1131,3 +1131,45 @@ fn label_errors(#[case] args: &[&str], #[case] error: &str) {
.fails_with_code(2)
.stderr_contains(error);
}

#[test]
fn width_option_forms() {
let (at, ts) = at_and_ts!();
at.write("w1", "x\n");
at.write("w2", "y\n");
for args in [
&["-W", "20"][..],
&["-W20"],
&["--width", "20"],
&["--width=20"],
] {
ts.ucmd()
.arg("-y")
.args(args)
.args(&["w1", "w2"])
.succeeds()
.stderr_is("")
.stdout_is("x <\n >\ty\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.

GNU prints x | y here (see #396), so this pins our side_diff divergence
could you please add a comment or open an issue for it?

}
ts.ucmd()
.args(&["--tabsize", "4", "w1", "w2"])
.fails_with_code(1);
}

#[rstest]
#[case::width_missing(&["file1", "file2", "-W"], "option '-W' requires an argument")]
#[case::width_long_missing(&["file1", "file2", "--width"], "option '--width' requires an argument")]
#[case::tabsize_missing(&["file1", "file2", "--tabsize"], "option '--tabsize' requires an argument")]
#[case::width_invalid_zero(&["-y", "-W", "0", "file1", "file2"], "invalid width «0»")]
#[case::width_invalid_text(&["-y", "--width", "abc", "file1", "file2"], "invalid width «abc»")]
#[case::tabsize_invalid_zero(&["--tabsize", "0", "file1", "file2"], "invalid tabsize «0»")]
#[case::tabsize_invalid_text(&["--tabsize", "foo", "file1", "file2"], "invalid tabsize «foo»")]
fn width_and_tabsize_errors(#[case] args: &[&str], #[case] error: &str) {
let (at, ts) = at_and_ts!();
at.write("file1", "foo\n");
at.write("file2", "bar\n");
ts.ucmd()
.args(args)
.fails_with_code(2)
.stderr_contains(error);
}
Loading