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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! Implementations of the commands run by the CLI

use std::collections::HashSet;
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};

use xml::writer::{EmitterConfig, XmlEvent};

#[doc(inline)]
use crate::archive::Archiver;
use crate::buf_reader;
use crate::config::Config;
#[doc(inline)]
use crate::date::Date;
#[doc(inline)]
use crate::date::DateTime;
use crate::day::format_dur;
#[doc(inline)]
use crate::day::Day;
use crate::emit_xml;
#[doc(inline)]
use crate::error::Error;
#[doc(inline)]
use crate::error::PathError;
#[doc(inline)]
use crate::entry::{Entry, PROJECT_RE};
#[doc(inline)]
use crate::logfile::Logfile;
#[doc(inline)]
use crate::stack::Stack;
#[doc(inline)]
use crate::task_line_iter::TaskLineIter;
use crate::Result;

#[doc(inline)]
use crate::cli::args::DateRangeArgs;
use crate::cli::args::DayFilter;
#[doc(inline)]
use crate::cli::args::FilterArgs;
#[doc(inline)]
use crate::cli::args::PosIntArg;

/// The style definition for the chart HTML.
const STYLESHEET: &str = r#"
    .day {
      display: grid;
      grid-template-columns: 25% 1fr;
      grid-template-rows: 4em auto;
      padding-left: 0.5em;
      padding-bottom: 2em;
    }
    .day:nth-child(even) { background-color: #eee; }
    .day + .day {
      border-top: 1px solid black;
    }
    .tasks {
      display: grid;
      grid-template-columns: auto auto auto;
      grid-template-rows: repeat(auto-file);
    }
    @media screen and (min-width:400px) {
      .day { grid-template-columns: auto auto; }
      .tasks { grid-template-columns: auto; }
    }
    @media screen and (min-width:1024px) {
      .day { grid-template-columns: 40% 1fr; }
      .tasks { grid-template-columns: auto auto; }
    }
    @media screen and (min-width:1250px) {
      .day { grid-template-columns: 30% 1fr; }
      .tasks { grid-template-columns: auto auto auto; }
    }
    @media screen and (min-width:1400px) {
      .day { grid-template-columns: 25% 1fr; }
      .tasks { grid-template-columns: auto auto auto auto; }
    }
    .day .project {
      grid-column: 1;
      grid-row: 1 / span 2;
    }
    .day .tasks {
      grid-column: 2;
      grid-row: 2;
    }
    .project h2 { margin-bottom: 2em; }
    .piechart {
      display: grid;
      grid-template-columns: auto 1fr;
      grid-template-rows: auto;
    }
    .piechart .pie { grid-column: 1; grid-row: 1; }
    .piechart table { grid-column: 2; grid-row: 1; }
    .hours { grid-column: 1 / span 2; grid-row: 2; }
    .hours h3 { margin-left: 5em; margin-bottom: 0.5ex; }
    table.legend { margin-left: 0.75em; margin-bottom: auto; }
    .legend span { margin-left: 0.25em; }
    .legend td {
        display: flex;
        align-items: center;
    }
"#;

// Utility function to return the current stack file.
fn stack(config: &Config) -> Result<Stack> { Ok(Stack::new(&config.stackfile())?) }

// Utility function to return the current log file.
fn logfile(config: &Config) -> Result<Logfile> { Ok(Logfile::new(&config.logfile())?) }

/// Initialize the timelog directory supplied and create a `.timelogrc` config file.
/// If no directory is supplied default to `~/timelog`
///
/// ## Errors
///
/// - Return [`PathError::CantCreatePath`] if cannot create timelog directory
/// - Return [`PathError::FileAccess`] if we are unable to write the configuration.
/// - Return [`PathError::InvalidPath`] if the path is not valid
pub fn initialize(config: &Config, dir: &Option<String>) -> std::result::Result<(), PathError> {
    let mut config = config.clone();
    let dir = match dir {
        Some(s) => s.as_str(),
        None => config.dir(),
    };
    fs::create_dir_all(dir)
        .map_err(|e| PathError::CantCreatePath(dir.to_string(), e.to_string()))?;

    let candir = fs::canonicalize(dir)
        .map_err(|e| PathError::InvalidPath(dir.to_string(), e.to_string()))?;
    config.set_dir(candir.to_str().unwrap());
    config.create()?;
    Ok(())
}

/// Start a task.
/// Add an entry to the logfile marked with the current date and time and the supplied task
/// description.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the `file` has no filename.
/// - Return [`PathError::InvalidPath`] if the path part of `file` is not a valid path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened or created.
/// - Return [`PathError::FileWrite`] if the function fails to append to the file.
pub fn start_task(config: &Config, args: &[String]) -> Result<()> {
    let logfile = logfile(config)?;
    Ok(logfile.add_task(&args.join(" "))?)
}

/// Stop a task.
/// Add the 'stop' entry to the logfile marked with the current date and time.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file has no filename.
/// - Return [`PathError::InvalidPath`] if the path part of log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the log file cannot be opened or created.
/// - Return [`PathError::FileWrite`] if the function fails to append to the log file.
pub fn stop_task(config: &Config) -> Result<()> {
    let logfile = logfile(config)?;
    Ok(logfile.add_task("stop")?)
}

/// Add a comment line to the logfile
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file has no filename.
/// - Return [`PathError::InvalidPath`] if the path part of log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the log file cannot be opened or created.
/// - Return [`PathError::FileWrite`] if the function fails to append to the log file.
pub fn add_comment(config: &Config, args: &[String]) -> Result<()> {
    let logfile = logfile(config)?;
    Ok(logfile.add_comment(&args.join(" "))?)
}

/// Add a zero duration event to the logfile
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file has no filename.
/// - Return [`PathError::InvalidPath`] if the path part of log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the log file cannot be opened or created.
/// - Return [`PathError::FileWrite`] if the function fails to append to the log file.
pub fn add_event(config: &Config, args: &[String]) -> Result<()> {
    let logfile = logfile(config)?;
    Ok(logfile.add_event(&args.join(" "))?)
}

/// Start a task and saving the current entry description to the stack.
///
/// Add the task entry description to the logfile marked with the current date and time.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file or stack file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log or stack file is not a valid
/// path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened or created.
/// - Return [`PathError::FileWrite`] if the function fails to append to the file.
pub fn push_task(config: &Config, args: &[String]) -> Result<()> {
    let logfile = logfile(config)?;
    let entry = logfile.last_entry()?;
    if entry.entry_text().is_empty() {
        return Ok(());
    }

    let stack = stack(config)?;
    stack.push(&entry.entry_text())?;

    Ok(logfile.add_task(&args.join(" "))?)
}

/// Resume the previous task entry by popping it off the stack and starting that task at the
/// current date and time.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file or stack file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log or stack file is not a valid
/// path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened or created.
/// - Return [`PathError::FileWrite`] if the function fails to append to the file.
pub fn resume_task(config: &Config) -> Result<()> {
    let stack = stack(config)?;
    if let Some(task) = stack.pop() {
        logfile(config)?.add_task(&task)?;
    }
    Ok(())
}

/// Pause the current task by placing it on the stack and stopping timing.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file or stack file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log or stack file is not a valid
/// path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened or created.
/// - Return [`PathError::FileWrite`] if the function fails to append to the file.
pub fn pause_task(config: &Config) -> Result<()> { push_task(config, &["stop".to_owned()]) }

/// Discard the most recent entry in the logfile.
///
/// ## Errors
///
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
pub fn discard_last_entry(config: &Config) -> Result<()> {
    logfile(config)?.discard_line().map_err(|e| e.into())
}

/// Reset the datestamp on the most recent entry to now.
///
/// ## Errors
///
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
pub fn reset_last_entry(config: &Config) -> Result<()> {
    logfile(config)?.reset_last_entry()
}

/// Replace the task text on the most recent entry.
///
/// ## Errors
///
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
pub fn rewrite_last_entry(config: &Config, args: &[String]) -> Result<()> {
    logfile(config)?.rewrite_last_entry(&args.join(" "))
}

/// Mark the most recent entry as ignored
///
/// ## Errors
///
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
pub fn ignore_last_entry(config: &Config) -> Result<()> {
    logfile(config)?.ignore_last_entry()
}

/// List the entries for a particular date, or today if none is supplied.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
pub fn list_entries(config: &Config, date: &Option<String>) -> Result<()> {
    let file = logfile(config)?.open()?;

    let start = Date::parse(date.as_ref().unwrap_or(&String::from("today")))?;
    let end   = &start.succ().to_string();
    let start = start.to_string();

    for line in TaskLineIter::new(
        BufReader::new(file)
            .lines()
            .take_while(|ol| ol.is_ok())
            .map(|ol| ol.unwrap()),
        &start,
        end,
    )? {
        println!("{}", line);
    }
    Ok(())
}

/// List the projects in the logfile.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
pub fn list_projects(config: &Config) -> Result<()> {
    let mut projects: HashSet<String> = HashSet::new();

    let file = logfile(config)?.open()?;
    BufReader::new(file)
        .lines()
        .take_while(|ol| ol.is_ok())
        .map(|ol| ol.unwrap())
        .for_each(|ln| {
            if let Some(proj) = PROJECT_RE.captures(&ln) {
                projects.insert(proj.get(1).unwrap().as_str().to_owned());
            }
        });

    let mut names: Vec<String> = projects.iter().map(|p| p.to_string()).collect();
    names.as_mut_slice().sort();
    names.iter().for_each(|p| println!("{}", p));

    Ok(())
}

/// List the items on the stack, most recent first.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log or stack file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log or stack file is not a valid
/// path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
pub fn list_stack(config: &Config) -> Result<()> {
    let stackfile = stack(config)?;
    if !stackfile.exists() {
        return Ok(());
    }

    let file = stackfile.open()?;
    let mut lines: Vec<String> = BufReader::new(file)
        .lines()
        .take_while(|ol| ol.is_ok())
        .map(|ol| ol.unwrap())
        .collect();
    lines.as_mut_slice().reverse();
    lines.iter().for_each(|ln| println!("{}", ln));

    Ok(())
}

/// Launch the configured editor to edit the logfile.
///
/// ## Errors
///
/// - Return [`Error::EditorFailed`] if unable to run the editor.
pub fn edit(config: &Config) -> Result<()> {
    Command::new(config.editor())
        .arg(config.logfile())
        .status()
        .map_err(|e| Error::EditorFailed(config.editor().to_string(), e.to_string()))?;

    Ok(())
}

// Utility function for creating a day and initializing it if a previous entry was still open.
fn start_day(start: &str, prev: &Option<Entry>) -> Result<Day> {
    let mut day = Day::new(start)?;
    if let Some(p) = prev.as_ref() {
        day.start_day(p)?;
    }
    Ok(day)
}

// Generate a report from the entries in the logfile based on the supplied `args`.
//
// Uses the supplied filter object to apply appropriate filtering conditions that
// select the entries of interest from the logfile. These entries are collected into
// [`Day`]s which are then reported using the supplied function `f`.
//
// The purpose of this method is to handle all of the boring grunt-work of finding the
// entries in question and collecting them together to generate one or more daily reports.
//
// ## Errors
//
// - Return [`PathError::FilenameMissing`] if the log file is missing.
// - Return [`PathError::InvalidPath`] if the path part of the log file is not a valid path.
// - Return [`PathError::FileAccess`] if the file cannot be opened.
// - Return [`Error::BadProjectFilter`] if the supplied project Regexes are not valid
// - Return [`Error::WrongDateOrder`] if the start date is not before the end date
fn report<F>(config: &Config, filter: &dyn DayFilter, mut f: F) -> Result<()>
where
    F: FnMut(&Day) -> Result<()>,
{
    // let filter = FilterArgs::new(args)?;
    let start = filter.start();

    let file = logfile(config)?.open()?;
    let mut prev: Option<Entry> = TaskLineIter::new( buf_reader(file), &start, &filter.end())?
        .last_line_before()
        .and_then(|l| Entry::from_line(&l).ok());

    let mut day = start_day(&start, &prev)?;

    let file = logfile(config)?.open()?;
    for line in TaskLineIter::new(buf_reader(file), &start, &filter.end())? {
        let entry = Entry::from_line(&line)?;
        let stamp = entry.stamp();

        if day.date_stamp() != stamp {
            if let Some(filtered) = filter.filter_day(day) {
                f(&filtered)?;
            }

            day = start_day(&stamp, &prev)?;
        }
        day.add_entry(&entry)?;
        prev = Some(entry);
    }
    day.finish()?;

    if let Some(filtered) = filter.filter_day(day) {
        f(&filtered)?;
    }
    Ok(())
}

// Return a file object for the report file.
fn report_file(filename: &str) -> Result<fs::File> {
    Ok(OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&filename)
        .map_err(|e| PathError::FileAccess(filename.to_string(), e.to_string()))?)
}

