summaryrefslogtreecommitdiffstats
path: root/bin/domain/imag-timetrack/src/track.rs
blob: d5188bc6791ff28f8ab0a0bdd9215268d8bdca1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use clap::ArgMatches;
use chrono::naive::NaiveDate;
use chrono::naive::NaiveDateTime;
use failure::Error;
use failure::Fallible as Result;
use failure::err_msg;

use libimagrt::runtime::Runtime;
use libimagtimetrack::tag::TimeTrackingTag;
use libimagtimetrack::store::TimeTrackStore;

const DATE_TIME_PARSE_FMT : &str    = "%Y-%m-%dT%H:%M:%S";
const DATE_PARSE_FMT : &str         = "%Y-%m-%d";

pub fn track(rt: &Runtime) -> Result<()> {
    let (_, cmd) = rt.cli().subcommand();
    let cmd = cmd.unwrap(); // checked in main()

    // Gets the appropriate time from the commandline or None on error (errors already logged, so
    // callee can directly return in case of error
    fn get_time(cmd: &ArgMatches, clap_name: &str) -> Result<Option<NaiveDateTime>> {
        match cmd.value_of(clap_name) {
            None        => bail!("Not specified in commandline: {}", clap_name),
            Some("now") => Ok(Some(::chrono::offset::Local::now().naive_local())),
            Some(els)   => match NaiveDateTime::parse_from_str(els, DATE_TIME_PARSE_FMT) {
                Ok(ndt) => Ok(Some(ndt)),
                Err(_)  => Ok(Some(NaiveDate::parse_from_str(els, DATE_PARSE_FMT)?.and_hms(0, 0, 0))),
            }
        }
    }

    let start = get_time(&cmd, "start-time")?.ok_or_else(|| err_msg("No start-time"))?;
    let stop  = get_time(&cmd, "end-time")?.ok_or_else(|| err_msg("No end-time"))?;

    cmd.values_of("tags")
        .unwrap() // enforced by clap
        .map(String::from)
        .map(TimeTrackingTag::from)
        .map(|ttt| {
            let entry = rt.store().create_timetracking(&start, &stop, &ttt)?;
            rt.report_touched(entry.get_location()).map_err(Error::from)
        })
        .collect::<Result<Vec<_>>>()
        .map(|_| ())
}