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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Support for accessing the timelog logic from a tool
//!
//! # Examples
//!
//! ```rust,no_run
//! use clap::Parser;
//!
//! use timelog::Cli;
//!
//! # fn main() {
//! let cli = Cli::parse();
//! let _ = cli.run();
//! #  }
//! ```
//!
//! # Description
//!
//! The [`Cli`] struct handling the command line processing for the main program.
use std::iter::once;
use std::num::NonZeroU32;
use std::path::PathBuf;

use lazy_static::lazy_static;
use regex::Regex;
use clap::{Parser, Subcommand, Args};

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

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

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

pub mod args;
pub mod cmd;

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();
}

// Enumeration for determining whether to expand aliases.
#[derive(Clone, Copy)]
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!("{TASK_DESC}\n\n{DATE_DESC}");
}

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

    /// Drop items from stack.
    Drop {
        /// Number of items to drop from stack.
        ///
        /// If an positive integer is supplied, that number of items is dropped from the top of the stack.
        /// Otherwise, drop only the top item.
        #[arg(name="num")]
        num: Option<String>
    },

    /// Remove all except the top number of items from the stack.
    Keep {
        /// Number of items to keep on stack.
        ///
        /// If an positive integer is supplied, that number of items are kept on the top of stack, discarding the rest
        /// Otherwise, drop all but the top 10 items
        #[arg(name="num")]
        num: Option<String>
    },

    /// Display items on the stack.
    Ls
}

/// Specify the stack subcommands supported by the program.
#[derive(Subcommand)]
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.
    #[command(after_help = TASK_DESC)]
    Rewrite {
        #[arg(name="task_desc")]
        task: Vec<String>
    }
}

/// Specify the stack subcommands supported by the program.
#[derive(Subcommand)]
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)]
    #[command(after_help = DATE_DESC)]
    Detail {
        /// Projects to report
        #[arg(name="proj", short, long="proj")]
        projs: Vec<String>,

        /// Date range specification
        #[arg(name="date_range")]
        dates: Vec<String>
    },

    /// Display a summary of the appropriate days' projects.
    // #[structopt(usage = "report summary [date_desc [end_date_desc]] [project_regex]...", after_help = DATE_DESC)]
    #[command(after_help = DATE_DESC)]
    Summary {
        /// Projects to report
        #[arg(name="proj", short, long="proj")]
        projs: Vec<String>,

        /// Date range specification
        #[arg(name="date_range")]
        dates: Vec<String>
    },

    /// 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)]
    #[command(after_help = DATE_DESC)]
    Hours {
        /// Projects to report
        #[arg(name="proj", short, long="proj")]
        projs: Vec<String>,

        /// Date range specification
        #[arg(name="date_range")]
        dates: Vec<String>
    },

    /// Display the zero duration events for each of the appropriate days and projects.
    // #[structopt(usage = "report events [date_desc [end_date_desc]] [project_regex]", after_help = DATE_DESC)]
    #[command(after_help = DATE_DESC)]
    Events {
        /// Boolean option for a more compact format.
        #[arg(short)]
        compact: bool,

        /// Projects to report
        #[arg(name="proj", short, long="proj")]
        projs: Vec<String>,

        /// Date range specification
        #[arg(name="date_range")]
        dates: Vec<String>
    },

    /// Display the intervals between zero duration events for each of the appropriate days and
    /// projects.
    // #[structopt(usage = "report intervals [date_desc [end_date_desc]] [project_regex]", after_help = DATE_DESC)]
    #[command(after_help = DATE_DESC)]
    Intervals {
        /// Projects to report
        #[arg(name="proj", short, long="proj")]
        projs: Vec<String>,

        /// Date range specification
        #[arg(name="date_range")]
        dates: Vec<String>
    },

    /// 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)]
    #[command(after_help = DATE_DESC)]
    Chart {
        /// Date range specification
        #[arg(name="date_range")]
        dates: Vec<String>
    }
}

/// Specify the subcommands supported by the program.
#[derive(Subcommand)]
enum Subcommands {
    /// Create the timelog directory and configuration.
    Init {
        /// Directory for logging the task events and stack. Default to `~/timelog` if not
        /// supplied.
        #[arg(name="dir")]
        dir: Option<String>
    },

    /// Start timing a new task.
    ///
    /// Stop timing the current task (if any) and start timing a new task.
    #[command(after_help = TASK_DESC)]
    Start {
        #[arg(name="task_desc")]
        task: Vec<String>
    },

    /// Stop timing the current task.
    Stop,

    /// 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)]
    #[command(after_help = TASK_DESC)]
    Push {
        #[arg(name="task_desc")]
        task: Vec<String>
    },

