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
//! Support for accessing the timelog logic from a tool
//!
//! # Examples
//!
//! ```rust,no_run
//! use structopt::StructOpt;
//!
//! use timelog::Cli;
//!
//! # fn main() {
//! let cli = Cli::from_args();
//! let _ = cli.run();
//! #  }
//! ```
//!
//! # Description
//!
//! The [`Cli`] struct handling the command line processing for the main program.
use std::iter::once;
use std::path::PathBuf;

use crate::config::{Config, DEFAULT_BROWSER, DEFAULT_CONF, DEFAULT_DIR, DEFAULT_EDITOR};
#[doc(inline)]
use crate::error::Error;
#[doc(inline)]
use crate::error::PathError;
use crate::Result;

use lazy_static::lazy_static;
use regex::Regex;
use structopt::StructOpt;
use terminal_size::{terminal_size, Width};

pub mod args;
pub mod cmd;

pub type PosIntArg = args::PosIntArg;
pub type FilterArgs = args::FilterArgs;
pub type DateRangeArgs = args::DateRangeArgs;

/// Name of the program binary.
const BIN_NAME: &str = "rtimelog";

lazy_static! {
    /// Regular expression for matching the alias template match
    static ref SUBST_RE: Regex = Regex::new(r#"\{\}"#).unwrap();
}

// Utility type for a vector of strings
#[derive(Debug, Default, PartialEq, StructOpt)]
struct VecString {
    args: Vec<String>,
}

// Utility type for an optional string
#[derive(Debug, Default, PartialEq, StructOpt)]
struct OptString {
    arg: Option<String>,
}

// Enumeration for determining whether to expand aliases.
enum ExpandAlias {
    Yes,
    No,
}

// Help message explaining a task description
const TASK_DESC: &str = "The command takes a 'task description' consisting of an optional project \
formatted with a leading '+', an optional task name formatted with a leading '@', and potentially \
more text adding details to the task. If no task name starting with '@' is supplied, any extra text \
is treated as the task.";

// Help message explaining the format of an event description.
const DATE_DESC: &str = "The 'date description' consists of a date of the form 'YYYY-MM-DD', or one \
of a set of relative date strings including: today, yesterday, sunday, monday, tuesday, wednesday, \
thursday, friday, or saturday. The first two are obvious. The others refer to the previous instance \
of that day.";

lazy_static! {
    static ref FULL_DESC: String = format!("{}\n\n{}", TASK_DESC, DATE_DESC);
}

/// Specify the stack subcommands supported by the program.
#[derive(Debug, PartialEq, StructOpt)]
enum StackCommands {
    /// Clear all of the items from the stack.
    Clear,

    /// Drop items from stack.
    #[structopt(
        usage = "drop [{num}]",
        after_help = r"
    - If an positive integer is supplied, that number of items is dropped from the top of the stack.
    - If no argument is supplied, drop only the top item."
    )]
    Drop(OptString),

    /// Remove all except the top number of items from the stack.
    #[structopt(
        usage = "keep [{num}]",
        after_help = r"
    - If an positive integer is supplied, that number of items are kept on the top of stack, discarding the rest
    - If no argument is supplied, drop all but the top 10 items"
    )]
    Keep(OptString),

    /// Display items on the stack.
    Ls,
}

/// Specify the stack subcommands supported by the program.
#[derive(Debug, PartialEq, StructOpt)]
enum TaskCommands {
    /// Discard the most recent entry.
    Discard,

    /// Reset the time of the most recent entry to now.
    Now,

    /// Return to the previous task, setting the current entry as ignored.
    Ignore,

    /// Rewrite the most recent entry.
    #[structopt(usage = "task rewrite {event description}", after_help = TASK_DESC)]
    Rewrite(VecString),
}

