Debian Codegraph @

src/cli/time.rs

raw
1 use std::fmt::Display;
2 use std::fmt::Formatter;
3 use std::time::Duration;
4 use std::time::SystemTime;
5
6 use anyhow::Context;
7
8 use chrono::offset::Utc;
9 use chrono::DateTime;
10 use chrono::TimeZone;
11
12 use sequoia_openpgp as openpgp;
13 use openpgp::types::Timestamp;
14
15 /// The seconds in a day
16 pub const SECONDS_IN_DAY : u64 = 24 * 60 * 60;
17 /// The seconds in a year
18 pub const SECONDS_IN_YEAR : u64 =
19 // Average number of days in a year.
20 (365.2422222 * SECONDS_IN_DAY as f64) as u64;
21
22 use crate::Result;
23
24 /// A signed offset (in seconds).
25 #[derive(Debug, Clone, Eq, PartialEq)]
26 pub struct Offset {
27 /// Whether the offset is negative (strictly less than and not equal to 0).
28 negative: bool,
29 /// The number of seconds.
30 seconds: u64,
31 }
32
33 /// A thin wrapper around `openpgp::types::Timestamp`.
34 ///
35 /// Recall: an OpenPGP timestamp has a whole second resolution, and
36 /// uses a 32-bit quantity to represent the number of seconds since
37 /// the UNIX epoch.
38 #[derive(Debug, Clone, Eq, PartialEq)]
39 pub enum Time {
40 Timestamp(Timestamp),
41 Offset(Offset),
42 }
43
44 impl std::str::FromStr for Time {
45 type Err = anyhow::Error;
46
47 fn from_str(s: &str) -> anyhow::Result<Time> {
48 let s = s.trim();
49
50 if Time::is_offset(s) {
51 Ok(Self::parse_offset(s)?)
52 } else {
53 let time =
54 Time::parse_iso8601(s, chrono::NaiveTime::from_hms_opt(0, 0, 0)
55 .unwrap())?;
56 Ok(Time::try_from(SystemTime::from(time))?)
57 }
58 }
59 }
60
61 impl TryFrom<SystemTime> for Time {
62 type Error = anyhow::Error;
63
64 fn try_from(time: SystemTime) -> Result<Self> {
65 Ok(Self::Timestamp(Timestamp::try_from(time)?))
66 }
67 }
68
69 impl TryFrom<DateTime<Utc>> for Time {
70 type Error = anyhow::Error;
71
72 fn try_from(time: DateTime<Utc>) -> Result<Self> {
73 Self::try_from(SystemTime::try_from(time)?)
74 }
75 }
76
77 #[allow(dead_code)]
78 impl Time {
79 /// Returns the current time.
80 #[allow(dead_code)]
81 pub fn now() -> Self {
82 Time::Timestamp(Timestamp::now())
83 }
84
85 /// Returns a relative time in the future.
86 pub fn from_duration(duration: Duration) -> Self {
87 Time::Offset(Offset {
88 negative: false,
89 seconds: duration.as_secs(),
90 })
91 }
92
93 /// Parses the given string depicting a ISO 8601 timestamp.
94 fn parse_iso8601(
95 s: &str,
96 pad_date_with: chrono::NaiveTime,
97 ) -> anyhow::Result<DateTime<Utc>> {
98 // If you modify this function this function, synchronize the
99 // changes with the copy in sqv.rs!
100 for f in &[
101 "%Y-%m-%dT%H:%M:%S%#z",
102 "%Y-%m-%dT%H:%M:%S",
103 "%Y-%m-%dT%H:%M%#z",
104 "%Y-%m-%dT%H:%M",
105 "%Y-%m-%dT%H%#z",
106 "%Y-%m-%dT%H",
107 "%Y%m%dT%H%M%S%#z",
108 "%Y%m%dT%H%M%S",
109 "%Y%m%dT%H%M%#z",
110 "%Y%m%dT%H%M",
111 "%Y%m%dT%H%#z",
112 "%Y%m%dT%H",
113 ] {
114 if f.ends_with("%#z") {
115 if let Ok(d) = DateTime::parse_from_str(s, *f) {
116 return Ok(d.into());
117 }
118 } else if let Ok(d) = chrono::NaiveDateTime::parse_from_str(s, *f) {
119 return Ok(Utc.from_utc_datetime(&d));
120 }
121 }
122 for f in &["%Y-%m-%d", "%Y-%m", "%Y-%j", "%Y%m%d", "%Y%m", "%Y%j", "%Y"]
123 {
124 if let Ok(d) = chrono::NaiveDate::parse_from_str(s, *f) {
125 return Ok(Utc.from_utc_datetime(&d.and_time(pad_date_with)));
126 }
127 }
128 Err(anyhow::anyhow!("Malformed timestamp: {}.\n\
129 Try: YYYY-MM-DD[Thh:mm[:ss][[+|-]hh[:mm]]] \
130 or [+|-|]N[ymdhs]", s))
131 }
132
133 const OFFSET_SUFFIXES: &'static [char] = &['y', 'm', 'w', 'd', 's'];
134
135 /// Whether the string appears to be an offset (e.g., 1y).
136 fn is_offset(s: &str) -> bool {
137 s.trim_end().ends_with(Self::OFFSET_SUFFIXES)
138 }
139
140 /// Parse a string as an offset.
141 ///
142 /// `offset` must be at least two chars long, and consist of an
143 /// optional + or -, digits, and a trailing factor identifier (one
144 /// of `"y"`, `"m"`, `"w"`, `"d"`, `"s"` for year, month, week,
145 /// day, and second, respectively).
146 pub fn parse_offset(offset: &str) -> Result<Self> {
147 if offset.len() < 2 {
148 return Err(anyhow::anyhow!(
149 "Value must contain at least one digit and one factor."
150 ));
151 }
152
153 let (negative, seconds) = match offset.strip_suffix(Self::OFFSET_SUFFIXES) {
154 Some(digits) => {
155 let (negative, count) = match digits.parse::<i64>() {
156 Ok(count) => {
157 (count.is_negative(), count.unsigned_abs())
158 }
159 Err(err) => return Err(err).context(
160 format!("Value '{}' is out of range", digits)
161 ),
162 };
163
164 let factor = match offset.chars().last() {
165 Some('y') => SECONDS_IN_YEAR,
166 Some('m') => SECONDS_IN_YEAR / 12,
167 Some('w') => 7 * SECONDS_IN_DAY,
168 Some('d') => SECONDS_IN_DAY,
169 Some('s') => 1,
170 _ => unreachable!(
171 "Value without 'y', 'm', 'w', 'd' or 's' \
172 suffix impossible since checked for it."
173 ),
174 };
175
176 (negative,
177 count.checked_mul(factor).ok_or_else(|| {
178 anyhow::anyhow!("{} is too large (overflow)", count)
179 })?)
180 }
181 None => {
182 return Err(anyhow::anyhow!(
183 if let Some(suffix) = offset.chars().last() {
184 format!(
185 "Invalid suffix '{}' in '{}' \
186 (try <digits><{}>, e.g. '1y')",
187 suffix,
188 offset,
189 Self::OFFSET_SUFFIXES.iter().map(|c| c.to_string())
190 .collect::<Vec<String>>()
191 .join("|"))
192 } else {
193 format!(
194 "Invalid value: {} \
195 (try <digits><{}>, e.g. '1y')",
196 offset,
197 Self::OFFSET_SUFFIXES.iter().map(|c| c.to_string())
198 .collect::<Vec<String>>()
199 .join("|"))
200 }
201 ))
202 }
203 };
204
205 Ok(Time::Offset(Offset {
206 negative,
207 seconds,
208 }))
209 }
210
211 /// Returns the time as an absolute time.
212 pub fn to_system_time(&self, now: SystemTime) -> Result<SystemTime> {
213 match self {
214 Time::Timestamp(ts) => Ok(ts.clone().try_into()?),
215 Time::Offset(offset) => {
216 if offset.negative {
217 Ok(now - Duration::new(offset.seconds, 0))
218 } else {
219 Ok(now + Duration::new(offset.seconds, 0))
220 }
221 }
222 }
223 }
224
225 /// Returns the time since the specified time.
226 ///
227 /// Returns an error if `t` is in the future relative to the time.
228 pub fn duration_since(&self, t: SystemTime) -> Result<Duration> {
229 Ok(self.to_system_time(t)?.duration_since(t)?)
230 }
231
232 }
233
234 impl Display for Time {
235 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
236 match self {
237 Time::Timestamp(time) => write!(f, "{}", time),
238 Time::Offset(offset) => {
239 if offset.negative {
240 write!(f, "-")?;
241 }
242
243 let seconds = offset.seconds;
244 if seconds % SECONDS_IN_YEAR == 0 {
245 write!(f, "{}y", seconds / SECONDS_IN_YEAR)
246 } else if seconds % (SECONDS_IN_YEAR / 12) == 0 {
247 write!(f, "{}m", seconds / (SECONDS_IN_YEAR / 12))
248 } else if seconds % (SECONDS_IN_DAY * 7) == 0 {
249 write!(f, "{}w", seconds / (SECONDS_IN_DAY * 7))
250 } else if seconds % SECONDS_IN_DAY == 0 {
251 write!(f, "{}d", seconds / SECONDS_IN_DAY)
252 } else {
253 write!(f, "{}s", seconds)
254 }
255 },
256 }
257 }
258 }
259
260 #[cfg(test)]
261 mod test {
262 use super::*;
263
264 #[test]
265 fn test_parse_iso8601() -> anyhow::Result<()> {
266 let z = chrono::NaiveTime::from_hms_opt(0, 0, 0).unwrap();
267 Time::parse_iso8601("2017-03-04T13:25:35Z", z)?;
268 Time::parse_iso8601("2017-03-04T13:25:35+08:30", z)?;
269 Time::parse_iso8601("2017-03-04T13:25:35", z)?;
270 Time::parse_iso8601("2017-03-04T13:25Z", z)?;
271 Time::parse_iso8601("2017-03-04T13:25", z)?;
272 // CliTime::parse_iso8601("2017-03-04T13Z", z)?; // XXX: chrono doesn't like
273 // CliTime::parse_iso8601("2017-03-04T13", z)?; // ditto
274 Time::parse_iso8601("2017-03-04", z)?;
275 // CliTime::parse_iso8601("2017-03", z)?; // ditto
276 Time::parse_iso8601("2017-031", z)?;
277 Time::parse_iso8601("20170304T132535Z", z)?;
278 Time::parse_iso8601("20170304T132535+0830", z)?;
279 Time::parse_iso8601("20170304T132535", z)?;
280 Time::parse_iso8601("20170304T1325Z", z)?;
281 Time::parse_iso8601("20170304T1325", z)?;
282 // CliTime::parse_iso8601("20170304T13Z", z)?; // ditto
283 // CliTime::parse_iso8601("20170304T13", z)?; // ditto
284 Time::parse_iso8601("20170304", z)?;
285 // CliTime::parse_iso8601("201703", z)?; // ditto
286 Time::parse_iso8601("2017031", z)?;
287 // CliTime::parse_iso8601("2017", z)?; // ditto
288 Ok(())
289 }
290
291 #[test]
292 fn test_parse_offset() {
293 assert_eq!(
294 Time::parse_offset("1y").unwrap(),
295 Time::from_duration(Duration::new(SECONDS_IN_YEAR, 0)),
296 );
297 assert_eq!(
298 Time::parse_offset("+1y").unwrap(),
299 Time::from_duration(Duration::new(SECONDS_IN_YEAR, 0)),
300 );
301 assert_eq!(
302 Time::parse_offset("-1y").unwrap(),
303 Time::Offset(Offset { negative: true, seconds: SECONDS_IN_YEAR }),
304 );
305 assert!(Time::parse_offset("f").is_err());
306 assert!(Time::parse_offset("foo").is_err());
307 assert!(Time::parse_offset("1o").is_err());
308 }
309 }