tiempo-rs/src/commands/list.rs

107 lines
2.8 KiB
Rust
Raw Normal View History

2021-07-14 12:37:45 -05:00
use std::convert::TryFrom;
use std::io::Write;
use clap::ArgMatches;
use chrono::{Utc, Duration};
use itertools::Itertools;
use crate::error::{Error, Result};
use crate::database::Database;
use crate::config::Config;
use super::Command;
#[derive(Default)]
pub struct Args {
all: bool,
}
impl<'a> TryFrom<&'a ArgMatches<'a>> for Args {
type Error = Error;
fn try_from(matches: &ArgMatches) -> Result<Args> {
Ok(Args {
all: matches.is_present("all"),
})
}
}
pub struct ListCommand {}
impl<'a> Command<'a> for ListCommand {
type Args = Args;
fn handle<D, O, E>(args: Args, db: &mut D, out: &mut O, _err: &mut E, _config: &Config) -> Result<()>
where
D: Database,
O: Write,
E: Write,
{
// no sheet, list sheets
let now = Utc::now();
let mut sheets = if args.all {
db.entries_all_visible(None, None)?
} else {
db.entries_full(None, None)?
};
sheets.sort_unstable_by_key(|e| e.sheet.clone());
let sheets: Vec<_> = sheets
.into_iter()
.group_by(|e| e.sheet.clone())
.into_iter()
.map(|(key, group)| {
(key, group.fold(Duration::seconds(0), |acc, e| {
acc + (e.end.unwrap_or(now) - e.start)
}))
})
.collect();
for sheet in sheets {
writeln!(out, "{} {}", sheet.0, sheet.1)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use chrono::{Utc, TimeZone};
use pretty_assertions::assert_eq;
use crate::database::{SqliteDatabase, Database};
use crate::test_utils::PrettyString;
use super::*;
#[test]
fn list_sheets() {
let args = Default::default();
let mut db = SqliteDatabase::from_memory().unwrap();
let mut out = Vec::new();
let mut err = Vec::new();
let config = Default::default();
db.init().unwrap();
db.entry_insert(Utc.ymd(2021, 1, 1).and_hms(0, 0, 0), None, None, "_archived".into()).unwrap();
db.entry_insert(Utc.ymd(2021, 1, 1).and_hms(0, 0, 0), None, None, "sheet1".into()).unwrap();
db.entry_insert(Utc.ymd(2021, 1, 1).and_hms(0, 0, 0), None, None, "sheet2".into()).unwrap();
db.entry_insert(Utc.ymd(2021, 1, 1).and_hms(0, 0, 0), None, None, "sheet3".into()).unwrap();
ListCommand::handle(args, &mut db, &mut out, &mut err, &config).unwrap();
assert_eq!(PrettyString(&String::from_utf8_lossy(&out)), PrettyString(" Timesheet Running Today Total Time
sheet1 0:00:00 0:00:00 10:13:55
*sheet2 0:00:00 0:00:00 0:00:00
sheet3 0:00:00 1:52:45 9:32:03
"));
}
#[test]
fn list_sheets_shows_last() {
assert!(false);
}
}