todo_lib 11.1.0

Collection of utilities for todo.txt 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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
use chrono::{Duration, NaiveDate};

use crate::{human_date, todotxt};

#[derive(Debug)]
struct ExprItem<'a> {
    pub sign: char,
    pub val: &'a str,
}

/// Keeps a task tag values.
#[derive(Default, Clone)]
pub struct TaskTag {
    /// Tag name
    pub name: String,
    /// Tag raw value - the one that was passed in the command line by a user, e.g, `due+1`
    pub svalue: Option<String>,
    /// Calculated value. It is filled during calculation.
    pub dvalue: Option<NaiveDate>,
}

/// List of tags.
pub struct TaskTagList(Vec<TaskTag>);

/// The type of a tag value.
#[derive(Debug, PartialEq)]
pub enum TagValueType {
    /// The raw value defined by a user.
    Raw(String),
    /// Value calculated by this module (`ttdl add` case).
    /// Or the value read from the file (`ttdl edit` case).
    Calc(NaiveDate),
    /// The tag does not exists.
    None,
}

impl TaskTagList {
    /// Fills the tag list from the parsed task.
    pub fn from_task(task: &todotxt::Task) -> Self {
        let mut v = Vec::new();
        if let Some(dt) = task.due_date {
            let tg = TaskTag { name: "due".to_string(), dvalue: Some(dt), svalue: None };
            v.push(tg);
        }
        if let Some(dt) = task.create_date {
            let tg = TaskTag { name: "created".to_string(), dvalue: Some(dt), svalue: None };
            v.push(tg);
        }
        if let Some(dt) = task.threshold_date {
            let tg = TaskTag { name: "t".to_string(), dvalue: Some(dt), svalue: None };
            v.push(tg);
        }
        for (key, value) in task.tags.iter() {
            let tg = TaskTag { name: key.clone(), svalue: Some(value.clone()), dvalue: None };
            v.push(tg);
        }
        TaskTagList(v)
    }
    /// Fills the tag list from the raw string.
    pub fn from_str(s: &str, dt: NaiveDate) -> Self {
        let hmap = todotxt::extract_tags(s);
        let mut v = Vec::new();
        for (key, val) in hmap.iter() {
            let tg = TaskTag { name: key.to_string(), svalue: Some(val.to_string()), dvalue: None };
            v.push(tg);
        }
        let tg = TaskTag { name: "created".to_string(), dvalue: None, svalue: Some(todotxt::format_date(dt)) };
        v.push(tg);
        TaskTagList(v)
    }
    /// Change the tag value.
    /// Use the method after the value of the tag was calculated.
    pub fn set_tag(&mut self, tag: &str, value: NaiveDate) {
        for v in self.0.iter_mut() {
            if v.name.as_str() == tag {
                v.dvalue = Some(value);
                return;
            }
        }
    }
    /// Returns the value of a tag.
    pub fn tag_value(&self, tag: &str) -> TagValueType {
        for v in self.0.iter() {
            if v.name.as_str() == tag {
                if let Some(dt) = v.dvalue {
                    return TagValueType::Calc(dt);
                } else if let Some(ref s) = v.svalue {
                    return TagValueType::Raw(s.clone());
                }
            }
        }
        TagValueType::None
    }
}

// Full date format: YYYY-MM-DD
fn parse_full_date(s: &str) -> Option<&str> {
    let mut st = s;
    match s.find(|c: char| !c.is_ascii_digit()) {
        None => return None,
        Some(i) => {
            if i != 4 {
                return None;
            } else {
                st = &st[i..];
            }
        }
    }
    if !st.starts_with('-') {
        return None;
    }
    st = &st[1..];
    match st.find(|c: char| !c.is_ascii_digit()) {
        None => return None,
        Some(i) => {
            if i != 2 {
                return None;
            } else {
                st = &st[i..];
            }
        }
    }
    if !st.starts_with('-') {
        return None;
    }
    st = &st[1..];
    match st.find(|c: char| !c.is_ascii_digit()) {
        None => {
            if st.len() == 2 {
                Some(s)
            } else {
                None
            }
        }
        Some(i) => {
            if i != 2 {
                None
            } else {
                let l = "2020-01-01".len();
                let rest = &s[l..];
                if !rest.starts_with('-') && !rest.starts_with('+') {
                    return None;
                }
                Some(&s[..l])
            }
        }
    }
}

