From 4b61e4c15e99cf42c929d122211540028ecfcd55 Mon Sep 17 00:00:00 2001 From: draarivpatel-ui <287273626+draarivpatel-ui@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:00:16 -0600 Subject: [PATCH] diff: match GNU command-line error messages --- src/params.rs | 152 +++++++++++++++++++++++++++---------- tests/by-util/test_diff.rs | 29 ++++++- 2 files changed, 139 insertions(+), 42 deletions(-) diff --git a/src/params.rs b/src/params.rs index f26c7149..cd0b5d4e 100644 --- a/src/params.rs +++ b/src/params.rs @@ -121,11 +121,17 @@ impl Default for Params { } } -fn extra_operand(executable: &OsStr, param: &OsStr) -> String { +/// A command-line error formatted the way GNU reports it: the utility +/// name, the message and a pointer to --help. +fn usage_error(executable: &OsStr, message: impl std::fmt::Display) -> String { let exe = executable.to_string_lossy(); - format!( - "{exe}: extra operand '{}'\n{exe}: Try '{exe} --help' for more information.", - param.to_string_lossy() + format!("{exe}: {message}\n{exe}: Try '{exe} --help' for more information.") +} + +fn extra_operand(executable: &OsStr, param: &OsStr) -> String { + usage_error( + executable, + format!("extra operand '{}'", param.to_string_lossy()), ) } @@ -158,7 +164,10 @@ pub fn parse_params>( let bytes = param.as_encoded_bytes(); let label = if bytes == b"-L" || bytes == b"--label" { Some(opts.next().map(|(_, label)| label).ok_or_else(|| { - format!("option '{}' requires an argument", param.to_string_lossy()) + usage_error( + ¶ms.executable, + format!("option '{}' requires an argument", param.to_string_lossy()), + ) })?) } else { bytes @@ -174,7 +183,10 @@ pub fn parse_params>( } else if params.to_label.is_none() { params.to_label = Some(label); } else { - return Err("too many file label options".to_string()); + return Err(usage_error( + ¶ms.executable, + "too many file label options", + )); } continue; } @@ -220,13 +232,21 @@ pub fn parse_params>( "auto" => ColorWhen::Auto, "always" => ColorWhen::Always, "never" => ColorWhen::Never, - _ => return Err(format!("invalid color '{when}'")), + _ => { + return Err(usage_error( + ¶ms.executable, + format!("invalid color '{when}'"), + )) + } }; continue; } if param == "--palette" { let Some((_, palette)) = opts.next() else { - return Err("option '--palette' requires an argument".to_string()); + return Err(usage_error( + ¶ms.executable, + "option '--palette' requires an argument", + )); }; params.palette = Some(palette.to_string_lossy().into_owned()); continue; @@ -241,12 +261,14 @@ pub fn parse_params>( } if param == "-p" || param == "--show-c-function" { show_c_function = true; - push_function_line_pattern(&mut params, C_FUNCTION_PATTERN)?; + push_function_line_pattern(&mut params, C_FUNCTION_PATTERN) + .map_err(|e| format!("{}: {e}", params.executable.to_string_lossy()))?; continue; } if let Some(argument) = option_argument(¶m, Some("-F"), "--show-function-line") { - let pattern = argument_value(argument, ¶m, &mut opts)?; - push_function_line_pattern(&mut params, &pattern.to_string_lossy())?; + let pattern = argument_value(argument, ¶m, &mut opts, ¶ms.executable)?; + push_function_line_pattern(&mut params, &pattern.to_string_lossy()) + .map_err(|e| format!("{}: {e}", params.executable.to_string_lossy()))?; continue; } if param == "--no-dereference" { @@ -262,7 +284,12 @@ pub fn parse_params>( continue; } if let Some(argument) = option_argument(¶m, Some("-S"), "--starting-file") { - params.starting_file = Some(argument_value(argument, ¶m, &mut opts)?); + params.starting_file = Some(argument_value( + argument, + ¶m, + &mut opts, + ¶ms.executable, + )?); continue; } if param == "-r" || param == "--recursive" { @@ -287,44 +314,63 @@ pub fn parse_params>( } if param == "--normal" { if format.is_some() && format != Some(Format::Normal) { - return Err("Conflicting output style options".to_string()); + return Err(usage_error( + ¶ms.executable, + "conflicting output style options", + )); } 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()); + return Err(usage_error( + ¶ms.executable, + "conflicting output style options", + )); } 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()); + return Err(usage_error( + ¶ms.executable, + "conflicting output style options", + )); } format = Some(Format::SideBySide); continue; } if let Some(argument) = option_argument(¶m, Some("-W"), "--width") { - let width_value = argument_value(argument, ¶m, &mut opts)?; + let width_value = argument_value(argument, ¶m, &mut opts, ¶ms.executable)?; let width_str = width_value.to_string_lossy(); params.width = match width_str.parse::() { Ok(num) if num > 0 => num, - _ => return Err(format!("invalid width «{width_str}»")), + _ => { + return Err(usage_error( + ¶ms.executable, + format!("invalid width «{width_str}»"), + )) + } }; continue; } if let Some(argument) = option_argument(¶m, None, "--tabsize") { - let tabsize_value = argument_value(argument, ¶m, &mut opts)?; + let tabsize_value = argument_value(argument, ¶m, &mut opts, ¶ms.executable)?; let tabsize_str = tabsize_value.to_string_lossy(); params.tabsize = match tabsize_str.parse::() { Ok(num) if num > 0 && num <= MAX_TABSIZE => num, - _ => return Err(format!("invalid tabsize «{tabsize_str}»")), + _ => { + return Err(usage_error( + ¶ms.executable, + format!("invalid tabsize «{tabsize_str}»"), + )) + } }; continue; } - match match_context_diff_params(¶m, next_param, format) { + match match_context_diff_params(¶m, next_param, format, ¶ms.executable) { Ok(DiffStyleMatch { is_match, context_count, @@ -341,7 +387,7 @@ pub fn parse_params>( } Err(error) => return Err(error), } - match match_unified_diff_params(¶m, next_param, format) { + match match_unified_diff_params(¶m, next_param, format, ¶ms.executable) { Ok(DiffStyleMatch { is_match, context_count, @@ -359,7 +405,10 @@ pub fn parse_params>( Err(error) => return Err(error), } if param.to_string_lossy().starts_with('-') { - return Err(format!("unrecognized option '{}'", param.to_string_lossy())); + return Err(usage_error( + ¶ms.executable, + format!("unrecognized option '{}'", param.to_string_lossy()), + )); } operand_positions.push(position); if from.is_none() { @@ -376,9 +425,9 @@ pub fn parse_params>( operand_positions.push(position); param } else { - return Err(format!( - "Usage: {} ", - params.executable.to_string_lossy() + return Err(usage_error( + ¶ms.executable, + format!("Usage: {} ", params.executable.to_string_lossy()), )); }; params.to = if let Some(to) = to { @@ -387,9 +436,9 @@ pub fn parse_params>( operand_positions.push(position); param } else { - return Err(format!( - "Usage: {} ", - params.executable.to_string_lossy() + return Err(usage_error( + ¶ms.executable, + format!("Usage: {} ", params.executable.to_string_lossy()), )); }; // Operands after `--` are not checked by the option loop above. @@ -492,13 +541,16 @@ fn argument_value( argument: OptionArgument, param: &OsStr, opts: &mut impl Iterator, + executable: &OsStr, ) -> Result { match argument { OptionArgument::Attached(value) => Ok(value.into()), - OptionArgument::Separate => opts - .next() - .map(|(_, value)| value) - .ok_or_else(|| format!("option '{}' requires an argument", param.to_string_lossy())), + OptionArgument::Separate => opts.next().map(|(_, value)| value).ok_or_else(|| { + usage_error( + executable, + format!("option '{}' requires an argument", param.to_string_lossy()), + ) + }), } } @@ -526,6 +578,7 @@ fn match_context_diff_params( param: &OsString, next_param: Option<&OsString>, format: Option, + executable: &OsStr, ) -> Result { const CONTEXT_RE: &str = r"^(-[cC](?\d*)|--context(=(?\d*))?|-(?\d+)c)$"; let regex = Regex::new(CONTEXT_RE).unwrap(); @@ -534,7 +587,7 @@ fn match_context_diff_params( 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()); + return Err(usage_error(executable, "conflicting output style options")); } let captures = regex.captures(param.to_str().unwrap()).unwrap(); let num = captures @@ -554,7 +607,12 @@ fn match_context_diff_params( context_count = Some(context_size); next_param_consumed = true; } - Err(_) => return Err(format!("invalid context length '{size_str}'")), + Err(_) => { + return Err(usage_error( + executable, + format!("invalid context length '{size_str}'"), + )) + } } } } @@ -570,6 +628,7 @@ fn match_unified_diff_params( param: &OsString, next_param: Option<&OsString>, format: Option, + executable: &OsStr, ) -> Result { const UNIFIED_RE: &str = r"^(-[uU](?\d*)|--unified(=(?\d*))?|-(?\d+)u)$"; let regex = Regex::new(UNIFIED_RE).unwrap(); @@ -578,7 +637,7 @@ fn match_unified_diff_params( 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()); + return Err(usage_error(executable, "conflicting output style options")); } let captures = regex.captures(param.to_str().unwrap()).unwrap(); let num = captures @@ -598,7 +657,12 @@ fn match_unified_diff_params( context_count = Some(context_size); next_param_consumed = true; } - Err(_) => return Err(format!("invalid context length '{size_str}'")), + Err(_) => { + return Err(usage_error( + executable, + format!("invalid context length '{size_str}'"), + )) + } } } } @@ -1061,7 +1125,10 @@ mod tests { ); } assert_eq!( - Err("option '--tabsize' requires an argument".to_string()), + Err(usage_error( + &os("diff"), + "option '--tabsize' requires an argument" + )), parse_params( [os("diff"), os("foo"), os("bar"), os("--tabsize")] .iter() @@ -1118,7 +1185,10 @@ mod tests { .is_err()); for too_large in [(MAX_TABSIZE + 1).to_string(), usize::MAX.to_string()] { assert_eq!( - Err(format!("invalid tabsize «{too_large}»")), + Err(usage_error( + &os("diff"), + format!("invalid tabsize «{too_large}»") + )), parse_params( [ os("diff"), @@ -1189,7 +1259,7 @@ mod tests { .chain(["foo", "bar"]) .chain(args.iter().copied()); assert_eq!( - Err(error.to_string()), + Err(usage_error(&os("diff"), error)), parse_params(cmd_args.map(os).peekable()) ); } @@ -1220,7 +1290,7 @@ mod tests { ) ); assert_eq!( - Err("too many file label options".to_string()), + Err(usage_error(&os("diff"), "too many file label options")), parse_params( [ os("diff"), @@ -1470,7 +1540,7 @@ mod tests { assert_eq!( parse(&["-F", "oops\\"]), - Err("'oops\\': Trailing backslash".to_string()) + Err("diff: 'oops\\': Trailing backslash".to_string()) ); } diff --git a/tests/by-util/test_diff.rs b/tests/by-util/test_diff.rs index 5879b50a..083b11c6 100644 --- a/tests/by-util/test_diff.rs +++ b/tests/by-util/test_diff.rs @@ -1009,7 +1009,7 @@ fn function_lines() { ts.ucmd() .args(&["-u", "-F", "\\(", "old.c", "new.c"]) .fails_with_code(2) - .stderr_is("'\\(': Unmatched ( or \\(\n"); + .stderr_is("diff: '\\(': Unmatched ( or \\(\n"); } // A function line is cut at 40 bytes, even inside a multi-byte character. @@ -1336,3 +1336,30 @@ fn ignore_tab_expansion_with_differing_files() { .fails_with_code(1) .stdout_contains(" header\t1\n-old line\n+new line\n footer\t2\n"); } + +// Errors while parsing options are prefixed with the utility name like GNU +// and add the "Try --help" line; other command-line errors get only the +// prefix. +#[test] +fn usage_errors_have_program_prefix() { + let (at, ts) = at_and_ts!(); + at.write("file", "x\n"); + + ts.ucmd() + .args(&["--bogus", "file", "file"]) + .fails_with_code(2) + .stderr_is( + "diff: unrecognized option '--bogus'\ndiff: Try 'diff --help' for more information.\n", + ); + ts.ucmd() + .args(&["-c", "-u", "file", "file"]) + .fails_with_code(2) + .stderr_is( + "diff: conflicting output style options\ndiff: Try 'diff --help' for more information.\n", + ); + + ts.ucmd() + .args(&["-F", "\\", "file", "file"]) + .fails_with_code(2) + .stderr_is("diff: '\\': Trailing backslash\n"); +}