tiempo-rs/src/old.rs

60 lines
1.8 KiB
Rust
Raw Normal View History

use std::io::Write;
use chrono::{DateTime, Utc, Local, LocalResult, TimeZone};
use ansi_term::Color::Yellow;
use crate::error::{Error, Result};
use crate::models::Entry;
use crate::database::{Database, DBVersion};
fn local_to_utc(t: DateTime<Utc>) -> Result<DateTime<Utc>> {
let local_time = match Local.from_local_datetime(&t.naive_utc()) {
LocalResult::None => return Err(Error::NoneLocalTime(t.naive_utc().to_string())),
LocalResult::Single(t) => t,
LocalResult::Ambiguous(t1, t2) => return Err(Error::AmbiguousLocalTime {
orig: t.naive_utc().to_string(),
t1: t1.naive_local(),
t2: t2.naive_local(),
}),
};
Ok(Utc.from_utc_datetime(&local_time.naive_utc()))
}
fn local_to_utc_vec(entries: Vec<Entry>) -> Result<Vec<Entry>> {
entries
.into_iter()
.map(|e| {
Ok(Entry {
start: local_to_utc(e.start)?,
end: e.end.map(|t| local_to_utc(t)).transpose()?,
..e
})
})
.collect()
}
pub fn entries_or_warning<D: Database>(entries: Vec<Entry>, db: &D) -> Result<(Vec<Entry>, bool)> {
if let DBVersion::Timetrap = db.version()? {
// this indicates that times in the database are specified in the
// local time and need to be converted to utc before displaying
Ok((local_to_utc_vec(entries)?, true))
} else {
Ok((entries, false))
}
}
pub fn warn_if_needed<E: Write>(err: &mut E, needs_warning: bool) -> Result<()> {
if needs_warning {
writeln!(
err,
"{} You are using the old timetrap format, it is advised that \
you update your database using t migrate",
Yellow.bold().paint("[WARNING]"),
)?;
}
Ok(())
}