~swalladge/tempoit

ref: ad1a951722668de70c2d546829c872894fc534d3 tempoit/src/timew.rs -rw-r--r-- 4.7 KiB
ad1a9517Samuel Walladge Add contributing guidelines 3 months ago
                                                                                
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
use std::error::Error;
use std::fmt;
use std::process::Command;
use std::str;

use chrono::{DateTime, Local, NaiveDateTime, Utc};
use regex::Regex;
use serde::{Deserialize, Deserializer};

use crate::jira::Worklog;

fn deserialize_id<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: Deserializer<'de>,
{
    let id = u32::deserialize(deserializer)?;
    Ok(format!("@{}", id))
}

fn deserialize_datetime<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
where
    D: Deserializer<'de>,
{
    let date_string = String::deserialize(deserializer)?;
    NaiveDateTime::parse_from_str(&date_string, "%Y%m%dT%H%M%SZ")
        .map_err(serde::de::Error::custom)
        .map(|x| DateTime::<Utc>::from_utc(x, Utc))
}

fn deserialize_option_datetime<'de, D>(deserializer: D) -> Result<Option<DateTime<Utc>>, D::Error>
where
    D: Deserializer<'de>,
{
    let option_date_string = Option::<String>::deserialize(deserializer)?;
    option_date_string
        .map(|x| {
            NaiveDateTime::parse_from_str(&x, "%Y%m%dT%H%M%SZ")
                .map_err(serde::de::Error::custom)
                .map(|x| DateTime::<Utc>::from_utc(x, Utc))
        })
        .transpose()
}

// All datetimes output from timew export are in utc.
#[derive(Debug, Deserialize)]
struct Interval {
    #[serde(deserialize_with = "deserialize_id")]
    id: String,
    #[serde(deserialize_with = "deserialize_datetime")]
    start: DateTime<Utc>,
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_option_datetime")]
    end: Option<DateTime<Utc>>,
    #[serde(default)]
    tags: Vec<String>,
    annotation: Option<String>,
}

impl fmt::Display for Interval {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let date = self.end.unwrap_or(self.start).date().format("%Y-%m-%d");
        let duration = match self.end {
            Some(end) => {
                let duration = end - self.start;
                format!(
                    "{}h {}m",
                    duration.num_hours(),
                    duration.num_minutes() - duration.num_hours() * 60
                )
            }
            None => "open".to_owned(),
        };

        write!(
            f,
            "{id:<5} {date} {duration:7} [{tags:^15}] '{annotation}'",
            date = date,
            id = self.id,
            tags = self.tags.join(", "),
            annotation = self.annotation.clone().unwrap_or("-".to_owned()),
            duration = duration,
        )
    }
}

fn parse_interval(ticket_regex: &Regex, interval: &Interval) -> Result<Worklog, String> {
    let end = match interval.end {
        Some(end) => end,
        None => {
            return Err(format!("INFO( open ): {}", interval));
        }
    };

    let duration = end - interval.start;
    let date = end.with_timezone(&Local).date().naive_local();

    let issue = match interval.tags.iter().find(|x| ticket_regex.is_match(x)) {
        Some(issue) => issue.to_uppercase(),
        None => {
            return Err(format!("ERR( untagged ): {}", interval));
        }
    };

    let id = interval.id.to_string();

    let description = match interval.annotation.clone() {
        None => {
            return Err(format!("ERR(no ann): {}", interval));
        }
        Some(ann) => ann,
    };

    return Ok(Worklog {
        id,
        duration,
        date,
        issue,
        description,
    });
}

type ClientResult<T> = Result<T, Box<dyn Error>>;

pub struct TimewClient {
    ticket_regex: Regex,
}

impl TimewClient {
    pub fn new(ticket_regex: Regex) -> Self {
        Self {
            ticket_regex,
        }
    }

    pub fn get_worklogs(&self) -> ClientResult<Vec<Result<Worklog, String>>> {
        // TODO: make this command configurable
        let proc = Command::new("timew")
            .args(&["export", "oc", "log"])
            .output()?;
        let export_contents = str::from_utf8(&proc.stdout)?;
        let intervals: Vec<Interval> = serde_json::from_str(export_contents)?;

        Ok(intervals.iter().map(|x| parse_interval(&self.ticket_regex, x)).collect())
    }

    pub fn record_success(&self, id: &str) -> ClientResult<()> {
        run("timew", &["tag", id, "logged"])?;
        run("timew", &["untag", id, "log", "logfail"])
    }

    pub fn record_fail(&self, id: &str) -> ClientResult<()> {
        run("timew", &["tag", id, "logfail"])
    }
}

/// Helper function to spawn and run a command, returning an error if did not exit cleanly.
pub fn run(cmd: &str, args: &[&str]) -> Result<(), Box<dyn Error>> {
    println!("RUN {} {:?}", cmd, args);
    let status = Command::new(cmd).args(args).status()?;
    match status.success() {
        true => Ok(()),
        false => Err(format!("Command exited with {}", status).into()),
    }
}