// Display the chart in the configured browser.
fn launch_chart(config: &Config, filename: &str) -> Result<()> {
    Command::new(config.browser())
        .arg(filename)
        .stderr(Stdio::null())    // discard output, for odd chromium message
        .status()
        .map_err(|e| Error::EditorFailed(config.browser().to_string(), e.to_string()))?;
    Ok(())
}

/// Create a graphical chart for each supplied day.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
/// - Return [`Error::BadProjectFilter`] if the supplied project Regexes are not valid
/// - Return [`Error::WrongDateOrder`] if the start date is not before the end date
pub fn chart_daily(config: &Config, args: &[String]) -> Result<()> {
    let filename = config.reportfile();
    let mut file = report_file(&filename)?;
    let mut w = EmitterConfig::new()
        .perform_indent(true)
        .write_document_declaration(false)
        .create_writer(&mut file);
    emit_xml!(&mut w, html => {
        emit_xml!(w, head => {
            emit_xml!(w, title; "Daily Timelog Report")?;
            emit_xml!(w, style, type: "text/css"; STYLESHEET)
        })?;
        emit_xml!(w, body => {
            report(config, &DateRangeArgs::new(args)?, |day|
                day.daily_chart().write(&mut w)
            )
        })
    })?;

    launch_chart(config, &filename)
}

