date: fix format for nanoseconds

This commit is contained in:
Jan Scheer 2021-05-11 23:03:59 +02:00
parent 019f1b1a88
commit 8200d399e8
2 changed files with 26 additions and 4 deletions

View file

@ -207,11 +207,16 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
.alias(OPT_UNIVERSAL_2) .alias(OPT_UNIVERSAL_2)
.help("print or set Coordinated Universal Time (UTC)"), .help("print or set Coordinated Universal Time (UTC)"),
) )
.arg(Arg::with_name(OPT_FORMAT).multiple(true)) .arg(Arg::with_name(OPT_FORMAT).multiple(false))
.get_matches_from(args); .get_matches_from(args);
let format = if let Some(form) = matches.value_of(OPT_FORMAT) { let format = if let Some(form) = matches.value_of(OPT_FORMAT) {
let form = form[1..].into(); if !form.starts_with('+') {
eprintln!("date: invalid date {}", form);
return 1;
}
// GNU `date` uses `%N` for nano seconds, however crate::chrono uses `%f`
let form = form[1..].replace("%N", "%f");
Format::Custom(form) Format::Custom(form)
} else if let Some(fmt) = matches } else if let Some(fmt) = matches
.values_of(OPT_ISO_8601) .values_of(OPT_ISO_8601)
@ -237,7 +242,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
let set_to = match matches.value_of(OPT_SET).map(parse_date) { let set_to = match matches.value_of(OPT_SET).map(parse_date) {
None => None, None => None,
Some(Err((input, _err))) => { Some(Err((input, _err))) => {
eprintln!("date: invalid date '{}'", input); eprintln!("date: invalid date {}", input);
return 1; return 1;
} }
Some(Ok(date)) => Some(date), Some(Ok(date)) => Some(date),
@ -301,7 +306,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
println!("{}", formatted); println!("{}", formatted);
} }
Err((input, _err)) => { Err((input, _err)) => {
println!("date: invalid date '{}'", input); println!("date: invalid date {}", input);
} }
} }
} }

View file

@ -104,6 +104,23 @@ fn test_date_format_full_day() {
.stdout_matches(&re); .stdout_matches(&re);
} }
#[test]
fn test_date_nano_seconds() {
// %N nanoseconds (000000000..999999999)
let re = Regex::new(r"^\d{1,9}$").unwrap();
new_ucmd!().arg("+%N").succeeds().stdout_matches(&re);
}
#[test]
fn test_date_format_without_plus() {
// [+FORMAT]
new_ucmd!()
.arg("%s")
.fails()
.stderr_contains("date: invalid date %s")
.code_is(1);
}
#[test] #[test]
#[cfg(all(unix, not(target_os = "macos")))] #[cfg(all(unix, not(target_os = "macos")))]
fn test_date_set_valid() { fn test_date_set_valid() {