Skip to content

Commit 61ab298

Browse files
authored
show future commit dates without panicking (#1389)
1 parent 81b4831 commit 61ab298

File tree

1 file changed

+12
-18
lines changed

1 file changed

+12
-18
lines changed

src/info/utils/mod.rs

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::cli::NumberSeparator;
22
use gix::date::Time;
33
use num_format::ToFormattedString;
44
use owo_colors::{DynColors, Style};
5-
use std::time::{Duration, SystemTime};
5+
use std::time::SystemTime;
66
use time::{format_description::well_known::Rfc3339, OffsetDateTime};
77
use time_humanize::HumanTime;
88

@@ -26,17 +26,13 @@ where
2626
fn to_human_time(time: Time) -> String {
2727
let since_epoch_duration = SystemTime::now()
2828
.duration_since(SystemTime::UNIX_EPOCH)
29-
.unwrap();
30-
31-
let ts = Duration::from_secs(match time.seconds.try_into() {
32-
Ok(s) => s,
33-
Err(_) => return "<before UNIX epoch>".into(),
34-
});
35-
let duration = since_epoch_duration.checked_sub(ts).expect(
36-
"Achievement unlocked: time travel! \
37-
Check your system clock and commit dates.",
38-
);
39-
let ht = HumanTime::from(-(duration.as_secs() as i64));
29+
.expect("System time is before the Unix epoch");
30+
// Calculate the distance from the current time. This handles
31+
// future dates gracefully and will simply return something like `in 5 minutes`
32+
let delta_in_seconds = time
33+
.seconds
34+
.saturating_sub(since_epoch_duration.as_secs() as i64);
35+
let ht = HumanTime::from(delta_in_seconds);
4036
ht.to_string()
4137
}
4238

@@ -107,24 +103,22 @@ mod tests {
107103
}
108104

109105
#[test]
110-
#[should_panic(
111-
expected = "Achievement unlocked: time travel! Check your system clock and commit dates."
112-
)]
113-
fn should_panic_when_display_human_time_and_commit_date_in_the_future() {
106+
fn handle_display_human_time_and_commit_date_in_the_future() {
114107
let day = Duration::from_secs(60 * 60 * 24);
115108
let current_time = SystemTime::now()
116109
.duration_since(SystemTime::UNIX_EPOCH)
117110
.unwrap();
118111
let tomorrow = current_time + day;
119112
let time = Time::new(tomorrow.as_secs() as gix::date::SecondsSinceUnixEpoch, 0);
120-
format_time(time, false);
113+
let result = format_time(time, false);
114+
assert_eq!(result, "in a day");
121115
}
122116

123117
#[test]
124118
fn display_time_before_epoch() {
125119
let time = Time::new(gix::date::SecondsSinceUnixEpoch::MIN, 0);
126120
let result = to_human_time(time);
127-
assert_eq!(result, "<before UNIX epoch>");
121+
assert!(result.ends_with(" years ago"));
128122
}
129123

130124
#[rstest]

0 commit comments

Comments
 (0)