timmy 0.1.0

A time tracker mainly for programming tasks
Documentation
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
#![feature(question_mark)]

extern crate timmy;

#[macro_use]
extern crate log;
extern crate env_logger;

extern crate clap;
extern crate rusqlite;
extern crate chrono;
extern crate ansi_term;

use std::{fs, env, io};
use std::path::Path;
use std::convert::From;
use std::process::Command;
use clap::{Arg, App, SubCommand};
use rusqlite::{Connection, Statement, Transaction};
use chrono::*;
use ansi_term::Style;
use timmy::tables::*;
use timmy::chronny;

#[derive(Debug)]
enum Error {
    ProjectNotFound(String),
    Sqlite(rusqlite::Error),
    Git,
    InvalidDateTime(String),
}

impl From<rusqlite::Error> for Error {
    fn from(e: rusqlite::Error) -> Error {
        Error::Sqlite(e)
    }
}

fn open_connection() -> Result<Connection, Error> {
    let home = env::var("HOME").unwrap_or("./".into());
    let path = Path::new(&home).join(".timmy");
    if !path.exists() {
        fs::create_dir(&path).unwrap();
    }
    let path = path.join("db.sqlite3");
    let conn = Connection::open(path)?;

    conn.execute_batch("CREATE TABLE IF NOT EXISTS projects (
                            id       INTEGER PRIMARY KEY,
                            name     TEXT NOT NULL UNIQUE,
                            customer TEXT
                        );
                        CREATE TABLE IF NOT EXISTS tags_projects_join (
                            tag_name   TEXT NOT NULL,
                            project_id INTEGER NOT NULL,
                            UNIQUE(tag_name, project_id)
                        );
                        CREATE TABLE IF NOT EXISTS timeperiods (
                            id           INTEGER PRIMARY KEY,
                            project_id   INTEGER NOT NULL,
                            description  TEXT,
                            start        DATETIME NOT NULL,
                            end          DATETIME NOT NULL
                        );
                        CREATE TABLE IF NOT EXISTS commits (
                            sha           TEXT NOT NULL UNIQUE,
                            summary       TEXT NOT NULL,
                            project_id    INTEGER NOT NULL,
                            timeperiod_id INTEGER NOT NULL);")?;
    Ok(conn)
}

fn format_time(time: f64) -> String {
    if time > 1.0 {
        format!("{}hrs {}mins",
                time.floor(),
                (60.0 * (time - time.floor())).floor())
    } else if time > 0.0 {
        format!("{}mins", (time * 60.0).floor())
    } else {
        format!("None")
    }
}

fn create_project(conn: &mut Connection,
                  name: &str,
                  customer: Option<&str>,
                  tags: &str)
                  -> Result<(), Error> {
    let tx = conn.transaction()?;
    let proj_id = tx.execute("INSERT INTO projects(name, customer) VALUES (?,?)",
                 &[&name, &customer])?;
    if tags != "" {
        for tag in tags.split(',') {
            tx.execute("INSERT INTO tags_projects_join VALUES (?, ?)",
                         &[&tag, &proj_id])?;
        }
    }
    tx.commit()?;
    Ok(())
}

fn find_project(conn: &mut Connection, name: &str) -> Result<i64, Error> {
    match conn.query_row("SELECT id FROM projects WHERE name=?",
                         &[&name],
                         |row| row.get(0)) {
        Ok(id) => Ok(id),
        Err(rusqlite::Error::QueryReturnedNoRows) => Err(Error::ProjectNotFound(name.into())),
        Err(e) => Err(Error::from(e)),
    }
}

