rtimelog 1.1.1

System for tracking time in a text-log-based format.
Documentation
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! Interface to the timelog file for the timelog application.
//!
//! # Examples
//!
//! ```rust
//! use timelog::logfile::Logfile;
//! # fn main() -> Result<(), timelog::Error> {
//! let timelog = Logfile::new("./timelog.txt" )?;
//!
//! let task = timelog.last_line();
//! println!("{:?}", task);
//!
//! timelog.add_task("+Project @Task More detail");
//! #   std::fs::remove_file(timelog.clone_file()).expect("Oops");
//! #   Ok(())
//! # }
//! ```

use std::fmt::{self, Display};
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::num::NonZeroU32;
use std::path::Path;
use std::result;
use std::time::Duration;

use crate::buf_reader;
#[doc(inline)]
use crate::date::{DateTime, Time};
#[doc(inline)]
use crate::entry::{Entry, EntryError, EntryKind};
#[doc(inline)]
use crate::error::Error;
#[doc(inline)]
use crate::error::PathError;
#[doc(inline)]
use crate::file;

const TWELVE_HOURS: u64 = 12 * 3600;

/// Problems that can be found in a logfile
///
/// Problems contain the line number where the problem was discovered, except FileAccess.
#[derive(Debug, Eq, PartialEq)]
pub enum Problem {
    FileAccess,
    BlankLine(usize),
    InvalidTimeStamp(usize),
    MissingTask(usize),
    InvalidMarker(usize),
    EventsOrder(usize),
    EventLength(usize)
}

impl Display for Problem {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let (msg, lineno) = match self {
            Self::FileAccess => return write!(f, "Error: Unable to open file"),
            Self::BlankLine(n) => ("Error: Blank entry line", n),
            Self::InvalidTimeStamp(n) => ("Error: Time stamp is invalid or missing", n),
            Self::MissingTask(n) => ("Error: Task missing from entry line", n),
            Self::InvalidMarker(n) => ("Error: Unrecognized marker character", n),
            Self::EventsOrder(n) => ("Error: Entries out of order", n),
            Self::EventLength(n) => ("Warn: Very long interval, possibly missing stop", n)
        };
        write!(f, "Line {lineno}: {msg}")
    }
}

impl Problem {
    fn from_error(err: EntryError, lineno: usize) -> Self {
        match err {
            EntryError::BlankLine => Self::BlankLine(lineno),
            EntryError::InvalidTimeStamp => Self::InvalidTimeStamp(lineno),
            EntryError::MissingTask => Self::MissingTask(lineno),
            EntryError::InvalidMarker => Self::InvalidMarker(lineno)
        }
    }
}

/// A [`Logfile`] type that wraps the timelog log file.
#[derive(Debug)]
pub struct Logfile(String);

impl Logfile {
    /// Creates a [`Logfile`] object wrapping the supplied file.
    ///
    /// # 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::InvalidTimelogPath`] if stack path is invalid.
    pub fn new(file: &str) -> result::Result<Self, PathError> {
        file::canonical_filename(file, file::FileKind::LogFile).map(Self)
    }

    /// Open the log file, return a [`File`].
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if unable to open the file.
    pub fn open(&self) -> result::Result<File, PathError> {
        File::open(&self.0).map_err(|e| PathError::FileAccess(self.0.clone(), e.to_string()))
    }

    /// Clone the filename
    pub fn clone_file(&self) -> String { self.0.clone() }

    /// Return `true` if the timelog file exists
    pub fn exists(&self) -> bool { Path::new(&self.0).exists() }

