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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
extern crate chrono;
extern crate clap;
extern crate colonnade;
extern crate two_timer;

use crate::configure::Configuration;
use crate::log::{Done, Item, ItemsAfter, LogController};
use crate::util::{fatal, log_path, remainder};
use chrono::{Local, NaiveDateTime};
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use colonnade::{Alignment, Colonnade};
use std::collections::BTreeSet;
use two_timer::parse;

fn after_help() -> &'static str {
    "\
If you want aggregate statistics about your job log, this is your subcommand.

  > job statistics
  lines                            18,867
  first timestamp     2014-10-06 08:57:29
  last timestamp      2020-01-31 16:50:22
  hours clocked                    10,701
  events                           14,529
  notes                               202
  distinct event tags               2,337
  distinct note tags                   17
  comments                          1,333
  blank lines                           2
  errors                                0

All prefixes of 'statistics' after 's' -- 'st', 'sta', 'stat', etc. -- are aliases of \
this subcommand, as is 'stats'. The 's' prefix is reserved for the summary subcommand.
"
}

pub fn cli(mast: App<'static, 'static>, display_order: usize) -> App<'static, 'static> {
    mast.subcommand(
        SubCommand::with_name("statistics")
            .after_help(after_help())
            .aliases(&[
                "st",
                "sta",
                "stat",
                "stats",
                "stati",
                "statis",
                "statist",
                "statisti",
                "statistic",
            ])
            .arg(
                Arg::with_name("raw-numbers")
                    .long("raw-numbers")
                    .help("Shows counts without the comma group separator")
                    .display_order(1),
            )
            .about("Shows overall statistics of the log")
            .setting(AppSettings::TrailingVarArg)
            .arg(
                Arg::with_name("period")
                    .help("time expression")
                    .long_help(
                        "All the <period> arguments are concatenated to produce a time expression.",
                    )
                    .value_name("period")
                    .multiple(true),
            )
            .display_order(display_order),
    )
}

pub fn run(directory: Option<&str>, matches: &ArgMatches) {
    let no_commas = matches.is_present("raw-numbers");
    let conf = Configuration::read(None, directory);
    let mut colonnade =
        Colonnade::new(2, conf.width()).expect("could not build the statistics table");
    colonnade.columns[1].alignment(Alignment::Right);
    let (start_offset, end_time) = where_to_begin(matches, &conf);
    let items = ItemsAfter::new(
        start_offset,
        log_path(conf.directory()).as_path().to_str().unwrap(),
    );
    let mut line_count = 0;
    let mut event_count = 0;
    let mut note_count = 0;
    let mut comment_count = 0;
    let mut error_count = 0;
    let mut blank_line_count = 0;
    let mut event_tags: BTreeSet<String> = BTreeSet::new();
    let mut note_tags: BTreeSet<String> = BTreeSet::new();
    let mut first_timestamp: Option<NaiveDateTime> = None;
    let mut last_timestamp: Option<NaiveDateTime> = None;
    let mut duration = 0;
    let mut open_timetamp: Option<NaiveDateTime> = None;
    for item in items {
        if let Some((t, _)) = item.time() {
            if t > &end_time {
                break;
            }
            last_timestamp = Some(t.clone());
            if first_timestamp.is_none() {
                first_timestamp = Some(t.clone());
            }
            if open_timetamp.is_none() {
                open_timetamp = Some(t.clone());
            }
        }
        line_count += 1;
        match item {
            Item::Event(e, _) => {
                event_count += 1;
                for t in e.tags {
                    event_tags.insert(t);
                }
            }
            Item::Note(n, _) => {
                note_count += 1;
                for t in n.tags {
                    note_tags.insert(t);
                }
            }
            Item::Blank(_) => blank_line_count += 1,
            Item::Comment(_) => comment_count += 1,
            Item::Done(Done(d), _) => {
                if let Some(t) = open_timetamp {
                    duration += (d.timestamp() - t.timestamp()) as usize;
                }
                open_timetamp = None;
            }
            Item::Error(_, _) => error_count += 1,
        }
    }
    let data = [
        [String::from("lines"), format_num(line_count, no_commas)],
        [
            String::from("first timestamp"),
            if let Some(t) = first_timestamp {
                format!("{}", t)
            } else {
                String::from("")
            },
        ],
        [
            String::from("last timestamp"),
            if let Some(t) = last_timestamp {
                format!("{}", t)
            } else {
                String::from("")
            },
        ],
        [
            String::from("hours clocked"),
            format!(
                "{}",
                format_num(
                    ((duration as f64) / (60.0 * 60.0)).round() as usize,
                    no_commas
                )
            ),
        ],
        [String::from("events"), format_num(event_count, no_commas)],
        [String::from("notes"), format_num(note_count, no_commas)],
        [
            String::from("distinct event tags"),
            format_num(event_tags.len(), no_commas),
        ],
        [
            String::from("distinct note tags"),
            format_num(note_tags.len(), no_commas),
        ],
        [
            String::from("comments"),
            format_num(comment_count, no_commas),
        ],
        [
            String::from("blank lines"),
            format_num(blank_line_count, no_commas),
        ],
        [String::from("errors"), format_num(error_count, no_commas)],
    ];
    for line in colonnade.tabulate(&data).expect("couild not tabulate data") {
        println!("{}", line);
    }
}

fn where_to_begin(matches: &ArgMatches, conf: &Configuration) -> (usize, NaiveDateTime) {
    if matches.is_present("period") {
        let period = remainder("period", matches);
        match parse(&period, conf.two_timer_config()) {
            Ok((t1, t2, _)) => {
                let mut log =
                    LogController::new(None, conf).expect("could not open log for reading");
                if let Some(item) = log.find_line(&t1) {
                    (item.offset(), t2)
                } else {
                    fatal("the log does not cover the period specified", conf);
                    unreachable!()
                }
            }
            _ => {
                fatal(
                    &format!("could not parse {} as a time expression", period),
                    conf,
                );
                unreachable!()
            }
        }
    } else {
        (0, Local::now().naive_local())
    }
}

fn format_num(n: usize, no_commas: bool) -> String {
    let s1 = n.to_string();
    if no_commas {
        return s1;
    }
    let mut count = 0;
    let mut s = String::new();
    for c in s1.chars().rev() {
        s.push(c);
        count += 1;
        if count % 3 == 0 && count < s1.len() {
            s += ",";
        }
    }
    s.chars().rev().collect()
}