From 5abeb012e8c0155132122781cb597ca811c497fc Mon Sep 17 00:00:00 2001 From: Roy Ivy III Date: Thu, 29 Dec 2022 22:38:44 -0600 Subject: [PATCH] fix/sleep: improve match of error output to GNU practices --- src/uu/sleep/src/sleep.rs | 47 +++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/src/uu/sleep/src/sleep.rs b/src/uu/sleep/src/sleep.rs index a39e9ce6f..d34cbe942 100644 --- a/src/uu/sleep/src/sleep.rs +++ b/src/uu/sleep/src/sleep.rs @@ -9,8 +9,8 @@ use std::thread; use std::time::Duration; use uucore::{ - error::{UResult, UUsageError}, - format_usage, + error::{UResult, USimpleError, UUsageError}, + format_usage, show, }; use clap::{crate_version, Arg, ArgAction, Command}; @@ -33,12 +33,21 @@ mod options { pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().try_get_matches_from(args)?; - if let Some(values) = matches.get_many::(options::NUMBER) { - let numbers = values.map(|s| s.as_str()).collect::>(); - return sleep(&numbers); - } + let numbers = matches + .get_many::(options::NUMBER) + .ok_or_else(|| { + USimpleError::new( + 1, + format!( + "missing operand\nTry '{} --help' for more information.", + uucore::execution_phrase() + ), + ) + })? + .map(|s| s.as_str()) + .collect::>(); - Ok(()) + return sleep(&numbers); } pub fn uu_app() -> Command { @@ -52,20 +61,24 @@ pub fn uu_app() -> Command { Arg::new(options::NUMBER) .help("pause for NUMBER seconds") .value_name(options::NUMBER) - .action(ArgAction::Append) - .required(true), + .action(ArgAction::Append), ) } fn sleep(args: &[&str]) -> UResult<()> { - let sleep_dur = - args.iter().try_fold( - Duration::new(0, 0), - |result, arg| match uucore::parse_time::from_str(&arg[..]) { - Ok(m) => Ok(m.saturating_add(result)), - Err(f) => Err(UUsageError::new(1, f)), - }, - )?; + let mut arg_error = false; + let intervals = args.iter().map(|s| match uucore::parse_time::from_str(s) { + Ok(result) => result, + Err(err) => { + arg_error = true; + show!(USimpleError::new(1, err)); + Duration::new(0, 0) + } + }); + let sleep_dur = intervals.fold(Duration::new(0, 0), |acc, n| acc + n); + if arg_error { + return Err(UUsageError::new(1, "")); + }; thread::sleep(sleep_dur); Ok(()) }