tiempo-rs/src/commands/month.rs

61 lines
1.7 KiB
Rust
Raw Normal View History

2021-07-07 13:52:40 -05:00
use std::convert::TryFrom;
use std::io::Write;
use clap::ArgMatches;
use chrono::{DateTime, Utc, Local, Datelike};
use regex::Regex;
use crate::error::{Result, Error};
use crate::database::Database;
use crate::formatters::Formatter;
use crate::config::Config;
use crate::regex::parse_regex;
use crate::timeparse::parse_time;
use super::{Command, display::{Sheet, entries_for_display}};
/// Given a local datetime, returns the time of the previous monday's start
fn beginning_of_month(now: DateTime<Local>) -> DateTime<Utc> {
now.date().with_day(1).unwrap().and_hms(0, 0, 0).with_timezone(&Utc)
}
#[derive(Default)]
pub struct Args {
ids: bool,
end: Option<DateTime<Utc>>,
format: Formatter,
grep: Option<Regex>,
sheet: Option<Sheet>,
}
impl<'a> TryFrom<&'a ArgMatches<'a>> for Args {
type Error = Error;
fn try_from(matches: &'a ArgMatches) -> Result<Args> {
Ok(Args {
ids: matches.is_present("ids"),
end: matches.value_of("end").map(|s| parse_time(s)).transpose()?,
format: matches.value_of("format").unwrap().parse()?,
grep: matches.value_of("grep").map(parse_regex).transpose()?,
sheet: matches.value_of("sheet").map(|s| s.parse()).transpose()?,
})
}
}
pub struct MonthCommand { }
impl<'a> Command<'a> for MonthCommand {
type Args = Args;
fn handle<D, O, E>(args: Self::Args, db: &mut D, out: &mut O, err: &mut E, _config: &Config) -> Result<()>
where
D: Database,
O: Write,
E: Write,
{
let start = beginning_of_month(Local::now());
entries_for_display(Some(start), args.end, args.sheet, db, out, err, args.format, args.ids, args.grep)
}
}