Skip to content

Commit

Permalink
show future commit dates without panicking (#1389)
Browse files Browse the repository at this point in the history
  • Loading branch information
MalteT committed Aug 15, 2024
1 parent 81b4831 commit 61ab298
Showing 1 changed file with 12 additions and 18 deletions.
30 changes: 12 additions & 18 deletions src/info/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::cli::NumberSeparator;
use gix::date::Time;
use num_format::ToFormattedString;
use owo_colors::{DynColors, Style};
use std::time::{Duration, SystemTime};
use std::time::SystemTime;
use time::{format_description::well_known::Rfc3339, OffsetDateTime};
use time_humanize::HumanTime;

Expand All @@ -26,17 +26,13 @@ where
fn to_human_time(time: Time) -> String {
let since_epoch_duration = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();

let ts = Duration::from_secs(match time.seconds.try_into() {
Ok(s) => s,
Err(_) => return "<before UNIX epoch>".into(),
});
let duration = since_epoch_duration.checked_sub(ts).expect(
"Achievement unlocked: time travel! \
Check your system clock and commit dates.",
);
let ht = HumanTime::from(-(duration.as_secs() as i64));
.expect("System time is before the Unix epoch");
// Calculate the distance from the current time. This handles
// future dates gracefully and will simply return something like `in 5 minutes`
let delta_in_seconds = time
.seconds
.saturating_sub(since_epoch_duration.as_secs() as i64);
let ht = HumanTime::from(delta_in_seconds);
ht.to_string()
}

Expand Down Expand Up @@ -107,24 +103,22 @@ mod tests {
}

#[test]
#[should_panic(
expected = "Achievement unlocked: time travel! Check your system clock and commit dates."
)]
fn should_panic_when_display_human_time_and_commit_date_in_the_future() {
fn handle_display_human_time_and_commit_date_in_the_future() {
let day = Duration::from_secs(60 * 60 * 24);
let current_time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
let tomorrow = current_time + day;
let time = Time::new(tomorrow.as_secs() as gix::date::SecondsSinceUnixEpoch, 0);
format_time(time, false);
let result = format_time(time, false);
assert_eq!(result, "in a day");
}

#[test]
fn display_time_before_epoch() {
let time = Time::new(gix::date::SecondsSinceUnixEpoch::MIN, 0);
let result = to_human_time(time);
assert_eq!(result, "<before UNIX epoch>");
assert!(result.ends_with(" years ago"));
}

#[rstest]
Expand Down

0 comments on commit 61ab298

Please sign in to comment.