Skip to main content

git_editor/utils/
dates.rs

1//! Parsing of user-supplied dates.
2//!
3//! Accepted forms:
4//! * `YYYY-MM-DD HH:MM:SS` — interpreted as UTC (offset `+0000`)
5//! * `YYYY-MM-DD HH:MM:SS +HH:MM` / `+HHMM` / `Z` — explicit offset
6//! * RFC 3339, e.g. `2024-01-01T10:00:00+05:30`
7
8use crate::rewrite::engine::GitTime;
9use crate::utils::types::Result;
10use chrono::{DateTime, FixedOffset, NaiveDateTime};
11
12pub const DATE_FORMAT_HELP: &str =
13    "YYYY-MM-DD HH:MM:SS (UTC), optionally followed by an offset like +05:30, or RFC 3339";
14
15/// Parse a date into a git timestamp (seconds + offset).
16pub fn parse_git_time(input: &str) -> Result<GitTime> {
17    let input = input.trim();
18    if let Ok(naive) = NaiveDateTime::parse_from_str(input, "%Y-%m-%d %H:%M:%S") {
19        return Ok(GitTime::new(naive.and_utc().timestamp(), 0));
20    }
21    let with_offset = parse_with_offset(input)
22        .or_else(|| DateTime::parse_from_rfc3339(input).ok())
23        .ok_or_else(|| format!("Invalid date '{input}' (expected {DATE_FORMAT_HELP})"))?;
24    Ok(GitTime::new(
25        with_offset.timestamp(),
26        with_offset.offset().local_minus_utc() / 60,
27    ))
28}
29
30/// The instant as naive UTC, for display and range arithmetic.
31pub fn parse_utc(input: &str) -> Result<NaiveDateTime> {
32    let time = parse_git_time(input)?;
33    Ok(DateTime::from_timestamp(time.seconds, 0)
34        .ok_or("date out of range")?
35        .naive_utc())
36}
37
38/// Render a git timestamp as `YYYY-MM-DD HH:MM:SS +HHMM` in its own offset.
39pub fn format_git_time(time: GitTime) -> String {
40    FixedOffset::east_opt(time.offset_minutes * 60)
41        .and_then(|tz| DateTime::from_timestamp(time.seconds, 0).map(|t| t.with_timezone(&tz)))
42        .map_or_else(
43            || time.seconds.to_string(),
44            |t| t.format("%Y-%m-%d %H:%M:%S %z").to_string(),
45        )
46}
47
48/// RFC 3339 rendering in the timestamp's own offset, e.g. `2024-01-01T10:00:00+05:30`.
49pub fn to_rfc3339(time: GitTime) -> String {
50    FixedOffset::east_opt(time.offset_minutes * 60)
51        .and_then(|tz| DateTime::from_timestamp(time.seconds, 0).map(|t| t.with_timezone(&tz)))
52        .map_or_else(|| time.seconds.to_string(), |t| t.to_rfc3339())
53}
54
55fn parse_with_offset(input: &str) -> Option<DateTime<FixedOffset>> {
56    let normalized = input
57        .strip_suffix('Z')
58        .map(|s| format!("{} +00:00", s.trim_end()));
59    let input = normalized.as_deref().unwrap_or(input);
60    ["%Y-%m-%d %H:%M:%S %:z", "%Y-%m-%d %H:%M:%S %z"]
61        .iter()
62        .find_map(|fmt| DateTime::parse_from_str(input, fmt).ok())
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn plain_dates_are_utc() {
71        let t = parse_git_time("2024-01-01 00:00:00").unwrap();
72        assert_eq!(t, GitTime::new(1_704_067_200, 0));
73    }
74
75    #[test]
76    fn explicit_offsets_are_kept() {
77        let expected = GitTime::new(1_704_067_200 - 330 * 60, 330);
78        assert_eq!(
79            parse_git_time("2024-01-01 00:00:00 +05:30").unwrap(),
80            expected
81        );
82        assert_eq!(
83            parse_git_time("2024-01-01 00:00:00 +0530").unwrap(),
84            expected
85        );
86        assert_eq!(
87            parse_git_time("2024-01-01T00:00:00+05:30").unwrap(),
88            expected
89        );
90        assert_eq!(
91            parse_git_time("2024-01-01 00:00:00 -05:00").unwrap(),
92            GitTime::new(1_704_067_200 + 300 * 60, -300)
93        );
94        assert_eq!(
95            parse_git_time("2024-01-01 00:00:00Z").unwrap(),
96            GitTime::new(1_704_067_200, 0)
97        );
98    }
99
100    #[test]
101    fn invalid_dates_are_rejected() {
102        for bad in ["2023-13-45 25:61:61", "yesterday", "2024-01-01", ""] {
103            assert!(parse_git_time(bad).is_err(), "{bad}");
104        }
105    }
106
107    #[test]
108    fn format_round_trips() {
109        let t = parse_git_time("2024-01-01 10:00:00 +05:30").unwrap();
110        assert_eq!(format_git_time(t), "2024-01-01 10:00:00 +0530");
111        assert_eq!(parse_git_time(&format_git_time(t)).unwrap(), t);
112    }
113
114    #[test]
115    fn rfc3339_keeps_offset() {
116        let t = parse_git_time("2024-01-01 10:00:00 +05:30").unwrap();
117        assert_eq!(to_rfc3339(t), "2024-01-01T10:00:00+05:30");
118        assert_eq!(parse_git_time(&to_rfc3339(t)).unwrap(), t);
119    }
120
121    #[test]
122    fn utc_view_of_offset_date() {
123        let utc = parse_utc("2024-01-01 05:30:00 +05:30").unwrap();
124        assert_eq!(utc.to_string(), "2024-01-01 00:00:00");
125    }
126}