summaryrefslogtreecommitdiffstats
path: root/bin/domain/imag-timetrack/src/shell.rs
blob: 30693438705b520b0e86fb05cb5467131660da57 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2019 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 std::env;
use std::process::Command;

use filters::filter::Filter;
use failure::Fallible as Result;
use failure::err_msg;
use failure::Error;
use resiter::Filter as RFilter;
use resiter::AndThen;

use libimagrt::runtime::Runtime;
use libimagtimetrack::iter::filter::has_one_of_tags;
use libimagtimetrack::store::TimeTrackStore;
use libimagtimetrack::tag::TimeTrackingTag;
use libimagtimetrack::timetracking::TimeTracking;

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

    let start = ::chrono::offset::Local::now().naive_local();
    let tags = cmd.values_of("tags")
        .unwrap() // enforced by clap
        .map(String::from)
        .map(TimeTrackingTag::from)
        .collect::<Vec<_>>();

    let mut shellcmd = {
        let mkshell = |s: String| {
            let mut cmd = Command::new(s);
            cmd.stdin(::std::process::Stdio::inherit());
            cmd.stdout(::std::process::Stdio::inherit());
            cmd.stderr(::std::process::Stdio::inherit());
            cmd
        };

        if let Some(s) = cmd.value_of("shell") {
            Ok(mkshell(s.to_owned()))
        } else {
            env::var("SHELL")
                .map(mkshell)
                .map_err(|e| match e {
                    env::VarError::NotPresent => {
                        err_msg("No $SHELL variable in environment, cannot work!")
                    },
                    env::VarError::NotUnicode(_) => {
                        err_msg("SHELL variable is not unicode, cannot work!")
                    }
                })
        }
    }?;

    for tag in tags.iter() {
        let entry = rt.store().create_timetracking_at(&start, tag)?;
        rt.report_touched(entry.get_location())?;
    }

    if !shellcmd.status()?.success() {
        return Err(format_err!("Failed to execute {:?}", shellcmd))
    }
    let stop      = ::chrono::offset::Local::now().naive_local();
    let filter    = has_one_of_tags(&tags);

    rt.store()
        .get_timetrackings()?
        .filter_ok(|e| filter.filter(e))
        .and_then_ok(|mut elem| {
            let _ = elem.set_end_datetime(stop.clone())?;
            debug!("Setting end time worked: {:?}", elem);
            rt.report_touched(elem.get_location()).map_err(Error::from)
        })
        .collect::<Result<Vec<_>>>()
        .map(|_| ())
}