Skip to content

Commit

Permalink
date: refactor date printing into its own method
Browse files Browse the repository at this point in the history
  • Loading branch information
BenWiederhake committed Aug 11, 2024
1 parent e7d618f commit d3be43e
Showing 1 changed file with 28 additions and 23 deletions.
51 changes: 28 additions & 23 deletions src/uu/date/src/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,33 @@ impl DateSource {
}
}

fn print_date(format_string: &str, date: DateTime<FixedOffset>) -> UResult<()> {
// GNU `date` uses `%N` for nano seconds, however crate::chrono uses `%f`
let format_string = &format_string.replace("%N", "%f");
// Refuse to pass this string to chrono as it is crashing in this crate
if format_string.contains("%#z") {
return Err(USimpleError::new(
1,
format!("invalid format {}", format_string.replace("%f", "%N")),
));
}
// Hack to work around panic in chrono,
// TODO - remove when a fix for https:/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}");
Ok(())
}

#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?;
Expand Down Expand Up @@ -300,29 +327,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
for date in dates {
match date {
Ok(date) => {
// GNU `date` uses `%N` for nano seconds, however crate::chrono uses `%f`
let format_string = &format_string.replace("%N", "%f");
// Refuse to pass this string to chrono as it is crashing in this crate
if format_string.contains("%#z") {
return Err(USimpleError::new(
1,
format!("invalid format {}", format_string.replace("%f", "%N")),
));
}
// Hack to work around panic in chrono,
// TODO - remove when a fix for https:/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}");
print_date(format_string, date)?;
}
Err((input, _err)) => show!(USimpleError::new(
1,
Expand Down

0 comments on commit d3be43e

Please sign in to comment.