// Short date format: MM-DD
fn parse_short_date(s: &str) -> Option<&str> {
    let mut st = s;
    match s.find(|c: char| !c.is_ascii_digit()) {
        None => return None,
        Some(i) => {
            if i != 2 {
                return None;
            } else {
                st = &st[i..];
            }
        }
    }
    if !st.starts_with('-') {
        return None;
    }
    st = &st[1..];
    match st.find(|c: char| !c.is_ascii_digit()) {
        None => {
            if st.len() == 2 {
                Some(s)
            } else {
                None
            }
        }
        Some(i) => {
            if i != 2 {
                None
            } else {
                let l = "01-01".len();
                let rest = &s[l..];
                if !rest.starts_with('-') && !rest.starts_with('+') {
                    return None;
                }
                Some(&s[..l])
            }
        }
    }
}

// Single day format:DD
fn parse_single_day(s: &str) -> Option<&str> {
    match s.find(|c: char| !c.is_ascii_digit()) {
        None => {
            if s.len() < 3 {
                Some(s)
            } else {
                None
            }
        }
        Some(i) => {
            if i > 2 || i == 0 {
                None
            } else {
                let rest = &s[i..];
                if !rest.starts_with('-') && !rest.starts_with('+') {
                    return None;
                }
                Some(&s[..i])
            }
        }
    }
}

// Special date: tue, today, tomorrow etc
fn parse_special(s: &str) -> Option<&str> {
    let c = s.chars().next()?;
    if !c.is_ascii_lowercase() && !c.is_ascii_uppercase() {
        return None;
    }
    match s.find(|c: char| !c.is_ascii_lowercase() && !c.is_ascii_uppercase()) {
        None => Some(s),
        Some(idx) => {
            let rest = &s[idx..];
            if !rest.starts_with('-') && !rest.starts_with('+') { None } else { Some(&s[..idx]) }
        }
    }
}

// Duration: ##D (1-2 digits and duration type DWMY)
fn parse_duration(s: &str) -> Option<&str> {
    let c = s.chars().next()?;
    let durs = ['d', 'D', 'w', 'W', 'm', 'M', 'y', 'Y'];
    if c.is_ascii_digit() {
        let idxl = match s.find(|c: char| !c.is_ascii_digit()) {
            None => return Some(s),
            Some(i) => i,
        };
        let rest = &s[idxl..];
        if rest.starts_with('-') || rest.starts_with('+') {
            Some(&s[..idxl])
        } else if let Some(cc) = rest.chars().next() {
            if durs.contains(&cc) {
                if s.len() == idxl + 1 {
                    Some(s)
                } else {
                    let rest = &s[idxl + 1..];
                    if rest.starts_with('-') || rest.starts_with('+') { Some(&s[..idxl + 1]) } else { None }
                }
            } else {
                None
            }
        } else {
            None
        }
    } else if durs.contains(&c) {
        match s.find(|c: char| !c.is_ascii_lowercase() && !c.is_ascii_uppercase()) {
            None => {
                if s.len() == 1 {
                    Some(s)
                } else {
                    None
                }
            }
            Some(idx) => {
                let rest = &s[idx..];
                if rest.starts_with('-') || rest.starts_with('+') { Some(&s[..idx]) } else { None }
            }
        }
    } else {
        None
    }
}

fn parse_base_date(s: &str) -> Result<ExprItem<'_>, String> {
    if let Some(st) = parse_special(s) {
        return Ok(ExprItem { sign: '+', val: st });
    }
    if let Some(st) = parse_full_date(s) {
        return Ok(ExprItem { sign: '+', val: st });
    }
    if let Some(st) = parse_short_date(s) {
        return Ok(ExprItem { sign: '+', val: st });
    }
    if let Some(st) = parse_single_day(s) {
        return Ok(ExprItem { sign: '+', val: st });
    }
    Err("Failed to parse base date".to_string())
}

