tiempo-rs/src/commands/month.rs

196 lines
6.9 KiB
Rust
Raw Normal View History

2021-07-07 13:52:40 -05:00
use std::convert::TryFrom;
2021-08-25 14:30:27 -05:00
use std::io::{BufRead, Write};
2021-07-10 13:20:42 -05:00
use std::str::FromStr;
2021-07-07 13:52:40 -05:00
use clap::ArgMatches;
2021-07-10 13:20:42 -05:00
use chrono::{DateTime, Utc, Local, Datelike, TimeZone};
2021-07-07 13:52:40 -05:00
use regex::Regex;
use crate::error::{Result, Error};
use crate::database::Database;
use crate::formatters::Formatter;
use crate::regex::parse_regex;
2021-08-25 14:30:27 -05:00
use crate::io::Streams;
2021-07-07 13:52:40 -05:00
2021-08-25 14:30:27 -05:00
use super::{Command, Facts, display::{Sheet, entries_for_display}};
2021-07-07 13:52:40 -05:00
2021-07-10 13:20:42 -05:00
/// Given a local datetime, returns the time when the month it belongs started
fn beginning_of_month(time: DateTime<Local>) -> DateTime<Utc> {
2023-02-13 18:17:47 -06:00
time.date_naive().with_day(1).unwrap().and_hms_opt(0, 0, 0).unwrap().and_local_timezone(Utc).unwrap()
2021-07-10 13:20:42 -05:00
}
/// Given a datetime compute the time where the previous_month started in UTC
fn beginning_of_previous_month(time: DateTime<Local>) -> DateTime<Utc> {
match time.month() {
1 => {
2023-02-13 18:17:47 -06:00
Local.with_ymd_and_hms(time.year()-1, 12, 1, 0, 0, 0).unwrap().with_timezone(&Utc)
2021-07-10 13:20:42 -05:00
}
2023-02-13 18:17:47 -06:00
n => Local.with_ymd_and_hms(time.year(), n-1, 1, 0, 0, 0).unwrap().with_timezone(&Utc)
2021-07-10 13:20:42 -05:00
}
}
#[derive(Default)]
2021-07-10 13:20:42 -05:00
enum MonthSpec {
Last,
#[default]
2021-07-10 13:20:42 -05:00
This,
Month(u32),
}
impl FromStr for MonthSpec {
type Err = Error;
fn from_str(s: &str) -> Result<MonthSpec> {
match s.trim().to_lowercase().as_str() {
2021-07-10 13:27:38 -05:00
"this" | "current" => Ok(MonthSpec::This),
2021-07-10 13:20:42 -05:00
"last" => Ok(MonthSpec::Last),
"jan" | "january" => Ok(MonthSpec::Month(1)),
"feb" | "february" => Ok(MonthSpec::Month(2)),
"mar" | "march" => Ok(MonthSpec::Month(3)),
"apr" | "april" => Ok(MonthSpec::Month(4)),
"may" => Ok(MonthSpec::Month(5)),
"jun" | "june" => Ok(MonthSpec::Month(6)),
"jul" | "july" => Ok(MonthSpec::Month(7)),
"aug" | "august" => Ok(MonthSpec::Month(8)),
"sep" | "september" => Ok(MonthSpec::Month(9)),
"oct" | "october" => Ok(MonthSpec::Month(10)),
"nov" | "november" => Ok(MonthSpec::Month(11)),
"dic" | "december" => Ok(MonthSpec::Month(12)),
_ => Err(Error::InvalidMonthSpec(s.into())),
}
}
2021-07-07 13:52:40 -05:00
}
#[derive(Default)]
pub struct Args {
ids: bool,
2021-07-10 13:20:42 -05:00
month: MonthSpec,
2021-08-19 20:50:34 -05:00
format: Option<Formatter>,
2021-07-07 13:52:40 -05:00
grep: Option<Regex>,
sheet: Option<Sheet>,
}
2023-02-13 18:17:47 -06:00
impl<'a> TryFrom<&'a ArgMatches> for Args {
2021-07-07 13:52:40 -05:00
type Error = Error;
fn try_from(matches: &'a ArgMatches) -> Result<Args> {
Ok(Args {
ids: matches.is_present("ids"),
2021-07-10 13:20:42 -05:00
month: matches.value_of("month").map(|s| s.parse()).transpose()?.unwrap_or(MonthSpec::This),
2021-08-19 20:50:34 -05:00
format: matches.value_of("format").map(|v| v.parse()).transpose()?,
2021-07-07 13:52:40 -05:00
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;
2021-08-25 14:30:27 -05:00
fn handle<D, I, O, E>(args: Self::Args, streams: &mut Streams<D, I, O, E>, facts: &Facts) -> Result<()>
2021-07-07 13:52:40 -05:00
where
D: Database,
2021-08-25 14:30:27 -05:00
I: BufRead,
2021-07-07 13:52:40 -05:00
O: Write,
E: Write,
{
2021-08-25 14:30:27 -05:00
let now = facts.now;
2021-07-10 13:20:42 -05:00
let (start, end) = match args.month {
MonthSpec::This => (beginning_of_month(now.with_timezone(&Local)), now),
2021-07-10 13:20:42 -05:00
MonthSpec::Last => {
(beginning_of_previous_month(now.with_timezone(&Local)), beginning_of_month(now.with_timezone(&Local)))
2021-07-10 13:20:42 -05:00
},
MonthSpec::Month(month) => {
if month < now.month() {
// the specified month is in the current year
(
2023-02-13 18:17:47 -06:00
Local.with_ymd_and_hms(now.year(), month, 1, 0, 0, 0).unwrap().with_timezone(&Utc),
2021-07-10 13:20:42 -05:00
if month < 12 {
2023-02-13 18:17:47 -06:00
Local.with_ymd_and_hms(now.year(), month+1, 1, 0, 0, 0).unwrap().with_timezone(&Utc)
2021-07-10 13:20:42 -05:00
} else {
2023-02-13 18:17:47 -06:00
Local.with_ymd_and_hms(now.year()+1, 1, 1, 0, 0, 0).unwrap().with_timezone(&Utc)
2021-07-10 13:20:42 -05:00
}
)
} else {
// use previous year
(
2023-02-13 18:17:47 -06:00
Local.with_ymd_and_hms(now.year() - 1, month, 1, 0, 0, 0).unwrap().with_timezone(&Utc),
2021-07-10 13:20:42 -05:00
if month < 12 {
2023-02-13 18:17:47 -06:00
Local.with_ymd_and_hms(now.year() - 1, month + 1, 1, 0, 0, 0).unwrap().with_timezone(&Utc)
2021-07-10 13:20:42 -05:00
} else {
2023-02-13 18:17:47 -06:00
Local.with_ymd_and_hms(now.year(), 1, 1, 0, 0, 0).unwrap().with_timezone(&Utc)
2021-07-10 13:20:42 -05:00
}
)
}
},
};
2021-07-07 13:52:40 -05:00
2021-08-25 14:30:27 -05:00
entries_for_display(
Some(start),
Some(end),
args.sheet,
streams,
args.format.unwrap_or_else(|| facts.config.commands.month.default_formatter.as_ref().unwrap_or(&facts.config.default_formatter).clone()),
2021-08-25 14:30:27 -05:00
args.ids,
args.grep,
facts
)
2021-08-19 20:50:34 -05:00
}
}
#[cfg(test)]
mod tests {
use crate::config::{Config, CommandsSettings, BaseCommandSettings};
2021-08-19 20:50:34 -05:00
use super::*;
#[test]
fn respect_default_formatter() {
std::env::set_var("TZ", "CST+6");
let args = Default::default();
2021-08-25 14:30:27 -05:00
let mut streams = Streams::fake(b"");
2023-02-13 18:17:47 -06:00
let now = Utc.with_ymd_and_hms(2021, 6, 30, 11, 0, 0).unwrap();
2021-08-25 14:30:27 -05:00
let facts = Facts::new().with_config(Config {
2021-08-19 20:50:34 -05:00
default_formatter: Formatter::Ids,
..Default::default()
2021-08-25 14:30:27 -05:00
}).with_now(now);
2021-08-19 20:50:34 -05:00
2023-02-13 18:17:47 -06:00
streams.db.entry_insert(Utc.with_ymd_and_hms(2021, 6, 30, 10, 0, 0).unwrap(), None, Some("hola".into()), "default").unwrap();
streams.db.entry_insert(Utc.with_ymd_and_hms(2021, 6, 30, 10, 10, 0).unwrap(), None, Some("hola".into()), "default").unwrap();
2021-08-19 20:50:34 -05:00
2021-08-25 14:30:27 -05:00
MonthCommand::handle(args, &mut streams, &facts).unwrap();
2021-08-19 20:50:34 -05:00
2021-08-25 14:30:27 -05:00
assert_eq!(&String::from_utf8_lossy(&streams.out), "1 2\n");
assert_eq!(String::from_utf8_lossy(&streams.err), "");
2021-07-07 13:52:40 -05:00
}
#[test]
fn respect_command_default_formatter() {
std::env::set_var("TZ", "CST+6");
let args = Default::default();
let mut streams = Streams::fake(b"");
2023-02-13 18:17:47 -06:00
let now = Utc.with_ymd_and_hms(2021, 6, 30, 11, 0, 0).unwrap();
let facts = Facts::new().with_config(Config {
commands: CommandsSettings {
month: BaseCommandSettings {
default_formatter: Some(Formatter::Ids),
},
..Default::default()
},
..Default::default()
}).with_now(now);
2023-02-13 18:17:47 -06:00
streams.db.entry_insert(Utc.with_ymd_and_hms(2021, 6, 30, 10, 0, 0).unwrap(), None, Some("hola".into()), "default").unwrap();
streams.db.entry_insert(Utc.with_ymd_and_hms(2021, 6, 30, 10, 10, 0).unwrap(), None, Some("hola".into()), "default").unwrap();
MonthCommand::handle(args, &mut streams, &facts).unwrap();
assert_eq!(&String::from_utf8_lossy(&streams.out), "1 2\n");
assert_eq!(String::from_utf8_lossy(&streams.err), "");
}
2021-07-07 13:52:40 -05:00
}