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
use std::cmp::Ordering;
use std::fmt::{self, Display};
use std::fs::{canonicalize, File};
use std::io::prelude::*;
use std::io::{BufRead, BufReader, BufWriter};
use std::path::{Path, PathBuf};
use std::time::Duration;
#[doc(inline)]
use crate::date::DateTime;
#[doc(inline)]
use crate::error::Error;
#[doc(inline)]
use crate::error::PathError;
#[doc(inline)]
use crate::entry::{Entry, EntryError, EntryKind};
#[doc(inline)]
use crate::file::{append_open, pop_last_line, rw_open};
use crate::buf_reader;
const TWELVE_HOURS: u64 = 12 * 3600;
#[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 event, 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),
}
}
}
#[derive(Debug)]
pub struct Logfile(String);
impl Logfile {
pub fn new(file: &str) -> std::result::Result<Self, PathError> {
if file.is_empty() {
return Err(PathError::FilenameMissing);
}
let mut dir = PathBuf::from(file);
let filename = dir
.file_name()
.ok_or(PathError::FilenameMissing)?
.to_os_string();
dir.pop();
let mut candir = canonicalize(dir)
.map_err(|e| PathError::InvalidPath(file.to_owned(), e.to_string()))?;
candir.push(filename);
Ok(Self(candir.to_str().unwrap().to_owned()))
}
pub fn open(&self) -> std::result::Result<File, PathError> {
File::open(&self.0).map_err(|e| PathError::FileAccess(self.0.to_owned(), e.to_string()))
}
pub fn clone_file(&self) -> String { self.0.to_owned() }
pub fn exists(&self) -> bool { Path::new(&self.0).exists() }
pub fn add_line(&self, entry: &str) -> std::result::Result<(), PathError> {
let file = append_open(&self.0)?;
let mut stream = 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(())
}
pub fn add_task(&self, task: &str) -> std::result::Result<(), PathError> {
self.add_entry(&Entry::new(task, DateTime::now()))
}
pub fn add_entry(&self, entry: &Entry) -> std::result::Result<(), PathError> {
let line = format!("{}", entry);
self.add_line(&line)
}
pub fn add_comment(&self, comment: &str) -> std::result::Result<(), PathError> {
let file = append_open(&self.0)?;
let mut stream = 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(())
}
pub fn add_event(&self, line: &str) -> std::result::Result<(), PathError> {
self.add_entry(&Entry::new_marked(line, DateTime::now(), EntryKind::Event))
}
pub fn discard_line(&self) -> std::result::Result<(), PathError> {
let mut file = rw_open(&self.0)?;
pop_last_line(&mut file);
Ok(())
}
pub fn reset_last_entry(&self) -> std::result::Result<(), Error> {
let mut file = rw_open(&self.0)?;
if let Some(line) = pop_last_line(&mut file) {
if Entry::is_stop_line(&line) {
self.add_line(&line)?;
return Ok(());
}
let entry = Entry::from_line(&line)?;
self.add_entry(
&Entry::new(&entry.entry_text(), DateTime::now())
)?;
}
Ok(())
}
pub fn ignore_last_entry(&self) -> std::result::Result<(), Error> {
let mut file = rw_open(&self.0)?;
if let Some(line) = pop_last_line(&mut file) {
let entry = Entry::from_line(&line)?;
self.add_entry(
&Entry::new(&entry.entry_text(), DateTime::now()).ignore()
)?;
}
Ok(())
}
pub fn rewrite_last_entry(&self, task: &str) -> std::result::Result<(), Error> {
let mut file = rw_open(&self.0)?;
if let Some(line) = pop_last_line(&mut file) {
let entry = Entry::from_line(&line)?;
self.add_entry(
&Entry::new(task, entry.date_time())
)?;
}
Ok(())
}
pub fn raw_last_line(&self) -> Option<String> {
if self.exists() {
let file = File::open(&self.0).ok()?;
BufReader::new(file)
.lines()
.take_while(|ol| ol.is_ok())
.map(|ol| ol.unwrap())
.last()
}
else {
None
}
}
pub fn last_line(&self) -> Option<String> {
if self.exists() {
let file = File::open(&self.0).ok()?;
BufReader::new(file)
.lines()
.take_while(|ol| ol.is_ok())
.map(|ol| ol.unwrap())
.filter(|ln| !ln.starts_with('#') && EntryKind::from_entry_line(ln).is_start())
.last()
}
else {
None
}
}
pub fn last_entry(&self) -> std::result::Result<Entry, Error> {
Entry::from_line(&self.last_line().unwrap_or_default()).map_err(|e| e.into())
}
pub fn problems(&self) -> Vec<Problem> {
if !self.exists() {
return Vec::new();
}
let file = match self.open() {
Ok(file) => file,
Err(_) => return vec![Problem::FileAccess],
};
let mut errors: Vec<Problem> = Vec::new();
let mut iter = buf_reader(file);
let line = match iter.next() {
Some(line) => line,
None => return errors,
};
let mut prev = match Entry::from_line(&line) {
Ok(ev) => ev,
Err(e) => {
errors.push(Problem::from_error(&e, 1));
return errors;
}
};
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 > ev {
errors.push(Problem::EventsOrder(lineno));
}
else if !prev.is_stop() {
let diff = ev.date_time().sub(&prev.date_time()).unwrap_or_default();
if diff.cmp(&twelve_hour_dur) == Ordering::Greater {
errors.push(Problem::EventLength(lineno));
}
}
prev = ev;
},
Err(e) => errors.push(Problem::from_error(&e, lineno)),
}
}
errors
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::OpenOptions;
use crate::DateTime;
use regex::Regex;
use spectral::prelude::*;
use tempfile::TempDir;
fn make_timelog(lines: &Vec<String>) -> (TempDir, String) {
let tmpdir = TempDir::new().expect("Cannot make tempfile");
let mut path = tmpdir.path().to_path_buf();
path.push("timelog.txt");
let filename = path.to_str().unwrap();
let file = OpenOptions::new()
.create(true)
.append(true)
.open(filename)
.unwrap();
let mut stream = BufWriter::new(file);
lines
.iter()
.for_each(|line| writeln!(&mut stream, "{}", line).unwrap());
stream.flush().unwrap();
(tmpdir, filename.to_owned())
}
fn touch_timelog() -> (TempDir, String) { make_timelog(&vec![String::new()]) }
#[test]
fn test_new() {
let logfile = Logfile::new("./foo.txt").unwrap();
let expected = canonicalize(".")
.map(|mut pb| {
pb.push("foo.txt");
pb.to_str().unwrap().to_owned()
})
.unwrap_or("".to_owned());
assert_that!(logfile.clone_file()).is_equal_to(&expected);
}
#[test]
fn test_new_empty_name() {
assert_that!(Logfile::new(""))
.is_err()
.is_equal_to(&PathError::FilenameMissing);
}
#[test]
fn test_new_bad_path() {
assert_that!(Logfile::new("./xyzzy/foo.txt")).is_err_containing(PathError::InvalidPath(
"./xyzzy/foo.txt".to_string(),
"No such file or directory (os error 2)".to_string(),
));
}
#[test]
fn test_exists_false() {
let logfile = Logfile::new("./foo.txt").unwrap();
assert_that!(logfile.exists()).is_false();
}
#[test]
fn test_exists_true() {
let (_tmpdir, filename) = touch_timelog();
let logfile = Logfile::new(&filename).unwrap();
assert_that!(logfile.exists()).is_true();
}
#[test]
fn test_add_line() {
let (_tmpdir, filename) = touch_timelog();
let logfile = Logfile::new(&filename).unwrap();
assert_that!(logfile.add_line("2021-11-18 18:00:00 +project @task")).is_ok();
assert_that!(logfile.last_line())
.contains_value(&String::from("2021-11-18 18:00:00 +project @task"));
}
#[test]
fn test_add_entry() {
let (_tmpdir, filename) = touch_timelog();
let logfile = Logfile::new(&filename).unwrap();
let entry = Entry::new(
"+project @task",
DateTime::try_from("2021-11-18 18:00:00").expect("Bad date"),
);
assert_that!(logfile.add_entry(&entry)).is_ok();
assert_that!(logfile.last_line())
.contains_value(&String::from("2021-11-18 18:00:00 +project @task"));
}
#[test]
fn test_add_comment() {
let (_tmpdir, filename) = touch_timelog();
let logfile = Logfile::new(&filename).unwrap();
assert_that!(logfile.add_comment("This is a test")).is_ok();
assert_that!(logfile.raw_last_line())
.contains_value(&String::from("# This is a test"));
}
#[test]
fn test_add_event() {
let (_tmpdir, filename) = touch_timelog();
let logfile = Logfile::new(&filename).unwrap();
let expect = Regex::new(
r"\A\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\^something happened"
).expect("Regex failed");
assert_that!(logfile.add_event("something happened")).is_ok();
let last_line = logfile.raw_last_line();
assert_that!(last_line).is_some();
assert_that!(last_line.unwrap())
.matches(|val| expect.is_match(&val));
}
#[test]
fn test_last_line_missing() {
let (_tmpdir, filename) = touch_timelog();
let logfile = Logfile::new(&filename).unwrap();
assert_that!(logfile.last_line()).contains_value(String::new());
}
#[test]
fn test_last_line_empty() {
let (_tmpdir, filename) = make_timelog(&vec![]);
let logfile = Logfile::new(&filename).unwrap();
assert_that!(logfile.last_line()).is_none();
}
#[test]
fn test_last_line_lines() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-11-18 17:01:01 +foo".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
assert_that!(logfile.last_line()).contains_value(&"2021-11-18 17:08:04 +baz".to_owned());
}
#[test]
fn test_last_entry() {
let (_tmpdir, filename) = make_timelog(&vec![]);
let logfile = Logfile::new(&filename).unwrap();
assert_that!(logfile.last_entry())
.is_err()
.is_equal_to(&EntryError::BlankLine.into());
}
#[test]
fn test_last_entry_lines() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-11-18 17:01:01 +foo".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
let expected = Entry::from_line("2021-11-18 17:08:04 +baz").unwrap();
assert_that!(logfile.last_entry())
.is_ok()
.is_equal_to(&expected);
}
#[test]
fn test_problems_all_good() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-11-18 17:01:01 +foo".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
"2021-11-18 17:08:04 stop".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
assert_that!(logfile.problems()).is_empty();
}
#[test]
fn test_problems_all_good_with_comments() {
let (_tmpdir, filename) = make_timelog(&vec![
"# Start of file".to_owned(),
"2021-11-18 17:01:01 +foo".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"# Middle of file".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
"2021-11-18 17:08:04 stop".to_owned(),
"# End of file".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
assert_that!(logfile.problems()).is_empty();
}
#[test]
fn test_problems_blank_line() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-11-18 17:01:01 +foo".to_owned(),
"".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
let problems = logfile.problems();
assert_that!(problems).has_length(1);
assert_that!(problems.iter()).contains(Problem::BlankLine(2));
}
#[test]
fn test_problems_bad_date() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-1-18 17:01:01 +foo".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
"2021-11-18 17:08:04 stop".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
let problems = logfile.problems();
assert_that!(problems).has_length(1);
assert_that!(problems.iter()).contains(Problem::InvalidTimeStamp(1));
}
#[test]
fn test_problems_bad_time() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-11-18 7:01:01 +foo".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
"2021-11-18 17:08:04 stop".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
let problems = logfile.problems();
assert_that!(problems).has_length(1);
assert_that!(problems.iter()).contains(Problem::InvalidTimeStamp(1));
}
#[test]
fn test_problems_missing_timestamp() {
let (_tmpdir, filename) = make_timelog(&vec![
"+foo".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
"2021-11-18 17:08:04 stop".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
let problems = logfile.problems();
assert_that!(problems).has_length(1);
assert_that!(problems.iter()).contains(Problem::InvalidTimeStamp(1));
}
#[test]
fn test_problems_no_task() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-11-18 17:01:01 +foo".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-18 17:08:04 ".to_owned(),
"2021-11-18 17:08:04 stop".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
let problems = logfile.problems();
assert_that!(problems).has_length(1);
assert_that!(problems.iter()).contains(Problem::MissingTask(3));
}
#[test]
fn test_problems_unknown_marker() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-11-18 17:01:01 +foo".to_owned(),
"2021-11-18 17:04:02*+bar".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
"2021-11-18 17:08:04 stop".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
let problems = logfile.problems();
assert_that!(problems).has_length(1);
assert_that!(problems.iter()).contains(Problem::InvalidMarker(2));
}
#[test]
fn test_problems_entry_unordered() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-11-18 17:01:01 +foo".to_owned(),
"2021-11-18 17:08:04 +baz".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-18 17:08:04 stop".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
let problems = logfile.problems();
assert_that!(problems).has_length(1);
assert_that!(problems.iter()).contains(Problem::EventsOrder(3));
}
#[test]
fn test_problems_open_ended() {
let (_tmpdir, filename) = make_timelog(&vec![
"2021-11-18 17:01:01 +foo".to_owned(),
"2021-11-18 17:04:02 +bar".to_owned(),
"2021-11-19 17:08:04 +baz".to_owned(),
"2021-11-19 17:08:04 stop".to_owned(),
]);
let logfile = Logfile::new(&filename).unwrap();
let problems = logfile.problems();
assert_that!(problems).has_length(1);
assert_that!(problems.iter()).contains(Problem::EventLength(3));
}
}