fn parse_expression(s: &str) -> Result<Vec<ExprItem<'_>>, String> {
    let mut items = Vec::new();
    let mut st = match parse_base_date(s) {
        Err(e) => return Err(e),
        Ok(ei) => {
            let sc = &s[ei.val.len()..];
            items.push(ei);
            sc
        }
    };
    while !st.is_empty() {
        if st.len() < 2 {
            return Err(format!("Incomplete expression: '{s}'"));
        }
        let c = match st.chars().next() {
            Some(cc) => cc,
            None => return Err("Internal error".to_string()),
        };
        if c != '-' && c != '+' {
            return Err(format!("Invalid character '{c}'"));
        }
        st = &st[1..];
        match parse_duration(st) {
            None => return Err(format!("Invalid duration: '{st}'")),
            Some(v) => {
                let ei = ExprItem { sign: c, val: v };
                st = &st[ei.val.len()..];
                items.push(ei);
            }
        }
    }
    Ok(items)
}

fn parse_abs_date(base: NaiveDate, s: &str, soon_days: u8) -> Result<NaiveDate, String> {
    match human_date::human_to_date(base, s, soon_days) {
        Ok(d) => Ok(d),
        Err(e) => {
            if e == human_date::NO_CHANGE {
                match NaiveDate::parse_from_str(s, "%Y-%m-%d") {
                    Ok(d) => Ok(d),
                    Err(e) => Err(format!("Invalid date [{s}]: {e}")),
                }
            } else {
                Err(e)
            }
        }
    }
}

fn calc_base(
    base: NaiveDate,
    s: &str,
    tags: &mut TaskTagList,
    soon_days: u8,
    counter: usize,
) -> Result<NaiveDate, String> {
    let mut dt = base;
    if s.find(|c: char| !c.is_ascii_lowercase() && !c.is_ascii_uppercase()).is_none() {
        // Special date case
        let spec = s.to_lowercase();
        let tval = tags.tag_value(spec.as_str());
        match tval {
            TagValueType::None => {
                dt = parse_abs_date(dt, s, soon_days)?;
            }
            TagValueType::Calc(d) => {
                dt = d;
            }
            TagValueType::Raw(s) => {
                let d = calc_expr(base, &s, tags, soon_days, counter + 1)?;
                tags.set_tag(&spec, d);
                dt = d;
            }
        }
    } else {
        // Absolute date
        dt = parse_abs_date(dt, s, soon_days)?;
    }
    Ok(dt)
}

fn calc_expr(
    base: NaiveDate,
    s: &str,
    tags: &mut TaskTagList,
    soon_days: u8,
    counter: usize,
) -> Result<NaiveDate, String> {
    if counter > 10 {
        return Err("Recursion stack overflow".to_string());
    }

    let items = parse_expression(s)?;
    if items.is_empty() {
        return Err("Empty expression".to_string());
    }

    let mut dt = base;
    for (idx, item) in items.iter().enumerate() {
        match idx {
            0 => {
                dt = calc_base(base, item.val, tags, soon_days, counter)?;
            }
            _ => {
                let rec_str = if item.val.find(|c: char| !c.is_ascii_digit()).is_none() {
                    format!("{0}d", item.val)
                } else {
                    item.val.to_string()
                };
                let rc = match todotxt::Recurrence::parse(&rec_str) {
                    Ok(r) => r,
                    Err(e) => {
                        return Err(format!("Invalid duration '{0}': {e}", item.val));
                    }
                };
                match rc.period {
                    todotxt::Period::Day => {
                        let dur = if item.sign == '-' {
                            Duration::days(-(rc.count as i64))
                        } else {
                            Duration::days(rc.count as i64)
                        };
                        dt += dur;
                    }
                    todotxt::Period::Week => {
                        let dur = if item.sign == '-' {
                            Duration::days(-(rc.count as i64) * 7)
                        } else {
                            Duration::days(rc.count as i64 * 7)
                        };
                        dt += dur;
                    }
                    todotxt::Period::Month => {
                        dt = human_date::add_months(dt, rc.count.into(), item.sign == '-');
                    }
                    todotxt::Period::Year => {
                        dt = human_date::add_years(dt, rc.count.into(), item.sign == '-');
                    }
                    _ => {}
                }
            }
        }
    }

    Ok(dt)
}

