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
// cli args parser
use crate::config;
use crate::db::ops;
use crate::db::utils::TaskNotFound;
use crate::utils::{fmt_duration, open_naivedate, unwrap_string, utc_to_local_naive, BoxError};

use chrono::NaiveDate;
use comfy_table::Table;
use dialoguer::Confirm;
use log::debug;
use std::path::PathBuf;
use structopt::clap::AppSettings;
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
// #[structopt(setting = AppSettings::InferSubcommands)]
struct Cli {
    #[structopt(parse(from_os_str), help = "config file", long)]
    config: Option<PathBuf>,
    #[structopt(parse(from_os_str), help = "database file", long)]
    dbfile: Option<PathBuf>,
    #[structopt(subcommand)]
    cmd: Sub,
}

#[derive(StructOpt, Debug)]
enum Sub {
    #[structopt(name = "create", visible_alias = "new")]
    Create(CreateOpts),
    #[structopt(name = "edit")]
    Edit(EditOpts),
    #[structopt(name = "delete", visible_alias = "del")]
    Delete(DeleteOpts),
    #[structopt(name = "start")]
    Start(StartOpts),
    #[structopt(name = "stop")]
    Stop(StopOpts),
    #[structopt(name = "stopall")]
    StopAll(StopAllOpts),
    #[structopt(name = "status", visible_alias = "stat")]
    Status(StatusOpts),
    #[structopt(name = "list", visible_alias = "ls")]
    List(ListOpts),
    #[structopt(name = "test", setting = AppSettings::Hidden)]
    Test(TestOpts),
}

#[derive(StructOpt, Debug)]
struct TestOpts {}

#[derive(StructOpt, Debug)]
struct CreateOpts {
    #[structopt(help = "New task name")]
    name: String,
    #[structopt(short = "t", help = "Task allocation time in minutes")]
    allocated: Option<i32>,
    #[structopt(short = "d", help = "Due date")]
    duedate: Option<NaiveDate>,
    #[structopt(short = "n", long = "note", help = "Description")]
    note: Option<String>,
}

#[derive(StructOpt, Debug)]
struct EditOpts {
    #[structopt(help = "Task name")]
    name: String,
    #[structopt(short = "t", help = "Task allocation time in minutes")]
    allocated: Option<i32>,
    #[structopt(short = "d", help = "Due date")]
    duedate: Option<NaiveDate>,
    #[structopt(short = "n", long = "note", help = "Description")]
    note: Option<String>,
    #[structopt(short, long, help = "Set as finished", conflicts_with = "incomplete")]
    finish: bool,
    #[structopt(short, long, help = "Set as incomplete")]
    incomplete: bool,
}

#[derive(StructOpt, Debug)]
struct DeleteOpts {
    #[structopt(help = "Task name")]
    name: String,
    #[structopt(long, help = "Skip confirmation")]
    noconfirm: bool,
}

#[derive(StructOpt, Debug)]
struct StartOpts {
    #[structopt(help = "Task name(s)", required = true)]
    name: Vec<String>,
}

#[derive(StructOpt, Debug)]
struct StopOpts {
    #[structopt(help = "Task name(s)", required = true)]
    name: Vec<String>,
}

#[derive(StructOpt, Debug)]
struct StopAllOpts {}

#[derive(StructOpt, Debug)]
struct StatusOpts {
    #[structopt(short = "f", long = "filter", name = "task name")]
    filter: Option<String>,
}

#[derive(StructOpt, Debug)]
struct ListOpts {
    #[structopt(short = "s", long = "status", possible_values = &["all", "done", "incomplete"], default_value = "incomplete")]
    status: String,
    #[structopt(short = "f", long = "filter", name = "task name")]
    filter: Option<String>,
}

enum TaskStatus {
    All,
    Done,
    Incomplete,
}

impl std::str::FromStr for TaskStatus {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_ref() {
            "all" => Ok(TaskStatus::All),
            "done" => Ok(TaskStatus::Done),
            "incomplete" => Ok(TaskStatus::Incomplete),
            _ => Err("no match"),
        }
    }
}