    /// 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.
    // #[command(arg(name="date_desc"))]
    #[command(after_help = DATE_DESC)]
    Ls {
        #[arg(name="date_desc")]
        date: Option<String>
    },

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

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

    /// 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
    #[command(subcommand)]
    Report(ReportCommands),

    /// Stack specific commands
    #[command(subcommand)]
    Stack(StackCommands),

    /// Task specific commands
    #[command(subcommand)]
    Task(TaskCommands),

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

/// Specify all of the command line parameters supported by the program.
#[derive(Parser)]
#[command(author, name="rtimelog", version, about, long_about = None, after_help = FULL_DESC.as_str())]
pub struct Cli {
    /// Specify a directory for logging the task events and stack.
    #[arg(long, name="dir")]
    dir: Option<PathBuf>,

    /// Specify the editor to use for modifying events.
    #[arg(long, name="program")]
    editor: Option<PathBuf>,

    /// Specify the path to the configuration file.
    #[arg(long, name="filepath")]
    conf: Option<PathBuf>,

    /// Specify the command to execute the browser.
    #[arg(long, name="program")]
    browser: Option<String>,

    /// Sub-commands which determine what actions to take
    #[command(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 config = self.config()?;
        match &self.cmd {
            Some(cmd) => cmd.run(&config, ExpandAlias::Yes),
            None => Subcommands::default_command(&config).run(&config, ExpandAlias::No)
        }
    }

    // Execute the action built from alias
    //
    // # 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.
    fn run_alias(&self, config: &Config, expand: ExpandAlias) -> Result<()> {
        match &self.cmd {
            Some(cmd) => cmd.run(config, expand),
            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 mut config = match &self.conf {
            Some(conf_file) => {
                Config::from_file(conf_file.to_str().ok_or(PathError::FilenameMissing)?)
            }
            None => Config::from_file(&DEFAULT_CONF)
        }
        .unwrap_or_default();

        if let Some(dir) = &self.dir {
            config.set_dir(
                dir.to_str()
                    .ok_or_else(|| PathError::InvalidPath(String::new(), String::new()))?
            );
        }
        if let Some(editor) = &self.editor {
            config.set_editor(editor.to_str().ok_or(PathError::FilenameMissing)?);
        }
        if let Some(browser) = &self.browser {
            config.set_browser(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<()> {
        #![allow(clippy::unit_arg)]
        use Subcommands::*;

        match &self {
            Init{dir} => Ok(cmd::initialize(config, dir)?),
            Start{task} => cmd::start_task(config, task),
            Stop => cmd::stop_task(config),
            Comment(VecString{args}) => cmd::add_comment(config, args),
            Event(VecString{args}) => cmd::add_event(config, args),
            Push{task} => cmd::push_task(config, task),
            Resume => cmd::resume_task(config),
            Pause => cmd::pause_task(config),
            Swap => cmd::swap_entry(config),
            Ls{date} => cmd::list_entries(config, date),
            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 => Ok(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].clone()))
            }
            .or_else(|e| process_deprecated_cmd(&args[0], e))
        }
    }

    fn default_command(config: &Config) -> Self {
        match config.defcmd() {
            "init" => Self::Init { dir: None },
            "start" => Self::Start { task: Vec::new() },
            "stop" => Self::Stop,
            "push" => Self::Push { task: Vec::new() },
            "resume" => Self::Resume,
            "pause" => Self::Pause,
            "swap" => Self::Swap,
            "ls" => Self::Ls { date: None },
            "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(String::as_str);

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

        let cmd = Cli::parse_from(
            once(BIN_NAME)
                .chain(expand.iter().map(String::as_str))
                .chain(args_iter)
        );
        cmd.run_alias(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 { num } => {
                let deflt = NonZeroU32::new(1).expect("Safe with literal");
                cmd::stack_drop(config, args::parse_nonzero(num, deflt)?)
            }
            Keep { num } => {
                let deflt = NonZeroU32::new(10).expect("Safe with literal");
                cmd::stack_keep(config, args::parse_nonzero(num, deflt)?)
            }
            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 { task } => cmd::rewrite_last_entry(config, task)
        }
    }
}

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{projs, dates} => cmd::report_daily(config, dates, projs),
            Summary{projs, dates} => cmd::report_summary(config, dates, projs),
            Hours{projs, dates} => cmd::report_hours(config, dates, projs),
            Events{compact, projs, dates} => cmd::report_events(config, dates, projs, *compact),
            Intervals{projs, dates} => cmd::report_intervals(config, dates, projs),
            Chart{dates} => cmd::chart_daily(config, dates)
        }
    }
}