tiempo-rs/src/commands/display.rs

180 lines
5.1 KiB
Rust

use std::convert::TryFrom;
use std::io::Write;
use std::str::FromStr;
use clap::ArgMatches;
use chrono::{DateTime, Utc, Local, TimeZone, LocalResult};
use terminal_size::{Width, terminal_size};
use ansi_term::Color::Yellow;
use crate::error;
use crate::database::{Database, DBVersion};
use crate::formatters::Formatter;
use crate::config::Config;
use crate::models::Entry;
use super::Command;
fn local_to_utc(t: DateTime<Utc>) -> error::Result<DateTime<Utc>> {
let local_time = match Local.from_local_datetime(&t.naive_utc()) {
LocalResult::None => return Err(error::Error::NoneLocalTime(t.naive_utc())),
LocalResult::Single(t) => t,
LocalResult::Ambiguous(t1, t2) => return Err(error::Error::AmbiguousLocalTime {
orig: t.naive_utc(),
t1, t2,
}),
};
Ok(Utc.from_utc_datetime(&local_time.naive_utc()))
}
fn local_to_utc_vec(entries: Vec<Entry>) -> error::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()
}
fn term_width() -> usize {
if let Some((Width(w), _)) = terminal_size() {
w as usize
} else {
80
}
}
enum Sheet {
All,
Full,
Sheet(String),
}
impl FromStr for Sheet {
type Err = error::Error;
fn from_str(name: &str) -> error::Result<Sheet> {
Ok(match name {
"all" => Sheet::All,
"full" => Sheet::Full,
name => Sheet::Sheet(name.into()),
})
}
}
#[derive(Default)]
pub struct Args {
ids: bool,
start: Option<DateTime<Utc>>,
end: Option<DateTime<Utc>>,
format: Formatter,
grep: Option<String>,
sheet: Option<Sheet>,
}
impl<'a> TryFrom<&'a ArgMatches<'a>> for Args {
type Error = error::Error;
fn try_from(matches: &'a ArgMatches) -> error::Result<Args> {
Ok(Args {
ids: matches.is_present("ids"),
start: matches.value_of("at").map(|s| s.parse()).transpose()?,
end: matches.value_of("at").map(|s| s.parse()).transpose()?,
format: matches.value_of("format").unwrap().parse()?,
grep: matches.value_of("grep").map(|s| s.into()),
sheet: matches.value_of("sheet").map(|s| s.parse()).transpose()?,
})
}
}
pub struct DisplayCommand { }
impl<'a> Command<'a> for DisplayCommand {
type Args = Args;
fn handle<D, O, E>(args: Self::Args, db: &mut D, out: &mut O, err: &mut E, config: &Config) -> error::Result<()>
where
D: Database,
O: Write,
E: Write,
{
let entries = match args.sheet {
Some(Sheet::All) => db.entries_all_visible()?,
Some(Sheet::Full) => db.entries_full()?,
Some(Sheet::Sheet(name)) => db.entries_by_sheet(&name)?,
None => {
let current_sheet = db.current_sheet()?.unwrap_or("default".into());
db.entries_by_sheet(&current_sheet)?
}
};
let entries = 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
writeln!(
err,
"{} You are using the old timetrap format, it is advised that \
you update your database using t migrate",
Yellow.bold().paint("[WARNING]"),
)?;
local_to_utc_vec(entries)?
} else {
entries
};
args.format.print_formatted(
entries,
out,
Utc::now(),
args.ids,
term_width(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::database::SqliteDatabase;
use crate::test_utils::PrettyString;
#[test]
fn display_as_local_time_if_previous_version() {
let args = Default::default();
let mut db = SqliteDatabase::from_path("assets/test_old_db.db").unwrap();
let mut out = Vec::new();
let mut err = Vec::new();
let config = Default::default();
DisplayCommand::handle(args, &mut db, &mut out, &mut err, &config).unwrap();
assert_eq!(PrettyString(&String::from_utf8_lossy(&out)), PrettyString("Timesheet: default
Day Start End Duration Notes
Tue Jun 29, 2021 06:26:49 - 07:26:52 1:00:03 lets do some rust
1:00:03
-------------------------------------------------------------------
Total 1:00:03
"));
assert_eq!(
String::from_utf8_lossy(&err),
format!("{} You are using the old timetrap format, it is advised that you update your database using t migrate\n", Yellow.bold().paint("[WARNING]")),
);
}
#[test]
#[ignore]
fn correctly_use_utc_if_new_version() {
assert!(false, "start with a newly created database");
assert!(false, "correctly display times in local timezone");
}
}