    /// Append the supplied line (including time stamp) to the timelog file
    ///
    /// # Errors
    ///
    /// - 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 add_line(&self, entry: &str) -> result::Result<(), PathError> {
        let file = file::append_open(&self.0)?;
        let mut stream = io::BufWriter::new(file);
        writeln!(&mut stream, "{entry}")
            .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
        stream
            .flush()
            .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
        Ok(())
    }

    /// Append the supplied task to the timelog file
    ///
    /// # Errors
    ///
    /// - 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 add_task(&self, task: &str) -> result::Result<(), PathError> {
        self.add_entry(&Entry::new(task, DateTime::now()))
    }

    /// Append the supplied [`Entry`] to the timelog file
    ///
    /// # Errors
    ///
    /// - 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 add_entry(&self, entry: &Entry) -> result::Result<(), PathError> {
        let line = format!("{entry}");
        self.add_line(&line)
    }

    /// Add a comment line to the timelog file
    ///
    /// # Errors
    ///
    /// - 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 add_comment(&self, comment: &str) -> result::Result<(), PathError> {
        let file = file::append_open(&self.0)?;
        let mut stream = io::BufWriter::new(file);
        writeln!(&mut stream, "# {comment}")
            .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
        stream
            .flush()
            .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
        Ok(())
    }

    /// Add a zero duration event to the timelog file
    ///
    /// # Errors
    ///
    /// - 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 add_event(&self, line: &str) -> result::Result<(), PathError> {
        self.add_entry(&Entry::new_marked(line, DateTime::now(), EntryKind::Event))
    }

    /// Remove the most recent task from the logfile.
    ///
    /// # Errors
    ///
    /// - 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 discard_line(&self) -> result::Result<(), PathError> {
        let mut file = file::rw_open(&self.0)?;
        file::pop_last_line(&mut file);
        Ok(())
    }

    // Wrapper method that extracts the latest entry, calls a function on it
    // to produce a new entry and adds that one to replace the original.
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if the file cannot be opened or created.
    /// - Return [`PathError::FileWrite`] if the function fails to append to the file.
    fn change_last_entry<F>(&self, func: F) -> result::Result<(), Error>
    where
        F: FnOnce(Entry) -> result::Result<Entry, Error>
    {
        let mut file = file::rw_open(&self.0)?;
        if let Some(line) = file::pop_last_line(&mut file) {
            let old_entry = Entry::from_line(&line)?;
            if old_entry.is_stop() { return Err(Error::InvalidStopEdit); }
            if old_entry.is_ignore() { return Err(Error::InvalidIgnoreEdit); }
            match func(old_entry) {
                Ok(entry) => self.add_entry(&entry)?,
                Err(e) => {
                    self.add_line(&line)?;
                    return Err(e);
                }
            }
        }
        Ok(())
    }

    /// Reset most recent entry to current date time.
    ///
    /// # Errors
    ///
    /// - 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 reset_last_entry(&self) -> result::Result<(), Error> {
        self.change_last_entry(|entry| Ok(entry.change_date_time(DateTime::now())))
    }

    /// Ignore the most recent entry to current date time.
    ///
    /// # Errors
    ///
    /// - 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 ignore_last_entry(&self) -> result::Result<(), Error> {
        self.change_last_entry(|entry| Ok(entry.ignore()))
    }

    /// Rewrite the text of the most recent entry.
    ///
    /// # Errors
    ///
    /// - 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 rewrite_last_entry(&self, task: &str) -> result::Result<(), Error> {
        self.change_last_entry(|entry| Ok(entry.change_text(task)))
    }

    /// Reset the time of the most recent entry.
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if the file cannot be opened or created.
    /// - Return [`PathError::FileWrite`] if the function fails to append to the file.
    /// - Return [`Error::InvalidWasArgument`] if supplied time is not parsable.
    pub fn retime_last_entry(&self, time: Time) -> result::Result<(), Error> {
        self.change_last_entry(|entry| {
            let dt = DateTime::new_from_date_time(entry.date(), time);
            Ok(entry.change_date_time(dt))
        })
    }

    /// Shift the time of the most recent entry back the specified number of minutes.
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if the file cannot be opened or created.
    /// - Return [`PathError::FileWrite`] if the function fails to append to the file.
    /// - Return [`Error::InvalidWasArgument`] if supplied time is not parsable.
    pub fn rewind_last_entry(&self, minutes: NonZeroU32) -> result::Result<(), Error> {
        let dur = Duration::from_secs(u64::from(minutes.get()) * 60);
        self.change_last_entry(|entry| {
            let dt = (entry.date_time() - dur)?;
            Ok(entry.change_date_time(dt))
        })
    }

    /// Return the unfiltered last line of the timelog file or `None` if we can't.
    pub fn raw_last_line(&self) -> Option<String> {
        if self.exists() {
            let file = File::open(&self.0).ok()?;
            io::BufReader::new(file).lines().map_while(result::Result::ok).last()
        }
        else {
            None
        }
    }

    /// Return the last line of the timelog file or `None` if we can't.
    pub fn last_line(&self) -> Option<String> {
        if self.exists() {
            let file = File::open(&self.0).ok()?;
            io::BufReader::new(file)
                .lines()
                .map_while(Result::ok)
                .filter(|ln| !ln.starts_with('#') && EntryKind::from_entry_line(ln).is_start())
                .last()
        }
        else {
            None
        }
    }

    /// Return the last line of the timelog file as an [`Entry`].
    ///
    /// # Errors
    ///
    /// - Return [`Error::InvalidEntryLine`] if the line is not correctly formatted.
    pub fn last_entry(&self) -> result::Result<Entry, Error> {
        Entry::from_line(&self.last_line().unwrap_or_default()).map_err(Into::into)
    }

    /// Return a Vec of problems found with the file.
    ///
    /// If the Vec is empty, there are no problems.
    pub fn problems(&self) -> Vec<Problem> {
        if !self.exists() { return Vec::new(); }
        let Ok(file) = self.open() else {
            return vec![Problem::FileAccess];
        };

        let mut problems: Vec<Problem> = Vec::new();
        let mut iter = buf_reader(file);
        let Some(line) = iter.next() else { return problems; };
        let mut prev = match Entry::from_line(&line) {
            Ok(ev) => ev,
            Err(e) => {
                problems.push(Problem::from_error(e, 1));
                return problems;
            }
        };
        let twelve_hour_dur = Duration::from_secs(TWELVE_HOURS);
        for (line, lineno) in iter.zip(2..) {
            match Entry::from_line(&line) {
                Ok(ev) => {
                    if prev.date_time() > ev.date_time() {
                        problems.push(Problem::EventsOrder(lineno));
                    }
                    else if !prev.is_stop() && !prev.is_event() {
                        // Should be >= 0, because of previous conditional.
                        let diff = (ev.date_time() - prev.date_time()).unwrap_or_default();
                        if diff > twelve_hour_dur {
                            problems.push(Problem::EventLength(lineno));
                        }
                    }
                    prev = ev;
                }
                Err(e) => problems.push(Problem::from_error(e, lineno))
            }
        }

        problems
    }
}