/// Print the full daily report for each supplied day.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
/// - Return [`Error::BadProjectFilter`] if the supplied project Regexes are not valid
/// - Return [`Error::WrongDateOrder`] if the start date is not before the end date
pub fn report_daily(config: &Config, args: &[String]) -> Result<()> {
    report(config, &FilterArgs::new(args)?, |day| {
        print!("{}", day.detail_report());
        Ok(())
    })
}

/// Print the summary report for each supplied day.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
/// - Return [`Error::BadProjectFilter`] if the supplied project Regexes are not valid
/// - Return [`Error::WrongDateOrder`] if the start date is not before the end date
pub fn report_summary(config: &Config, args: &[String]) -> Result<()> {
    report(config, &FilterArgs::new(args)?, |day| {
        print!("{}", day.summary_report());
        Ok(())
    })
}

/// Print the hourly report for each supplied day.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
/// - Return [`Error::BadProjectFilter`] if the supplied project Regexes are not valid
/// - Return [`Error::WrongDateOrder`] if the start date is not before the end date
pub fn report_hours(config: &Config, args: &[String]) -> Result<()> {
    report(config, &FilterArgs::new(args)?, |day| {
        print!("{}", day.hours_report());
        Ok(())
    })
}

/// Print a report of the zero duration events for each supplied day.
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
/// - Return [`Error::BadProjectFilter`] if the supplied project Regexes are not valid
/// - Return [`Error::WrongDateOrder`] if the start date is not before the end date
pub fn report_events(config: &Config, args: &[String]) -> Result<()> {
    report(config, &DateRangeArgs::new(args)?, |day| {
        print!("{}", day.event_report());
        Ok(())
    })
}

