summaryrefslogtreecommitdiffstats
path: root/bin/domain/imag-timetrack/src/list.rs
blob: 5f91353b6b05ea10924173fe40a848543815d91a (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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//
// 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 chrono::NaiveDateTime;
use prettytable::Table;
use prettytable::Row;
use prettytable::Cell;
use kairos::parser::Parsed;
use kairos::parser::parse as kairos_parse;
use clap::ArgMatches;
use failure::Fallible as Result;
use failure::ResultExt;
use failure::Error;
use resiter::Filter;
use resiter::AndThen;
use resiter::Map;

use libimagstore::store::FileLockEntry;
use libimagtimetrack::timetracking::TimeTracking;
use libimagtimetrack::store::TimeTrackStore;

use libimagrt::runtime::Runtime;

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

    let gettime = |cmd: &ArgMatches, name| {
        match cmd.value_of(name).map(kairos_parse) {
            Some(Ok(Parsed::TimeType(tt))) => {
                let tt = tt
                    .calculate()
                    .context(format_err!("Failed to calculate date from '{}'", cmd.value_of(name).unwrap()))?;
                Ok(tt.get_moment().cloned())
            },
            Some(Ok(Parsed::Iterator(_))) => {
                Err(format_err!("Expected single point in time, got '{}', which yields a list of dates", cmd.value_of(name).unwrap()))
            },
            Some(Err(e)) => Err(e),
            None => Ok(None),
        }
    };

    let start = gettime(&cmd, "start-time")?;
    let end   = gettime(&cmd, "end-time")?;

    let list_not_ended = cmd.is_present("list-not-ended");
    let show_duration  = cmd.is_present("show-duration");

    list_impl(rt, start, end, list_not_ended, show_duration)
}

pub fn list_impl(rt: &Runtime,
                 start: Option<NaiveDateTime>,
                 end: Option<NaiveDateTime>,
                 list_not_ended: bool,
                 show_duration: bool)
    -> Result<()>
{
    use filters::failable::filter::FailableFilter;

    let start_time_filter = |timetracking: &FileLockEntry| -> Result<bool> {
        start.map(|s| match timetracking.get_start_datetime()? {
            Some(dt) => Ok(dt >= s),
            None     => {
                warn!("Funny things are happening: Timetracking has no start time");
                Ok(false)
            }
        })
        .unwrap_or(Ok(true))
    };

    let end_time_filter = |timetracking: &FileLockEntry| -> Result<bool> {
        end.map(|s| match timetracking.get_end_datetime()? {
            Some(dt) => Ok(dt <= s),
            None     => Ok(list_not_ended),
        })
        .unwrap_or(Ok(true))
    };

    let filter = start_time_filter.and(end_time_filter);

    let mut table = Table::new();
    let title_row = if !show_duration {
        Row::new(["Tag", "Start", "End"].iter().map(|s| Cell::new(s)).collect())
    } else {
        Row::new(["Tag", "Start", "End", "Duration"].iter().map(|s| Cell::new(s)).collect())
    };
    table.set_titles(title_row);

    let table_empty = rt.store()
        .get_timetrackings()?
        .and_then_ok(|e| filter.filter(&e).map(|b| (b, e)))
        .filter_ok(|tpl| tpl.0)
        .map_ok(|tpl| tpl.1)
        .and_then_ok(|e| {
            debug!("Processing {:?}", e.get_location());

            let tag   = e.get_timetrack_tag()?;
            debug!(" -> tag = {:?}", tag);

            let start = e.get_start_datetime()?;
            debug!(" -> start = {:?}", start);

            let end   = e.get_end_datetime()?;
            debug!(" -> end = {:?}", end);

            let v = match (start, end) {
                (None, _)          => {
                    let mut v = vec![String::from(tag.as_str()), String::from(""), String::from("")];
                    if show_duration {
                        v.push(String::from(""));
                    }
                    v
                },
                (Some(s), None)    => {
                    let mut v = vec![
                        String::from(tag.as_str()),
                        format!("{}", s),
                        String::from(""),
                    ];

                    if show_duration {
                        v.push(String::from(""));
                    }

                    v
                },
                (Some(s), Some(e)) => {
                    let mut v = vec![
                        String::from(tag.as_str()),
                        format!("{}", s),
                        format!("{}", e),
                    ];

                    if show_duration {
                        let duration = e - s;
                        let dur = format!("{days} Days, {hours} Hours, {minutes} Minutes, {seconds} Seconds",
                                days    = duration.num_days(),
                                hours   = duration.num_hours(),
                                minutes = duration.num_minutes(),
                                seconds = duration.num_seconds());

                        v.push(dur);
                    }

                    v
                },
            };

            let cells : Vec<Cell> = v.iter().map(|s| Cell::new(s)).collect();
            table.add_row(Row::new(cells));

            rt.report_touched(e.get_location())?;
            Ok(false)
        })
        .collect::<Result<Vec<bool>>>()?
        .iter()
        .any(|b| !b);

    if !table_empty {
        table.print(&mut rt.stdout())
            .context("Failed to print table")
            .map_err(Error::from)
            .map(|_| ())
    } else {
        Ok(())
    }
}