/// Calculate any expression using the existing tags.
/// NOTE: all expressions must follow the format:
///     <base-date> [<operation> <single-range>]?
/// where
///     base-date is either absolute date long or short format (YYYY-MM-DD) or and special date
///         like `today` or `sun`
///     operation is either `+` or `-`
///     single-range is the same format as recurrence #R (a number followed by a range type DWMY),
///         if range type is missing, it defaults to `d`=days
/// Examples:
///     `due+2` ==> 2 days after due date
///     `due+2d` ==> the same as above: 2 days after due date
///     `t-2w` ==> 2 weeks before threshold date
///     `due+1w+2d` ==> 1 week and 2 days after due date
pub fn calculate_expr(base: NaiveDate, s: &str, tags: &mut TaskTagList, soon_days: u8) -> Result<NaiveDate, String> {
    calc_expr(base, s, tags, soon_days, 1)
}

/// Calculates values of the main todo.txt tags.
/// The current list of such tags is short: `due` and `t`.
pub fn calculate_main_tags(base: NaiveDate, tags: &mut TaskTagList, soon_days: u8) -> Result<bool, String> {
    let mut anything_changed = false;
    for tag in ["due", "t"].into_iter() {
        let t = tags.tag_value(tag);
        if let TagValueType::Raw(s) = t {
            let cval = calculate_expr(base, &s, tags, soon_days)?;
            let fdate = todotxt::format_date(cval);
            if fdate.as_str() != s {
                tags.set_tag(tag, cval);
                anything_changed = true;
            }
        }
    }
    Ok(anything_changed)
}

/// Replaces the current tag values in a string with new calculated values.
/// The tag value is replaced only if the tag has TagValueType::Calc type.
/// The current list of replaced tags is short: `due` and `t`.
pub fn update_tags_in_str(tags: &TaskTagList, s: &str) -> String {
    let mut st = s.to_string();
    for tag in tags.0.iter() {
        if tag.name.as_str() != "due" && tag.name.as_str() != "t" {
            continue;
        }
        if let (Some(sval), Some(dval)) = (tag.svalue.clone(), tag.dvalue) {
            let old = format!("{0}:{sval}", tag.name);
            let new = format!("{0}:{1}", tag.name, todotxt::format_date(dval));
            todotxt::replace_word(&mut st, &old, &new);
        }
    }
    st
}

#[cfg(test)]
mod date_expr_test {
    use super::*;

    struct Test {
        txt: &'static str,
        err: bool,
        res: &'static str,
    }

    #[test]
    fn parse_full_date_test() {
        let tests: Vec<Test> = vec![
            Test { txt: "1999-20-20", err: false, res: "1999-20-20" },
            Test { txt: "1999-20-20+1d", err: false, res: "1999-20-20" },
            Test { txt: "1999-20-20-2", err: false, res: "1999-20-20" },
            Test { txt: "1999-20-20z", err: true, res: "" },
            Test { txt: "21999-20-20", err: true, res: "" },
            Test { txt: "1999-2-20", err: true, res: "" },
            Test { txt: "1999-20-0", err: true, res: "" },
            Test { txt: "19a9-20-20", err: true, res: "" },
            Test { txt: "1999-20-0a", err: true, res: "" },
            Test { txt: "cccccccccc", err: true, res: "" },
            Test { txt: "19992020", err: true, res: "" },
            Test { txt: "", err: true, res: "" },
            Test { txt: "-1999-20-20", err: true, res: "" },
        ];
        for test in tests.iter() {
            let r = parse_full_date(test.txt);
            match r {
                Some(rr) => {
                    if test.err {
                        assert!(false, "Test [{0}] must fail", test.txt);
                    }
                    assert_eq!(test.res, rr, "Failed [{0}]: {:?}", test.txt);
                }
                None => {
                    if !test.err {
                        assert!(false, "Test [{0}] must pass", test.txt);
                    }
                }
            }
        }
    }