/// Specify the stack subcommands supported by the program.
#[derive(Debug, PartialEq, StructOpt)]
enum ReportCommands {
    /// Display a report for the specified days and projects.
    #[structopt(usage = "report detail [date_desc [end_date_desc]] [project_regex]...", after_help = DATE_DESC)]
    Detail(VecString),

    /// Display a summary of the appropriate days' projects.
    #[structopt(usage = "report summary [date_desc [end_date_desc]] [project_regex]...", after_help = DATE_DESC)]
    Summary(VecString),

    /// Display the hours worked for each of the appropriate days and projects.
    #[structopt(usage = "report hours [date_desc [end_date_desc]] [project_regex]...", after_help = DATE_DESC)]
    Hours(VecString),

    /// Display the zero duration events for each of the appropriate days and projects.
    #[structopt(usage = "report events [date_desc [end_date_desc]]", after_help = DATE_DESC)]
    Events(VecString),

    /// Display a chart of the hours worked for each of the appropriate days and projects.
    #[structopt(usage = "report chart [date_desc [end_date_desc]]", after_help = DATE_DESC)]
    Chart(VecString),
}

/// Specify the subcommands supported by the program.
#[derive(Debug, PartialEq, StructOpt)]
enum Subcommands {
    /// Create the timelog directory and configuration.
    ///
    /// Use the supplied directory, or default to `~/timelog` if not supplied.
    #[structopt(usage = "init [dir]")]
    Init(OptString),

    /// Start timing a new task.
    ///
    /// Stop timing the current task (if any) and start timing a new task.
    #[structopt(usage = "start {task description}", after_help = TASK_DESC)]
    Start(VecString),

    /// Stop timing the current task.
    Stop,

    /// Add a comment line.
    Comment(VecString),

    /// Add a zero duration event
    Event(VecString),

    /// Save the current task and start timing a new task.
    ///
    /// This command works the same as the `start` command, except that the
    /// current task description is saved on the top of the stack. This makes
    /// resuming the previous task easier.
    #[structopt(usage = "push {task description}", after_help = TASK_DESC)]
    Push(VecString),

    /// Stop last task and restart top task on stack.
    Resume,

    /// Save the current task and stop timing.
    Pause,

    /// Pop the top task description on the stack and push the current task.
    Swap,

    /// List entries for the specified day. Default to today.
    #[structopt(usage = "ls {date_desc}", after_help = DATE_DESC)]
    Ls(OptString),

    /// List known projects.
    Lsproj,

    /// Open the timelog file in the current editor.
    Edit,

    /// Display the current task.
    Curr,

    /// Check the logfile for problems.
    Check,

    /// Archive the first year from the timelog file, as long as it isn't the current year.
    Archive,

    /// List the aliases from the config file.
    Aliases,

    /// Reporting commands
    Report(ReportCommands),

    /// Stack specific commands
    Stack(StackCommands),

    /// Task specific commands
    Task(TaskCommands),

    // `external_subcommand` tells structopt to put
    // all the extra arguments into this Vec
    #[structopt(external_subcommand)]
    Other(Vec<String>),
}

/// Specify all of the command line parameters supported by the program.
#[derive(StructOpt, Debug)]
#[structopt(about, after_help = FULL_DESC.as_str())]
pub struct Cli {
    /// Specify a directory for logging the task events and stack.
    #[structopt(long, parse(from_os_str), default_value = &DEFAULT_DIR)]
    dir: PathBuf,

    /// Specify the editor to use for modifying events.
    #[structopt(long, parse(from_os_str), default_value = &DEFAULT_EDITOR)]
    editor: PathBuf,

    /// Specify the path to the configuration file.
    #[structopt(long, parse(from_os_str), default_value = &DEFAULT_CONF)]
    conf: PathBuf,

    /// Specify the command to execute the browser.
    #[structopt(long, default_value = &DEFAULT_BROWSER)]
    browser: String,

    /// Sub-commands which determine what actions to take
    #[structopt(subcommand)]
    cmd: Option<Subcommands>,
}

