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