/// Display the current task
///
/// ## Errors
///
/// - Return [`PathError::FilenameMissing`] if the log file is missing.
/// - Return [`PathError::InvalidPath`] if the path part of the log file is not a valid path.
/// - Return [`PathError::FileAccess`] if the file cannot be opened.
pub fn current_task(config: &Config) -> Result<()> {
    let entry = logfile(config)?.last_entry()?;
    if entry.is_stop() {
        println!("Not in entry.");
    }
    else {
        println!("{}", &entry);
        let dur = DateTime::now().sub(&entry.date_time())?;
        println!("Duration: {}", format_dur(&dur));
    }

    Ok(())
}

/// Archive the first year from the logfile (if not the current year).
///
/// ## Errors
///
/// - Return [`Error::PathError`] for any error accessing the log or archive files.
pub fn archive_year(config: &Config) -> Result<()> {
    match Archiver::new(config).archive()? {
        None => println!("Nothing to archive"),
        Some(year) => println!("{} archived", year),
    }
    Ok(())
}

/// List the aliases from the config file.
pub fn list_aliases(config: &Config) -> Result<()> {
    let mut aliases: Vec<&String> = config.alias_names().collect();
    aliases.as_mut_slice().sort();
    let maxlen: usize = aliases.iter().map(|a| a.len()).max().unwrap_or_default();
    println!("Aliases:");
    for alias in aliases {
        println!(
            "  {1:0$} : {2}",
            &maxlen,
            &alias,
            config.alias(alias).unwrap()
        );
    }

    Ok(())
}

/// Check the logfile for any problems
pub fn check_logfile(config: &Config) -> Result<()> {
    let problems = logfile(config)?.problems();

    if problems.is_empty() {
        println!("No problems found");
    }
    else {
        for p in problems {
            println!("{}", p);
        }
    }

    Ok(())
}

/// Swap the current task with the top item on the stack.
pub fn swap_entry(config: &Config) -> Result<()> {
    let stack = stack(config)?;
    let logfile = logfile(config)?;
    if let Some(curr_task) = logfile.last_line() {
        if let Some(task) = stack.pop() {
            logfile.add_task(&task)?;
        }
        let entry = Entry::from_line(&curr_task)?;
        if !entry.is_stop() {
            stack.push(&entry.entry_text())?;
        }
    }
    Ok(())
}

/// Remove all but the top items on the stack
pub fn stack_keep(config: &Config, num: PosIntArg) -> Result<()> {
    let stack = stack(config)?;
    stack.keep(num.val())
}

/// Clear the stack
pub fn stack_clear(config: &Config) -> Result<()> {
    let stack = stack(config)?;
    stack.clear().map_err(|e| e.into())
}

/// Clear the stack
pub fn stack_drop(config: &Config, num: PosIntArg) -> Result<()> {
    let stack = stack(config)?;
    stack.drop(num.val())
}