1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 19:47:45 +00:00

date: Catch panic from invalid format string (#4240)

* Catch panic from invalid date string
This commit is contained in:
jaggededgedjustice 2022-12-25 20:11:34 +00:00 committed by GitHub
parent 083e4ac4df
commit b8a755a396
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 1 deletions

View file

@ -8,6 +8,7 @@
// spell-checker:ignore (chrono) Datelike Timelike ; (format) DATEFILE MMDDhhmm ; (vars) datetime datetimes // spell-checker:ignore (chrono) Datelike Timelike ; (format) DATEFILE MMDDhhmm ; (vars) datetime datetimes
use chrono::format::{Item, StrftimeItems};
use chrono::{DateTime, FixedOffset, Local, Offset, Utc}; use chrono::{DateTime, FixedOffset, Local, Offset, Utc};
#[cfg(windows)] #[cfg(windows)]
use chrono::{Datelike, Timelike}; use chrono::{Datelike, Timelike};
@ -243,7 +244,19 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Ok(date) => { Ok(date) => {
// GNU `date` uses `%N` for nano seconds, however crate::chrono uses `%f` // GNU `date` uses `%N` for nano seconds, however crate::chrono uses `%f`
let format_string = &format_string.replace("%N", "%f"); let format_string = &format_string.replace("%N", "%f");
let formatted = date.format(format_string).to_string().replace("%f", "%N"); // Hack to work around panic in chrono,
// TODO - remove when a fix for https://github.com/chronotope/chrono/issues/623 is released
let format_items = StrftimeItems::new(format_string);
if format_items.clone().any(|i| i == Item::Error) {
return Err(USimpleError::new(
1,
format!("invalid format {}", format_string.replace("%f", "%N")),
));
}
let formatted = date
.format_with_items(format_items)
.to_string()
.replace("%f", "%N");
println!("{}", formatted); println!("{}", formatted);
} }
Err((input, _err)) => show_error!("invalid date {}", input.quote()), Err((input, _err)) => show_error!("invalid date {}", input.quote()),

View file

@ -225,3 +225,10 @@ fn test_date_set_valid_4() {
assert!(result.stderr_str().starts_with("date: invalid date ")); assert!(result.stderr_str().starts_with("date: invalid date "));
} }
} }
#[test]
fn test_invalid_format_string() {
let result = new_ucmd!().arg("+%!").fails();
result.no_stdout();
assert!(result.stderr_str().starts_with("date: invalid format "));
}