fn track(conn: &mut Connection,
         name: &str,
         description: Option<&str>,
         start: Option<&str>,
         end: Option<&str>) -> Result<(), Error> {
    let proj_id = find_project(conn, name)?;
    let start = if let Some(start) = start {
        chronny::parse_datetime(start, Local::now()).ok_or(Error::InvalidDateTime(start.into()))?
    } else {
        Local::now()
    };
    let end = if let Some(end) = end {
        chronny::parse_datetime(end, Local::now()).ok_or(Error::InvalidDateTime(end.into()))?
    } else {
        println!("When you are finished with the task press ENTER");
        let mut s = String::new();
        io::stdin().read_line(&mut s).unwrap();
        Local::now()
    };

    let tx = conn.transaction()?;
    tx.execute("INSERT INTO timeperiods(project_id, start, end, description) VALUES (?,?,?,?)",
                &[&proj_id, &start, &end, &description])?;
    let period_id = tx.last_insert_rowid();
    {
        let mut stmnt = tx.prepare("INSERT INTO commits (sha, summary, project_id, timeperiod_id) \
                                    values(?,?,?,?)")?;
        get_commits(&mut stmnt, proj_id, period_id, &start, &end)?;
    }
    tx.commit()?;
    Ok(())
}

fn get_commits(insert_stmnt: &mut Statement, proj_id: i64, period_id: i64, start: &DateTime<Local>, end: &DateTime<Local>) -> Result<(), Error> {
    let mut cmd = Command::new("git");
    cmd.arg("whatchanged")
        .arg(format!("--since={}", start.to_rfc3339()))
        .arg(format!("--until={}", end.to_rfc3339()))
        .arg("-q");
    debug!("executing {:?}", cmd);
    let output = cmd.output()
        .map_err(|e| {
            debug!("{:?}", e);
            Error::Git
        })?;

    if !output.status.success() {
        debug!("Git error: {}", String::from_utf8_lossy(&output.stderr));
        return Err(Error::Git);
    }
    let s: String = String::from_utf8_lossy(&output.stdout).into_owned();

    let mut lines = s.lines();

    while let Some(line) = lines.next() {
        // parses the following:

        // commit f04a366b0da4377b2f1e87dc9ec68bdf68c24cee
        // Author: Matthew Hall <matthew@quickbeam.me.uk>
        // Date:   Sun Aug 21 15:00:43 2016 +0100
        //
        //     Add total time to project view

        if line.starts_with("commit") {
            let sha = line.split(' ').nth(1).unwrap();
            debug!("{}", sha);
            // skip author
            lines.next();
            // skip date
            lines.next();
            // skip newline
            lines.next();
            // parse summary
            let summary = lines.next().unwrap().trim();
            println!("Found commit {}: {}", sha, summary);
            insert_stmnt.execute(&[&sha, &summary, &proj_id, &period_id])?;
        }
    }
    Ok(())
}

fn git(conn: &mut Connection, project: &str) -> Result<(), Error> {
    let proj_id = find_project(conn, project)?;
    let tx = conn.transaction()?;

    tx.execute("DELETE FROM commits WHERE project_id=?", &[&proj_id])?;

    // tx.prepare borrows tx so to call commit stmnt must be dropped
    {
        let mut stmnt = tx.prepare("SELECT id, start, end FROM timeperiods WHERE project_id=?")?;
        let mut rows = stmnt.query(&[&proj_id])?;
        let mut insert_stmnt = tx.prepare("INSERT INTO commits (sha, summary, project_id, timeperiod_id) \
                                           values(?,?,?,?)")?;
        while let Some(row) = rows.next() {
            let row = row?;
            let period_id: i64 = row.get(0);
            let start: DateTime<Local> = row.get(1);
            let end: DateTime<Local> = row.get(2);
            get_commits(&mut insert_stmnt, proj_id, period_id, &start, &end)?;
        }
    }

    tx.commit()?;
    Ok(())
}