    #[test]
    fn parse_special_test() {
        let tests: Vec<Test> = vec![
            Test { txt: "today", err: false, res: "today" },
            Test { txt: "Today", err: false, res: "Today" },
            Test { txt: "tODAY", err: false, res: "tODAY" },
            Test { txt: "tue", err: false, res: "tue" },
            Test { txt: "tue-2", err: false, res: "tue" },
            Test { txt: "today%2", err: true, res: "" },
            Test { txt: "2+today", err: true, res: "" },
        ];
        for test in tests.iter() {
            let r = parse_special(test.txt);
            match r {
                Some(rr) => {
                    if test.err {
                        assert!(false, "Test [{0}] must fail", test.txt);
                    }
                    assert_eq!(test.res, rr, "Failed [{0}]: {:?}", test.txt);
                }
                None => {
                    if !test.err {
                        assert!(false, "Test [{0}] must pass", test.txt);
                    }
                }
            }
        }
    }

    #[test]
    fn parse_short_date_test() {
        let tests: Vec<Test> = vec![
            Test { txt: "20-20", err: false, res: "20-20" },
            Test { txt: "20-20+1d", err: false, res: "20-20" },
            Test { txt: "20-20-2", err: false, res: "20-20" },
            Test { txt: "20-20z", err: true, res: "" },
            Test { txt: "320-20", err: true, res: "" },
            Test { txt: "2-20", err: true, res: "" },
            Test { txt: "20-0", err: true, res: "" },
            Test { txt: "2a-20", err: true, res: "" },
            Test { txt: "20-0a", err: true, res: "" },
            Test { txt: "ccccc", err: true, res: "" },
            Test { txt: "2020", err: true, res: "" },
            Test { txt: "", err: true, res: "" },
            Test { txt: "-20-20", err: true, res: "" },
        ];
        for test in tests.iter() {
            let r = parse_short_date(test.txt);
            match r {
                Some(rr) => {
                    if test.err {
                        assert!(false, "Test [{0}] must fail", test.txt);
                    }
                    assert_eq!(test.res, rr, "Failed [{0}]: {:?}", test.txt);
                }
                None => {
                    if !test.err {
                        assert!(false, "Test [{0}] must pass", test.txt);
                    }
                }
            }
        }
    }

    #[test]
    fn parse_duration_test() {
        let tests: Vec<Test> = vec![
            Test { txt: "w+1", err: false, res: "w" },
            Test { txt: "200d-1", err: false, res: "200d" },
            Test { txt: "15w", err: false, res: "15w" },
            Test { txt: "y", err: false, res: "y" },
            Test { txt: "2+3", err: false, res: "2" },
            Test { txt: "day", err: true, res: "" },
            Test { txt: "", err: true, res: "" },
            Test { txt: "a20", err: true, res: "" },
            Test { txt: "20days", err: true, res: "" },
            Test { txt: "20/4", err: true, res: "" },
            Test { txt: "20w/4", err: true, res: "" },
        ];
        for test in tests.iter() {
            let r = parse_duration(test.txt);
            match r {
                Some(rr) => {
                    if test.err {
                        assert!(false, "Test [{0}] must fail", test.txt);
                    }
                    assert_eq!(test.res, rr, "Failed [{0}]: {:?}", test.txt);
                }
                None => {
                    if !test.err {
                        assert!(false, "Test [{0}] must pass", test.txt);
                    }
                }
            }
        }
    }

