From f595164063f161ae75c844bc6fd876f1f4174a35 Mon Sep 17 00:00:00 2001 From: Daniel Rocco Date: Sun, 14 Feb 2021 18:25:28 -0500 Subject: [PATCH] numfmt: prohibit --header=0 to align with GNU Adjust header option handling to prohibit passing a value of 0 to align with GNU numfmt. Also report header option parse errors as GNU does. closes #1708 --- src/uu/numfmt/src/numfmt.rs | 30 ++++++++++++++++++------------ tests/by-util/test_numfmt.rs | 24 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/src/uu/numfmt/src/numfmt.rs b/src/uu/numfmt/src/numfmt.rs index 3865619ea..4d3b7387a 100644 --- a/src/uu/numfmt/src/numfmt.rs +++ b/src/uu/numfmt/src/numfmt.rs @@ -291,11 +291,18 @@ fn parse_options(args: &ArgMatches) -> Result { let header = match args.occurrences_of(options::HEADER) { 0 => Ok(0), - _ => args - .value_of(options::HEADER) - .unwrap() - .parse::() - .map_err(|err| err.to_string()), + _ => { + let value = args.value_of(options::HEADER).unwrap(); + + value + .parse::() + .map_err(|_| value) + .and_then(|n| match n { + 0 => Err(value), + _ => Ok(n), + }) + .map_err(|value| format!("invalid header value ‘{}’", value)) + } }?; Ok(NumfmtOptions { @@ -423,17 +430,16 @@ pub fn uumain(args: impl uucore::Args) -> i32 { .arg(Arg::with_name(options::NUMBER).hidden(true).multiple(true)) .get_matches_from(args); - let options = parse_options(&matches).unwrap(); - - let result = match matches.values_of(options::NUMBER) { - Some(values) => handle_args(values, options), - None => handle_stdin(options), - }; + let result = + parse_options(&matches).and_then(|options| match matches.values_of(options::NUMBER) { + Some(values) => handle_args(values, options), + None => handle_stdin(options), + }); match result { Err(e) => { show_info!("{}", e); - exit!(1); + 1 } _ => 0, } diff --git a/tests/by-util/test_numfmt.rs b/tests/by-util/test_numfmt.rs index 625da766b..61667f310 100644 --- a/tests/by-util/test_numfmt.rs +++ b/tests/by-util/test_numfmt.rs @@ -107,6 +107,30 @@ fn test_header_default() { .stdout_is("header\n1000\n1100000\n100000000\n"); } +#[test] +fn test_header_error_if_non_numeric() { + new_ucmd!() + .args(&["--header=two"]) + .run() + .stderr_is("numfmt: invalid header value ‘two’"); +} + +#[test] +fn test_header_error_if_0() { + new_ucmd!() + .args(&["--header=0"]) + .run() + .stderr_is("numfmt: invalid header value ‘0’"); +} + +#[test] +fn test_header_error_if_negative() { + new_ucmd!() + .args(&["--header=-3"]) + .run() + .stderr_is("numfmt: invalid header value ‘-3’"); +} + #[test] fn test_negative() { new_ucmd!()