fn projects(conn: &mut Connection) -> Result<(), Error> {
    let mut projects_stmnt =
        conn.prepare("SELECT name, customer, group_concat(tag_name) FROM projects
                      LEFT JOIN tags_projects_join on project_id=projects.id
                      GROUP BY id;")?;
    let rows =
        projects_stmnt.query_map(&[], |row| (row.get(0), row.get(1), row.get(2)))?;
    let mut table = Table::with_headers(vec!["Name".into(), "Customer".into(), "Tags".into()]);
    for row in rows {
        let (name, customer, tags): (String, Option<String>, Option<String>) = row?;
        table.add_simple(vec![name,
                              customer.unwrap_or("".into()),
                              tags.unwrap_or("".into())]);
    }
    table.add_border_bottom();
    table.print();
    Ok(())
}

fn print_activity(conn: &mut Connection, id: i64, week: bool, since: Option<&str>, until: Option<&str>) -> Result<(), Error> {
    let mut since = if let Some(since) = since {
        debug!("{}", since);
        chronny::parse_datetime(since, Local::now()).ok_or(Error::InvalidDateTime(since.into()))?
    } else {
        Local::now().with_year(1).unwrap()
    };
    let until = if let Some(until) = until {
        debug!("{}", until);
        chronny::parse_datetime(until, Local::now()).ok_or(Error::InvalidDateTime(until.into()))?
    } else {
        Local::now()
    };
    if week {
        since = Local::now() - Duration::days(7);
    }
    debug!("printing activity between {:?} and {:?}", since, until);
    let mut periods_stmnt =
        conn.prepare("SELECT id, start, end, description,
                             CAST((julianday(end)-julianday(start))*24 AS REAL)
                      FROM timeperiods
                      WHERE project_id=? AND start > ? AND start < ?
                      ORDER BY start DESC")?;
    let rows = periods_stmnt.query_map(&[&id, &since, &until],
                   |row| (row.get(0), row.get(1), row.get(2), row.get(3), row.get(4)))?;

    let subtitle_style = Style::new().underline();
    println!("{}", subtitle_style.paint("Activity"));

    let mut total = 0.0f64;
    for row in rows {
        let (timeperiod_id, start, end, description, time): (i64,
                                                             DateTime<Local>,
                                                             DateTime<Local>,
                                                             Option<String>,
                                                             f64) = row?;
        total += time;
        let time_string = format_time(time);
        let description_string = if let Some(desc) = description {
            format!(": {}", desc)
        } else {
            "".into()
        };
        let time_fmt = "%H:%M";
        println!("{} {}-{} {}{}",
                 start.format("%a %d %B %Y"),
                 start.format(time_fmt),
                 end.format(time_fmt),
                 time_string,
                 description_string);

        let mut commits_stmnt = conn.prepare("SELECT summary FROM commits WHERE timeperiod_id=?")?;
        let commits = commits_stmnt.query_map(&[&timeperiod_id], |row| (row.get(0)))?;
        for commit in commits {
            let msg: String = commit?;
            println!("    * {}", msg);
        }
    }
    println!("Total: {}", format_time(total));
    Ok(())
}

fn print_project_summary(conn: &mut Connection,
                         id: i64,
                         name: &str,
                         customer: Option<String>,
                         tags: Option<String>)
                         -> Result<(), Error>
{
    let title_style = Style::new().underline().bold();
    print!("{}", title_style.paint(name));

    if let Some(customer) = customer {
        print!("{}",
               title_style.paint(format!("for {}", customer)));
    }
    println!("");

    if let Some(tags) = tags {
        println!("Tags: {}", tags);
    }

    let total_time: Option<f64> =
        conn.query_row("SELECT SUM(CAST((julianday(end)-julianday(start))*24 as REAL))
                        FROM timeperiods WHERE project_id=?",
                       &[&id],
                       |row| row.get(0))?;
    let total_time = total_time.unwrap_or(0.0);
    let total_time_str = format_time(total_time);
    println!("Total time spent: {}", total_time_str);
    println!("");
    Ok(())
}

fn project(conn: &mut Connection,
           name: &str,
           week: bool,
           since: Option<&str>,
           until: Option<&str>)
           -> Result<(), Error>
{
    let (id, customer, tags): (i64, Option<String>, Option<String>) =
        conn.query_row("SELECT id, customer, group_concat(tag_name) FROM projects
                        LEFT JOIN tags_projects_join ON project_id=projects.id
                        WHERE name=?",
                       &[&name],
                       |row| {
                           let id: Option<i64> = row.get(0);
                           if let None = id {
                               return Err(Error::ProjectNotFound(name.into()));
                           }
                           Ok((row.get(0), row.get(1), row.get(2)))
                       })??;
    print_project_summary(conn, id, name, customer, tags)?;
    print_activity(conn, id, week, since, until)
}

fn weeks(conn: &mut Connection, name: &str) -> Result<(), Error> {
    let project_id = find_project(conn, name)?;
    let mut day_stmnt =
        conn.prepare("SELECT start,
                             SUM(CAST((julianday(end)-julianday(start))*24 AS REAL))
                      FROM timeperiods
                      WHERE project_id=?
                      GROUP BY strftime('%j', start)
                      ORDER BY strftime('%Y%W', start) DESC, start")?;
    let rows = day_stmnt.query_map(&[&project_id], |row| (row.get(0), row.get(1)))?;
    let mut week = 0;
    let mut year = 0;
    let mut start_of_week = NaiveDate::from_isoywd(1, 1, Weekday::Mon);
    let mut table = Table::with_headers(vec!["Week".into(), "Day".into(), "Time".into()]);
    let mut total_time = -1.0;
    let total_separator = vec![Cell::new_left_bordered(CellType::Data("".into()), "│"),
                               Cell::new_left_bordered(CellType::Separator, "├"),
                               Cell::new_both_bordered(CellType::Separator, "┼", "┤")];
    for row in rows {
        let (start, time): (DateTime<Local>, f64) = row?;
        let (y,w,_) = start.isoweekdate();
        let time_str = format_time(time);
        let week_str = if w != week || y != year {
            week = w;
            year = y;
            start_of_week = NaiveDate::from_isoywd(y, w, Weekday::Mon);
            if total_time >= 0.0 {
                table.add_row(total_separator.clone());
                table.add_simple(vec!["".into(), "Total".into(), format_time(total_time)]);
                table.add_full_separator();
            }
            total_time = 0.0;
            format!("{}", start_of_week.format("%d/%m/%y"))
        } else {
            "".into()
        };
        total_time += time;
        table.add_simple(vec![week_str, format!("{}", start.format("%a")), time_str]);
    }
    table.add_row(total_separator.clone());
    table.add_simple(vec!["".into(), "Total".into(), format_time(total_time)]);
    table.add_border_bottom();
    table.print();
    Ok(())
}

fn short_weeks(conn: &mut Connection, name: &str) -> Result<(), Error> {
    let project_id = find_project(conn, name)?;
    let mut weeks_stmnt =
        conn.prepare("SELECT start,
                             SUM(CAST((julianday(end)-julianday(start))*24 AS REAL))
                      FROM timeperiods
                      WHERE project_id=?
                      GROUP BY strftime('%W', start)
                      ORDER BY strftime('%Y%W', start) DESC")?;
    let rows = weeks_stmnt.query_map(&[&project_id], |row| (row.get(0), row.get(1)))?;
    for row in rows {
        let (start, time): (DateTime<Local>, f64) = row?;
        let (y,w,_) = start.isoweekdate();
        let start_of_week = NaiveDate::from_isoywd(y, w, Weekday::Mon);
        let end_of_week = NaiveDate::from_isoywd(y, w, Weekday::Sun);
        let time_str = format_time(time);
        println!("{}-{}\t{}", start_of_week.format("%d/%m/%y"), end_of_week.format("%d/%m/%y"), time_str);
    }
    Ok(())
}

fn main() {
    env_logger::init().unwrap();

    let mut conn = open_connection().unwrap();
    let matches = App::new("Timmy")
        .version("0.1")
        .author("Matthew Hall")
        .about("Time tracker")
        .subcommand(SubCommand::with_name("new")
            .about("Creates a new project")
            .arg(Arg::with_name("NAME")
                .help("the project name")
                .required(true))
            .arg(Arg::with_name("customer")
                .short("c")
                .long("customer")
                .takes_value(true))
            .arg(Arg::with_name("tags")
                .short("t")
                .long("tags")
                .help("comma separated list of tags")
                .takes_value(true)))
        .subcommand(SubCommand::with_name("track")
            .about("Start tracking a time period")
            .arg(Arg::with_name("PROJECT")
                .help("the project to start tracking time for")
                .required(true))
            .arg(Arg::with_name("description")
                .short("d")
                .long("description")
                .help("a description of what you will do in the timeperiod")
                .takes_value(true))
            .arg(Arg::with_name("start")
                 .short("s")
                 .long("start")
                 .help("When to track from")
                 .takes_value(true))
            .arg(Arg::with_name("end")
                 .short("e")
                 .long("end")
                 .help("When to end")
                 .takes_value(true)
                 .requires("start")))
        .subcommand(SubCommand::with_name("git")
            .about("go through each time period and store the commits that happened during that \
                    time. timmy track automatically does this when you quit it for that \
                    time period. This command is useful if you've modified your git history \
                    in some way or you ran timmy track in the wrong directory.")
            .arg(Arg::with_name("PROJECT")
                .help("the project to assign the commits to")
                .required(true)))
        .subcommand(SubCommand::with_name("projects").about("List the projects"))
        .subcommand(SubCommand::with_name("project")
            .about("Show a project")
            .arg(Arg::with_name("NAME")
                .help("the project to show")
                .required(true))
            .arg(Arg::with_name("since")
                 .short("s")
                 .long("since")
                 .help("the date and time from which to show activity")
                 .takes_value(true))
            .arg(Arg::with_name("until")
                 .short("u")
                 .long("until")
                 .help("the date and time until which to show activity")
                 .takes_value(true))
            .arg(Arg::with_name("week")
                 .short("w")
                 .long("week")
                 .help("show activity in the past week")
                 .conflicts_with_all(&["since", "until"])))
        .subcommand(SubCommand::with_name("weeks")
            .about("show time spent per week")
            .arg(Arg::with_name("PROJECT")
                .help("the project to show")
                .required(true))
            .arg(Arg::with_name("short")
                 .long("short")
                 .help("show the short view")))
        .get_matches();

    let res = if let Some(matches) = matches.subcommand_matches("new") {
        create_project(&mut conn,
                       matches.value_of("NAME").unwrap(),
                       matches.value_of("customer"),
                       matches.value_of("tags").unwrap_or("".into()))
    } else if let Some(matches) = matches.subcommand_matches("track") {
        track(&mut conn,
              matches.value_of("PROJECT").unwrap(),
              matches.value_of("description"),
              matches.value_of("start"),
              matches.value_of("end"))
    } else if let Some(matches) = matches.subcommand_matches("git") {
        git(&mut conn, matches.value_of("PROJECT").unwrap())
    } else if let Some(_) = matches.subcommand_matches("projects") {
        projects(&mut conn)
    } else if let Some(matches) = matches.subcommand_matches("project") {
        project(&mut conn,
                matches.value_of("NAME").unwrap(),
                matches.is_present("week"),
                matches.value_of("since"),
                matches.value_of("until"))
    } else if let Some(matches) = matches.subcommand_matches("weeks") {
        if matches.is_present("short") {
            short_weeks(&mut conn, matches.value_of("PROJECT").unwrap())
        } else {
            weeks(&mut conn, matches.value_of("PROJECT").unwrap())
        }
    } else {
        unreachable!();
    };
    match res {
        Ok(()) => {}
        Err(Error::ProjectNotFound(p)) => println!("Project {} not found", p),
        Err(Error::Git) => println!("No git repository found"),
        Err(Error::Sqlite(e)) => {
            println!("There was a problem with the database");
            debug!("{:?}", e);
        },
        Err(Error::InvalidDateTime(s)) => println!("Could not parse {}", s),
    }
}