    #[test]
    fn parse_expression_test() {
        struct ETest {
            txt: &'static str,
            l: usize,
            err: bool,
            last: &'static str,
        }
        let tests: Vec<ETest> = vec![
            ETest { txt: "2003-01-01", err: false, l: 1, last: "2003-01-01" },
            ETest { txt: "2003-01-01+2d", err: false, l: 2, last: "2d" },
            ETest { txt: "2003-01-01+2d-9", err: false, l: 3, last: "9" },
            ETest { txt: "2003-01-01+9-10m", err: false, l: 3, last: "10m" },
            ETest { txt: "tue+67", err: false, l: 2, last: "67" },
            ETest { txt: "2003-01-01+abcd", err: true, l: 1, last: "" },
            ETest { txt: "tue+tue", err: true, l: 1, last: "" },
            ETest { txt: "tue/2", err: true, l: 1, last: "" },
            ETest { txt: "2d", err: true, l: 1, last: "" },
        ];
        for test in tests.iter() {
            let r = parse_expression(test.txt);
            match r {
                Ok(rr) => {
                    if test.err {
                        assert!(false, "Test [{0}] must fail", test.txt);
                    }
                    assert_eq!(test.l, rr.len(), "{0} expected {1} items, got {2}", test.txt, test.l, rr.len());
                    assert_eq!(
                        test.last,
                        rr[rr.len() - 1].val,
                        "Failed [{0}]: {:?}, [{1}] != [{2}]",
                        test.txt,
                        test.last,
                        rr[rr.len() - 1].val
                    );
                }
                Err(e) => {
                    if !test.err {
                        assert!(false, "Test [{0}] must pass: {e:?}", test.txt);
                    }
                }
            }
        }
    }

