Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

show future commit dates without panicking #1389

Merged
merged 2 commits into from
Aug 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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