pub fn parse_cli() -> Result<(), BoxError> {
    let args = Cli::from_args();
    debug!("Hello, world!");
    debug!("{:?}", &args);

    let conf: Option<&PathBuf> = match &args.config {
        Some(val) => Some(&val),
        None => None,
    };

    let dbfile: Option<&PathBuf> = match &args.dbfile {
        Some(val) => Some(&val),
        None => None,
    };

    let cfgpath = match config::create_config(conf, dbfile) {
        Ok((created, path)) => {
            if created {
                println!("Created config file at {:?}", path);
            }
            path
        }
        Err(err) => {
            return Err(err);
        }
    };

    let mut config = config::Config::load(Some(&cfgpath))?;

    if let Some(path) = &args.dbfile {
        config
            .database
            .insert("path".to_owned(), path.to_string_lossy().to_string());
    }

    match &args.cmd {
        Sub::Create(args) => {
            let allocated = match args.allocated {
                Some(val) => Some(val * 60), // mins to secs
                None => None,
            };
            ops::create_task(
                &config,
                &args.name,
                args.note.as_deref(),
                allocated,
                open_naivedate(args.duedate).as_deref(),
            )
        }
        Sub::List(args) => list_tasks(&config, args),
        Sub::Edit(args) => update_task(&config, args),
        Sub::Delete(args) => delete_task(&config, args),
        Sub::Start(args) => start_task(&config, args),
        Sub::Stop(args) => stop_task(&config, args),
        Sub::StopAll(args) => stop_all_tasks(&config, args),
        Sub::Status(args) => tasks_status(&config, args),
        _ => Ok(()),
    }
}

fn list_tasks(config: &config::Config, args: &ListOpts) -> Result<(), BoxError> {
    let data = ops::list_tasks(&config, args.filter.as_deref(), Some(&args.status))?;
    // debug!("result: {:#?}", data);
    let mut table = Table::new();
    table.set_header(vec![
        "#",
        "Task",
        "Notes",
        "Spent",
        "Allocated",
        "Due Date",
        "Done",
        "Created",
    ]);
    for (i, row) in data.iter().enumerate() {
        let spent = ops::get_total_spent(&config, &row.taskname)?;
        table.add_row(vec![
            (i + 1).to_string(),
            // (row.id).to_string(),
            row.taskname.to_string(),
            unwrap_string(row.notes.as_ref(), "-"),
            fmt_duration(spent, false, "not started"),
            fmt_duration(row.allocated, true, "-"),
            unwrap_string(row.duedate.as_ref(), "-"),
            row.done.to_string(),
            utc_to_local_naive(&row.created)?.to_string(),
        ]);
    }
    println!("{}", table);
    Ok(())
}

fn update_task(config: &config::Config, args: &EditOpts) -> Result<(), BoxError> {
    let allocated = args.allocated.unwrap_or(0) * 60; //
    let mut done: Option<bool> = None;
    if args.finish {
        done = Some(true);
    } else if args.incomplete {
        done = Some(false);
    }
    ops::update_tasks(
        config,
        &args.name,
        args.note.as_deref(),
        Some(allocated),
        open_naivedate(args.duedate).as_deref(),
        done,
    )
}

fn delete_task(config: &config::Config, args: &DeleteOpts) -> Result<(), BoxError> {
    if !args.noconfirm {
        let mut prompt = "Delete task ".to_owned();
        prompt.push_str(&args.name);
        prompt.push_str(" ?");
        if !Confirm::new().with_prompt(prompt).interact()? {
            return Ok(());
        }
    }
    let exists = ops::check_task_exists(config, &args.name)?;
    if !exists {
        return Err(TaskNotFound.into());
    }
    ops::delete_task(config, &args.name)
}

fn start_task(config: &config::Config, args: &StartOpts) -> Result<(), BoxError> {
    ops::start_worklogs(config, &args.name)
}

fn stop_task(config: &config::Config, args: &StopOpts) -> Result<(), BoxError> {
    ops::stop_worklogs(config, &args.name)
}

fn stop_all_tasks(config: &config::Config, _args: &StopAllOpts) -> Result<(), BoxError> {
    let running_tasks = ops::get_running_tasks(config, None)?;
    let tasknames: Vec<String> = running_tasks.iter().map(|t| t.name.to_owned()).collect();
    ops::stop_worklogs(config, &tasknames)
}

fn tasks_status(config: &config::Config, args: &StatusOpts) -> Result<(), BoxError> {
    let tasks = ops::get_running_tasks(config, args.filter.as_deref())?;
    if tasks.is_empty() {
        println!("No running task");
        return Ok(());
    }
    let mut table = Table::new();
    table.set_header(vec!["#", "Task", "Spent", "Last Started", "Total Spent"]);
    for (i, row) in tasks.iter().enumerate() {
        table.add_row(vec![
            (i + 1).to_string(),
            row.name.to_string(),
            fmt_duration(row.current_spent, false, "-"),
            utc_to_local_naive(&row.started)?.to_string(),
            fmt_duration(row.spent, false, "-"),
        ]);
    }
    println!("{}", table);
    Ok(())
}