impl Cli {
    /// Execute the action specified on the command line.
    ///
    /// ## Errors
    ///
    /// - Return [`PathError::FilenameMissing`] if no configuration file is known.
    /// - Return [`PathError::InvalidPath`] if the timelog directory is not a valid path.
    /// - Return [`PathError::FilenameMissing`] if no editor has been configured.
    /// - Return other errors specific to the commands.
    pub fn run(&self) -> Result<()> {
        let width = match terminal_size() {
            Some((Width(w), _)) => w as usize,
            _ => 120,
        };
        Self::clap().set_term_width(width);
        let config = self.config()?;
        match &self.cmd {
            Some(cmd) => cmd.run(&config, ExpandAlias::Yes),
            None => Subcommands::default_command(&config).run(&config, ExpandAlias::No),
        }
    }

    // Retrieve the configuration from the file.
    //
    // ## Errors
    //
    // - Return [`PathError::FilenameMissing`] if no configuration file is known.
    // - Return [`PathError::InvalidPath`] if the timelog directory is not a valid path.
    // - Return [`PathError::FilenameMissing`] if no editor has been configured.
    fn config(&self) -> std::result::Result<Config, PathError> {
        let conf_file = self.conf.to_str().ok_or(PathError::FilenameMissing)?;
        match Config::from_file(conf_file) {
            Ok(config) => Ok(config),
            Err(_) => {
                let mut config = Config::default();
                config.set_dir(
                    self.dir
                        .to_str()
                        .ok_or_else(|| PathError::InvalidPath(String::new(), String::new()))?
                );
                config.set_editor(
                    self.editor
                        .to_str()
                        .ok_or(PathError::FilenameMissing)?
                );
                config.set_browser(&self.browser);
                Ok(config)
            }
        }
    }
}

// Recognize deprecated commands, supply user message, and terminate the program.
fn process_deprecated_cmd(cmd: &str, e: Error) -> Result<()> {
    match cmd {
        "pop" => Err(Error::DeprecatedCommand("resume")),
        "drop" => Err(Error::DeprecatedCommand("stack drop' or 'stack clear")),
        "lstk" => Err(Error::DeprecatedCommand("stack ls")),
        "summary" => Err(Error::DeprecatedCommand("report summary")),
        "hours" => Err(Error::DeprecatedCommand("report hours")),
        "chart" => Err(Error::DeprecatedCommand("report chart")),
        _ => Err(e),
    }
}

impl Subcommands {
    /// Execute the action associated with the current variant.
    ///
    /// ## Errors
    ///
    /// - Return [`Error`]s for particular commands failing.
    /// - Return [`Error::InvalidCommand`] if the subcommand is not recognized and no alias
    /// matches.
    pub fn run(&self, config: &Config, expand: ExpandAlias) -> Result<()> {
        use Subcommands::*;

        match &self {
            Init(arg) => Ok(cmd::initialize(config, &arg.arg)?),
            Start(args) => cmd::start_task(config, &args.args),
            Stop => cmd::stop_task(config),
            Comment(args) => cmd::add_comment(config, &args.args),
            Event(args) => cmd::add_event(config, &args.args),
            Push(args) => cmd::push_task(config, &args.args),
            Resume => cmd::resume_task(config),
            Pause => cmd::pause_task(config),
            Swap => cmd::swap_entry(config),
            Ls(arg) => cmd::list_entries(config, &arg.arg),
            Lsproj => cmd::list_projects(config),
            Edit => cmd::edit(config),
            Curr => cmd::current_task(config),
            Check => cmd::check_logfile(config),
            Archive => cmd::archive_year(config),
            Aliases => cmd::list_aliases(config),
            Report(cmd) => cmd.run(config),
            Stack(cmd) => cmd.run(config),
            Task(cmd) => cmd.run(config),
            Other(args) => {
                match expand {
                    ExpandAlias::Yes => self.expand_alias(config, args),
                    ExpandAlias::No => Err(Error::InvalidCommand(args[0].to_owned())),
                }.or_else(|e| process_deprecated_cmd(&args[0], e))
            },
        }
    }