    #[test]
    fn parse_str_expression_test() {
        struct ETest {
            txt: &'static str,
            err: bool,
            res: NaiveDate,
        }
        let tests: Vec<ETest> = vec![
            ETest { txt: "2021-05-07", err: false, res: NaiveDate::from_ymd_opt(2021, 5, 7).unwrap() },
            ETest { txt: "2021-05-07+10d", err: false, res: NaiveDate::from_ymd_opt(2021, 5, 17).unwrap() },
            ETest { txt: "2021-05-07+2w", err: false, res: NaiveDate::from_ymd_opt(2021, 5, 21).unwrap() },
            ETest { txt: "2021-05-07-7d", err: false, res: NaiveDate::from_ymd_opt(2021, 4, 30).unwrap() },
            ETest { txt: "2021-05-07-2m", err: false, res: NaiveDate::from_ymd_opt(2021, 3, 07).unwrap() },
            ETest { txt: "2021-05-07+1y", err: false, res: NaiveDate::from_ymd_opt(2022, 5, 07).unwrap() },
            ETest { txt: "2021-05-07+12d-2d", err: false, res: NaiveDate::from_ymd_opt(2021, 5, 17).unwrap() },
            ETest { txt: "2021-05-07+12d-1w", err: false, res: NaiveDate::from_ymd_opt(2021, 5, 12).unwrap() },
            ETest { txt: "today", err: false, res: NaiveDate::from_ymd_opt(2020, 3, 15).unwrap() },
            ETest { txt: "yesterday+2d", err: false, res: NaiveDate::from_ymd_opt(2020, 3, 16).unwrap() },
            ETest { txt: "first+1w", err: false, res: NaiveDate::from_ymd_opt(2020, 4, 8).unwrap() },
            ETest { txt: "due+1d", err: false, res: NaiveDate::from_ymd_opt(2020, 4, 9).unwrap() },
            ETest { txt: "t-1d", err: false, res: NaiveDate::from_ymd_opt(2020, 4, 3).unwrap() },
            ETest { txt: "extra+1w", err: false, res: NaiveDate::from_ymd_opt(2022, 9, 23).unwrap() },
            ETest { txt: "2021-05-07*2", err: true, res: NaiveDate::from_ymd_opt(2021, 5, 7).unwrap() },
            ETest { txt: "2021-05-07+1t", err: true, res: NaiveDate::from_ymd_opt(2021, 5, 7).unwrap() },
            ETest { txt: "someday", err: true, res: NaiveDate::from_ymd_opt(2021, 5, 7).unwrap() },
        ];

        let base = NaiveDate::from_ymd_opt(2020, 3, 15).unwrap();
        let task = todotxt::Task::parse("create something due:2020-04-08 t:due-4 extra:2022-09-16", base);
        let mut tlist = TaskTagList::from_task(&task);
        for (idx, test) in tests.iter().enumerate() {
            let d = calculate_expr(base, test.txt, &mut tlist, 8);
            if test.err {
                if d.is_ok() {
                    assert!(false, "Test {idx}.[{0}] must fail", test.txt);
                }
            } else {
                if d.is_err() {
                    assert!(false, "Test {idx}.[{0}] must pass: {1:?}", test.txt, d);
                } else {
                    assert_eq!(d.unwrap(), test.res, "Test {idx}.[{0}]", test.txt);
                }
            }
        }
    }
    #[test]
    fn tag_list_from_str_test() {
        struct ETest {
            txt: &'static str,
            count: usize,
            values: Vec<&'static str>,
        }
        let base = NaiveDate::from_ymd_opt(2020, 3, 15).unwrap();
        // Do not forget to add +1 - for "created"
        let tests: Vec<ETest> = vec![
            ETest { txt: "", count: 1, values: vec!["created", "2020-03-15"] },
            ETest {
                txt: "house due:2015-08-12 was done:due+5 t:2015-07-30 .",
                count: 4,
                values: vec!["created", "2020-03-15", "due", "2015-08-12", "done", "due+5", "t", "2015-07-30"],
            },
        ];
        for (idx, test) in tests.iter().enumerate() {
            let tlist = TaskTagList::from_str(test.txt, base);
            assert_eq!(test.count, tlist.0.len());
            for vidx in 0..test.values.len() / 2 {
                let v = tlist.tag_value(test.values[vidx * 2]);
                assert_eq!(
                    v,
                    TagValueType::Raw(test.values[vidx * 2 + 1].to_string()),
                    "{idx}. Tag [{0}] must get value [{1}] instead of [{2:?}]",
                    test.values[vidx * 2],
                    test.values[vidx * 2 + 1],
                    v
                );
            }
        }
    }
    #[test]
    fn tag_calculate_done_test() {
        struct ETest {
            txt: &'static str,
            is_err: bool,
            value: &'static str,
        }
        let base = NaiveDate::from_ymd_opt(2020, 3, 15).unwrap();
        // Do not forget to add +1 - for "created"
        let tests: Vec<ETest> = vec![
            ETest { txt: "", is_err: true, value: "" },
            ETest { txt: "no done tag, just t:2023-09-11", is_err: true, value: "" },
            ETest { txt: "exists normal done:2023-06-24 tag", is_err: false, value: "2023-06-24" },
            ETest { txt: "house due:2015-08-12 was done:due+5 t:2015-07-30 .", is_err: false, value: "2015-08-17" },
        ];
        for (idx, test) in tests.iter().enumerate() {
            let mut tlist = TaskTagList::from_str(test.txt, base);
            let res = calculate_expr(base, "done", &mut tlist, 7);
            match res {
                Err(e) => {
                    if !test.is_err {
                        assert!(false, "{idx}. The test must not fail. Got {0:?}", e);
                    }
                }
                Ok(d) => {
                    if test.is_err {
                        assert!(false, "{idx}. The test must fail");
                    } else {
                        let ds = todotxt::format_date(d);
                        assert_eq!(test.value, ds.as_str(), "Expected date: {0}, got {1}", test.value, d);
                    }
                }
            }
        }
    }
    #[test]
    fn tag_fix_str_test() {
        struct ETest {
            txt: &'static str,
            val: &'static str,
            fixed: bool,
        }
        let base = NaiveDate::from_ymd_opt(2020, 3, 15).unwrap();
        let tests: Vec<ETest> = vec![
            ETest { txt: "exists normal due:2023-06-24 tag", val: "exists normal due:2023-06-24 tag", fixed: false },
            ETest {
                txt: "house done:2015-08-12 was due:done-5 t:2015-07-30 .",
                val: "house done:2015-08-12 was due:2015-08-07 t:2015-07-30 .",
                fixed: true,
            },
        ];
        for (idx, test) in tests.iter().enumerate() {
            let mut tlist = TaskTagList::from_str(test.txt, base);
            let fixed = calculate_main_tags(base, &mut tlist, 7).unwrap();
            assert_eq!(fixed, test.fixed);
            let new_str = update_tags_in_str(&tlist, test.txt);
            assert_eq!(new_str.as_str(), test.val, "{idx}. Must be equal [{0}], got [{new_str}]", test.val);
        }
    }
}