#[cfg(test)]
mod tests {
    use std::fs::{canonicalize, OpenOptions};

    use assert2::{assert, let_assert};
    use nzliteral::nzliteral;
    use regex::Regex;
    use rstest::rstest;
    use tempfile::TempDir;

    use super::*;
    use crate::date::Date;

    fn make_timelog(lines: &[String]) -> (TempDir, String) {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("timelog.txt");
        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(file) = OpenOptions::new()
            .create(true)
            .append(true)
            .open(filename));
        let mut stream = io::BufWriter::new(file);
        lines
            .iter()
            .for_each(|line| writeln!(&mut stream, "{line}").expect("Hardcoded value"));
        let_assert!(Ok(_) = stream.flush());
        (tmpdir, filename.to_string())
    }

    fn touch_timelog() -> (TempDir, String) { make_timelog(&[String::new()]) }

    // new

    #[test]
    fn test_new() {
        let_assert!(Ok(logfile) = Logfile::new("./foo.txt"));
        let expected = canonicalize(".")
            .map(|mut pb| {
                pb.push("foo.txt");
                pb.to_str().expect("Hardcoded value").to_string()
            })
            .unwrap_or("".to_string());
        assert!(logfile.clone_file() == expected);
    }

    #[test]
    fn test_new_empty_name() {
        let_assert!(Err(err) = Logfile::new(""));
        assert!(err == PathError::FilenameMissing);
    }

    #[test]
    fn test_new_bad_path() {
        let_assert!(Err(err) = Logfile::new("./xyzzy/foo.txt"));
        assert!(err == PathError::InvalidPath(
            "./xyzzy/foo.txt".to_string(),
            "No such file or directory (os error 2)".to_string()
        ));
    }

    // exists

    #[test]
    fn test_exists_false() {
        let_assert!(Ok(logfile) = Logfile::new("./foo.txt"));
        assert!(!logfile.exists());
    }

    #[test]
    fn test_exists_true() {
        let (_tmpdir, filename) = touch_timelog();
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.exists());
    }

    // add

    #[test]
    fn test_add_line() {
        let (_tmpdir, filename) = touch_timelog();
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let_assert!(Ok(_) = logfile.add_line("2021-11-18 18:00:00 +project @task"));
        let_assert!(Some(line) = logfile.last_line());
        assert!(line == String::from("2021-11-18 18:00:00 +project @task"));
    }

    #[test]
    fn test_add_task() {
        let (_tmpdir, filename) = touch_timelog();
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let_assert!(Ok(_) = logfile.add_task("+project @task"));
        let_assert!(Some(line) = logfile.last_line());
        assert!(line.ends_with("+project @task"));
    }

    #[test]
    fn test_add_entry() {
        let (_tmpdir, filename) = touch_timelog();
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let_assert!(Ok(datetime) = "2021-11-18 18:00:00".parse::<DateTime>());
        let entry = Entry::new("+project @task", datetime);
        let_assert!(Ok(_) = logfile.add_entry(&entry));
        let_assert!(Some(line) = logfile.last_line());
        assert!(line == String::from("2021-11-18 18:00:00 +project @task"));
    }

    #[test]
    fn test_add_comment() {
        let (_tmpdir, filename) = touch_timelog();
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let_assert!(Ok(_) = logfile.add_comment("This is a test"));
        let_assert!(Some(line) = logfile.raw_last_line());
        assert!(line == String::from("# This is a test"));
    }

    #[test]
    fn test_add_event() {
        let (_tmpdir, filename) = touch_timelog();
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        #[rustfmt::skip]
        let_assert!(Ok(expect) = Regex::new(r"\A\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\^something happened"));
        let_assert!(Ok(_) = logfile.add_event("something happened"));
        let_assert!(Some(last_line) = logfile.raw_last_line());
        assert!(expect.is_match(&last_line));
    }

    // discard_line

    #[test]
    fn test_discard_line() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.discard_line().is_ok());
        let_assert!(Some(line) = logfile.last_line());
        assert!(line == "2021-11-18 17:04:02 +bar".to_string());
    }

    // change entry

    #[test]
    fn test_reset_last_entry() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.reset_last_entry().is_ok());
        let_assert!(Ok(entry) = logfile.last_entry());
        assert!(entry.entry_text() == "+baz");
        assert!(entry.date() == Date::today());
    }

    #[test]
    fn test_ignore_last_entry() {
        let (_tmpdir, filename) = make_timelog(&vec![
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
        ]);
        // After ignore, second to last line will be the last returned.
        let_assert!(Ok(expect) = Entry::from_line("2021-11-18 17:04:02 +bar"));

        let logfile = Logfile::new(&filename).expect("Hardcoded value");
        let_assert!(Ok(_) = logfile.ignore_last_entry());
        let_assert!(Ok(last) = logfile.last_entry());
        assert!(last == expect);
    }

    #[test]
    fn test_rewrite_last_entry() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
        ]);
        let_assert!(Ok(expect) = Entry::from_line("2021-11-18 17:08:04 +foobar @Frond"));
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.rewrite_last_entry("+foobar @Frond").is_ok());
        let_assert!(Ok(last) = logfile.last_entry());
        assert!(last == expect);
    }

    #[test]
    fn test_retime_last_entry() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
        ]);
        let_assert!(Ok(expect) = Entry::from_line("2021-11-18 16:01:00 +baz"));
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let_assert!(Some(time) = Time::from_hms_opt(16, 1, 0));
        assert!(logfile.retime_last_entry(time).is_ok());
        let_assert!(Ok(last) = logfile.last_entry());
        assert!(last == expect);
    }

    #[test]
    fn test_rewind_last_entry() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
        ]);
        let_assert!(Ok(expect) = Entry::from_line("2021-11-18 16:57:04 +baz"));
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let minutes = nzliteral!(11);
        assert!(logfile.rewind_last_entry(minutes).is_ok());
        let_assert!(Ok(last) = logfile.last_entry());
        assert!(last == expect);
    }

    // last_line

    #[test]
    fn test_last_line_missing() {
        let (_tmpdir, filename) = touch_timelog();
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let_assert!(Some(last) = logfile.last_line());
        assert!(last == String::new());
    }

    #[test]
    fn test_last_line_empty() {
        let (_tmpdir, filename) = make_timelog(&[]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.last_line().is_none());
    }

    #[test]
    fn test_last_line_lines() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let_assert!(Some(last) = logfile.last_line());
        assert!(last == "2021-11-18 17:08:04 +baz".to_string());
    }

    #[test]
    fn test_last_entry() {
        let (_tmpdir, filename) = make_timelog(&[]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let_assert!(Err(err) = logfile.last_entry());
        assert!(err == Error::from(EntryError::BlankLine));
    }

    #[test]
    fn test_last_entry_lines() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        let_assert!(Ok(expected) = Entry::from_line("2021-11-18 17:08:04 +baz"));
        let_assert!(Ok(last) = logfile.last_entry());
        assert!(last == expected);
    }

    #[test]
    fn test_problems_all_good() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
            "2021-11-18 17:08:04 stop".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems().is_empty());
    }

    #[test]
    fn test_problems_all_good_with_comments() {
        let (_tmpdir, filename) = make_timelog(&[
            "# Start of file".to_string(),
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "# Middle of file".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
            "2021-11-18 17:08:04 stop".to_string(),
            "# End of file".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems().is_empty());
    }

    #[test]
    fn test_problems_blank_line() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems() == vec![Problem::BlankLine(2)]);
    }

    #[test]
    fn test_problems_bad_date() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-1-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
            "2021-11-18 17:08:04 stop".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems() == vec![Problem::InvalidTimeStamp(1)]);
    }

    #[test]
    fn test_problems_bad_time() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 7:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
            "2021-11-18 17:08:04 stop".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems() == vec![Problem::InvalidTimeStamp(1)]);
    }

    #[test]
    fn test_problems_missing_timestamp() {
        let (_tmpdir, filename) = make_timelog(&[
            "+foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
            "2021-11-18 17:08:04 stop".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems() == vec![Problem::InvalidTimeStamp(1)]);
    }

    #[test]
    fn test_problems_no_task() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 ".to_string(),
            "2021-11-18 17:08:04 stop".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems() == vec![Problem::MissingTask(3)]);
    }

    #[test]
    fn test_problems_unknown_marker() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02*+bar".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
            "2021-11-18 17:08:04 stop".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems() == vec![Problem::InvalidMarker(2)]);
    }

    #[test]
    fn test_problems_entry_unordered() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:08:04 +baz".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-18 17:08:04 stop".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems() == vec![Problem::EventsOrder(3)]);
    }

    #[rstest]
    #[case(Problem::BlankLine(2), "Line 2: Error: Blank entry line")]
    #[case(Problem::InvalidTimeStamp(3), "Line 3: Error: Time stamp is invalid or missing")]
    #[case(Problem::MissingTask(5), "Line 5: Error: Task missing from entry line")]
    #[case(Problem::InvalidMarker(5), "Line 5: Error: Unrecognized marker character")]
    #[case(Problem::EventsOrder(9), "Line 9: Error: Entries out of order")]
    #[case(Problem::EventLength(13), "Line 13: Warn: Very long interval, possibly missing stop")]
    fn test_problem_fmt(#[case]prob: Problem, #[case]display: &str) {
        assert!(prob.to_string() == String::from(display));
    }

    #[test]
    fn test_problems_open_ended() {
        let (_tmpdir, filename) = make_timelog(&[
            "2021-11-18 17:01:01 +foo".to_string(),
            "2021-11-18 17:04:02 +bar".to_string(),
            "2021-11-19 17:08:04 +baz".to_string(),
            "2021-11-19 17:08:04 stop".to_string(),
        ]);
        let_assert!(Ok(logfile) = Logfile::new(&filename));
        assert!(logfile.problems() == vec![Problem::EventLength(3)]);
    }
}