    fn default_command(config: &Config) -> Self {
        match config.defcmd() {
            "init" => Self::Init(OptString::default()),
            "start" => Self::Start(VecString::default()),
            "stop" => Self::Stop,
            "push" => Self::Push(VecString::default()),
            "resume" => Self::Resume,
            "pause" => Self::Pause,
            "swap" => Self::Swap,
            "ls" => Self::Ls(OptString::default()),
            "lsproj" => Self::Lsproj,
            "edit" => Self::Edit,
            "curr" => Self::Curr,
            "archive" => Self::Archive,
            "aliases" => Self::Aliases,
            _ => Self::Curr,
        }
    }

    // Replace an alias as the first argument with the definition of the alias.
    fn expand_alias(&self, config: &Config, args: &[String]) -> Result<()> {
        let alias = &args[0];
        let mut args_iter = args[1..].iter().map(|s| s.as_str());

        let expand: Vec<String> = config.alias(alias)
            .ok_or_else(|| Error::InvalidCommand(alias.to_owned()))?
            .split(' ')
            .map(|w| {
                if SUBST_RE.is_match(w) {
                    args_iter.next()
                        .map(|val| SUBST_RE.replace(w, val).into_owned())
                        .unwrap_or_else(|| w.to_string())
                }
                else {
                    w.to_string()
                }
            })
            .collect();

        let cmd =
            Subcommands::from_iter(
                once(BIN_NAME)
                    .chain(expand.iter().map(|s| s.as_str()))
                    .chain(args_iter)
            );
        cmd.run(config, ExpandAlias::No)
    }
}

impl StackCommands {
    /// Execute the action associated with the current variant.
    ///
    /// ## Errors
    ///
    /// - Return [`Error`]s for particular commands failing.
    /// - Return [`Error::InvalidCommand`] if the subcommand is not recognized and no alias
    /// matches.
    pub fn run(&self, config: &Config) -> Result<()> {
        use StackCommands::*;
        match &self {
            Clear => cmd::stack_clear(config),
            Drop(arg) => cmd::stack_drop(config, PosIntArg::parse(&arg.arg, 1)?),
            Keep(arg) => cmd::stack_keep(config, PosIntArg::parse(&arg.arg, 10)?),
            Ls => cmd::list_stack(config),
        }
    }
}

impl TaskCommands {
    /// Execute the action associated with the current variant.
    ///
    /// ## Errors
    ///
    /// - Return [`Error`]s for particular commands failing.
    /// - Return [`Error::InvalidCommand`] if the subcommand is not recognized and no alias
    /// matches.
    pub fn run(&self, config: &Config) -> Result<()> {
        use TaskCommands::*;
        match &self {
            Discard => cmd::discard_last_entry(config),
            Now => cmd::reset_last_entry(config),
            Ignore => cmd::ignore_last_entry(config),
            Rewrite(args) => cmd::rewrite_last_entry(config, &args.args),
        }
    }
}

impl ReportCommands {
    /// Execute the action associated with the current variant.
    ///
    /// ## Errors
    ///
    /// - Return [`Error`]s for particular commands failing.
    /// - Return [`Error::InvalidCommand`] if the subcommand is not recognized and no alias
    /// matches.
    pub fn run(&self, config: &Config) -> Result<()> {
        use ReportCommands::*;
        match &self {
            Detail(args) => cmd::report_daily(config, &args.args),
            Summary(args) => cmd::report_summary(config, &args.args),
            Hours(args) => cmd::report_hours(config, &args.args),
            Events(args) => cmd::report_events(config, &args.args),
            Chart(args) => cmd::chart_daily(config, &args.args),
        }
    }
}