toddi 0.3.2

A TODO focuser built on top of todo.txt
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
use std::path::PathBuf;

use chrono::Local;
use regex::Regex;

use anyhow::{anyhow, Result};

use crate::{
    egress,
    ingress::{SrcType, TaskSrc},
    DONE_FILE,
};

#[derive(Debug, Clone)]
/// Representation of a project being worked on.
pub struct Project {
    /// Project name
    pub name: String,

    /// Number of tasks left to do.
    pub todo: u8,

    /// Number of tasks done.
    pub done: u8,

    /// Remaining tasks
    tasks: TaskList,
}

impl Project {
    pub fn search_project(
        name: String,
        todo_tasks: TaskList,
        done_tasks: CompletedTaskList,
    ) -> Option<Project> {
        if todo_tasks.clone().contains_project(name.clone())
            || done_tasks.clone().contains_project(name.clone())
        {
            let project_task_list = todo_tasks.clone().get_project_tasks(name.clone());
            let todos = project_task_list.clone().tasks;
            let dones = done_tasks.get_project_tasks(name.clone()).tasks;
            Some(Project {
                name,
                todo: todos.len() as u8,
                done: dones.len() as u8,
                tasks: project_task_list,
            })
        } else {
            None
        }
    }

    pub fn get_current_task(self) -> Option<Task> {
        self.tasks.get_current_task()
    }

    pub fn complete_current_task(self) -> Result<()> {
        if let Some(current_task) = self.get_current_task() {
            let task_line = current_task.raw.clone();
            let source_type = current_task.source_type.clone();
            let source_location = current_task.source_location.clone();
            egress::remove_task(task_line, source_type, source_location)?;
            let completed_task: CompletedTask = current_task.complete()?;
            egress::add_completed_task(
                completed_task.raw,
                completed_task.source_type,
                completed_task.source_location,
            )?;
            Ok(())
        } else {
            Err(anyhow!(
                "Could not obtain and complete project's current task."
            ))
        }
    }
}

#[derive(Debug, Clone, Eq)]
/// Representation of a task line as defined in done.txt
pub struct CompletedTask {
    #[allow(dead_code)]
    /// Task description
    description: String,

    /// Task's project
    project: String,

    #[allow(dead_code)]
    /// Task's context
    context: String,

    /// Task's raw entry
    raw: String,

    #[allow(dead_code)]
    /// Task's source type
    source_type: SrcType,

    #[allow(dead_code)]
    /// Task's source location
    source_location: String,

    #[allow(dead_code)]
    /// Task's completion date
    completion_date: String,
}

impl PartialEq for CompletedTask {
    fn eq(&self, other: &Self) -> bool {
        // TODO: compare date first, then description
        self.completion_date == other.completion_date
    }
}

impl PartialOrd for CompletedTask {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for CompletedTask {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // TODO: compare date first, then description
        self.completion_date.cmp(&other.raw)
    }
}

impl CompletedTask {
    fn new(task_line: &str, source_type: SrcType, source_location: String) -> Result<Self> {
        let raw = task_line.to_string();
        match Self::validate_completed_task_line(task_line) {
            Ok(re) => {
                let caps = match re.captures(task_line) {
                    Some(caps) => caps,
                    None => return Err(anyhow!("The regex is already matched during validation, this should not be happening!\ntask_line: {:?}\nre: {:?}", task_line, re)),
                };
                let description = match caps.name("description") {
                    Some(desc) => desc.as_str().trim().to_string(),
                    None => "".to_string(),
                };
                let project = match caps.name("project") {
                    Some(proj) => proj.as_str().trim().to_string(),
                    None => "".to_string(),
                };
                let context = match caps.name("context") {
                    Some(context) => context.as_str().trim().to_string(),
                    None => "".to_string(),
                };
                let completion_date = match caps.name("date") {
                    Some(date) => date.as_str().trim().to_string(),
                    None => "".to_string(),
                };

                Ok(Self {
                    description,
                    project,
                    context,
                    raw,
                    source_type,
                    source_location,
                    completion_date,
                })
            }
            Err(err) => {
                eprintln!(
                    "could not validate completed task_line: {}\nError: {}",
                    task_line, err
                );
                Ok(Self {
                    description: task_line.to_string(),
                    project: "".to_string(),
                    context: "".to_string(),
                    raw,
                    source_type,
                    source_location,
                    completion_date: "".to_string(),
                })
            }
        }
    }

    fn validate_completed_task_line(task_line: &str) -> Result<Regex> {
        let re1 = match Regex::new(
            r"^x (?<date>[\d]{4}-[\d]{2}-[\d]{2}){1}(?<description>[[:alnum:]ë\s_\-\.']+)+(\+(?<project>[[:alnum:]]+))?\s?(@(?<context>[[:alnum:]]+))?$",
        ) {
            Ok(re) => re,
            Err(err) => return Err(anyhow!("Issue with pattern: {}", err)),
        };
        let re2 = match Regex::new(
            r"^x (?<date>[\d]{4}-[\d]{2}-[\d]{2}){1}(?<description>[[:alnum:]ë\s_\-\.']+)+(@(?<context>[[:alnum:]]+))?\s?(\+(?<project>[[:alnum:]]+))?$",
        ) {
            Ok(re) => re,
            Err(err) => return Err(anyhow!("Issue with pattern: {}", err)),
        };
        if re1.is_match(task_line) {
            Ok(re1)
        } else if re2.is_match(task_line) {
            Ok(re2)
        } else {
            Err(anyhow!("Invalid task line."))
        }
    }
}

#[derive(Debug, Clone, Eq)]
/// Representation of a task line as defined in todo.txt
pub struct Task {
    #[allow(dead_code)]
    /// Task priority
    priority: char,

    /// Task description
    pub description: String,

    /// Task's project
    pub project: String, // TODO: option

    #[allow(dead_code)]
    /// Task's context
    context: String,

    /// Task's raw entry
    raw: String,

    #[allow(dead_code)]
    /// Task's source type
    source_type: SrcType,

    #[allow(dead_code)]
    /// Task's source location
    source_location: String,
}

impl PartialEq for Task {
    fn eq(&self, other: &Self) -> bool {
        // TODO: compare priority first, then description
        self.raw == other.raw
    }
}

impl PartialOrd for Task {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Task {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // TODO: compare priority first, then description
        self.raw.cmp(&other.raw)
    }
}

impl Task {
    fn new(task_line: &str, source_type: SrcType, source_location: String) -> Result<Self> {
        let raw = task_line.to_string();
        match Self::validate_todo_task_line(task_line) {
            Ok(re) => {
                let caps = match re.captures(task_line) {
                    Some(caps) => caps,
                    None => return Err(anyhow!("The regex is already matched during validation, this should not be happening!\ntask_line: {:?}\nre: {:?}", task_line, re)),
                };
                let priority = match caps.name("priority") {
                    Some(prio) => {
                        if let Some(prio) = prio.as_str().chars().nth(0) {
                            prio
                        } else {
                            return Err(anyhow!("Could not extract first char from single character priority string {:?}", prio));
                        }
                    }
                    None => 'Z',
                };
                let description = match caps.name("description") {
                    Some(desc) => desc.as_str().trim().to_string(),
                    None => "".to_string(),
                };
                let project = match caps.name("project") {
                    Some(proj) => proj.as_str().trim().to_string(),
                    None => "".to_string(),
                };
                let context = match caps.name("context") {
                    Some(cont) => cont.as_str().trim().to_string(),
                    None => "".to_string(),
                };

                Ok(Self {
                    priority,
                    description,
                    project,
                    context,
                    raw,
                    source_type,
                    source_location,
                })
            }
            Err(err) => {
                eprintln!(
                    "could not validate todo task_line: {}\nError: {}",
                    task_line, err
                );
                Ok(Self {
                    priority: 'Z',
                    description: task_line.to_string(),
                    project: "".to_string(),
                    context: "".to_string(),
                    raw,
                    source_type,
                    source_location,
                })
            }
        }
    }

    fn validate_todo_task_line(task_line: &str) -> Result<Regex> {
        let re1 = match Regex::new(
            r"^([\(](?<priority>[A-Z])[\)])?(?<description>[[:alnum:]ë\s_\-\.']+)+(\+(?<project>[[:alnum:]]+))?\s?(@(?<context>[[:alnum:]]+))?$",
        ) {
            Ok(re) => re,
            Err(err) => return Err(anyhow!("Issue with pattern: {}", err)),
        };
        let re2 = match Regex::new(
            r"^([\(](?<priority>[A-Z])[\)])?(?<description>[[:alnum:]ë\s_\-\.']+)+(@(?<context>[[:alnum:]]+))?\s?(\+(?<project>[[:alnum:]]+))?$",
        ) {
            Ok(re) => re,
            Err(err) => return Err(anyhow!("Issue with pattern: {}", err)),
        };
        if re1.is_match(task_line) {
            Ok(re1)
        } else if re2.is_match(task_line) {
            Ok(re2)
        } else {
            Err(anyhow!("Invalid task line."))
        }
    }

    fn complete(&self) -> Result<CompletedTask> {
        let source_type = self.source_type.clone();
        let description = self.description.clone();
        let context = self.context.clone();
        let project = self.project.clone();
        let completion_date = Local::now().format("%Y-%m-%d").to_string();

        let source_location: String;
        let path_buf = PathBuf::from(self.source_location.clone());
        if let Some(parent) = path_buf.parent() {
            let mut path_buf = parent.to_path_buf();
            path_buf.push(DONE_FILE);
            if let Some(path) = path_buf.to_str() {
                source_location = String::from(path);
            } else {
                return Err(anyhow!("Failed to convert source_location path to string."));
            }
        } else {
            return Err(anyhow!("Failed to extract source_location directory."));
        }

        let mut raw = String::new();
        raw.push('x');
        raw.push(' ');
        raw.push_str(&completion_date);
        raw.push(' ');
        raw.push_str(&description);
        if !project.is_empty() {
            raw.push(' ');
            raw.push('+');
            raw.push_str(&project);
        }
        if !context.is_empty() {
            raw.push(' ');
            raw.push('@');
            raw.push_str(&context);
        }

        Ok(CompletedTask {
            description,
            project,
            context,
            raw,
            source_type,
            source_location,
            completion_date,
        })
    }
}

#[derive(Clone)]
/// Representation of a list of completed tasks
pub struct CompletedTaskList {
    /// List of completed tasks
    tasks: Vec<CompletedTask>,
}

impl CompletedTaskList {
    pub fn new(sources: Vec<TaskSrc>) -> Result<Self> {
        let mut tasks: Vec<CompletedTask> = vec![];
        for source in sources {
            tasks.push(CompletedTask::new(
                &source.data,
                source.kind,
                source.location,
            )?);
        }
        Ok(Self { tasks })
    }

    fn contains_project(self, name: String) -> bool {
        self.tasks.into_iter().any(|t| t.project == name)
    }

    fn get_project_tasks(self, name: String) -> CompletedTaskList {
        CompletedTaskList {
            tasks: self
                .tasks
                .into_iter()
                .filter(|t| t.project == name)
                .collect(),
        }
    }
}

#[derive(Debug, Clone)]
/// Representation of a list of tasks
pub struct TaskList {
    /// List of todo tasks
    tasks: Vec<Task>,
}

impl TaskList {
    pub fn new(sources: Vec<TaskSrc>) -> Result<Self> {
        let mut tasks: Vec<Task> = vec![];
        for source in sources {
            tasks.push(Task::new(&source.data, source.kind, source.location)?);
        }
        tasks.sort();
        Ok(Self { tasks })
    }

    fn contains_project(self, name: String) -> bool {
        self.tasks.into_iter().any(|t| t.project == name)
    }

    fn get_project_tasks(self, name: String) -> TaskList {
        TaskList {
            tasks: self
                .tasks
                .into_iter()
                .filter(|t| t.project == name)
                .collect(),
        }
    }

    pub fn get_current_task(self) -> Option<Task> {
        if self.tasks.is_empty() {
            None
        } else {
            self.tasks.first().map(|task| task.to_owned())
        }
    }

    pub fn complete_current_task(self) -> Result<()> {
        if let Some(current_task) = self.get_current_task() {
            let task_line = current_task.raw.clone();
            let source_type = current_task.source_type.clone();
            let source_location = current_task.source_location.clone();
            egress::remove_task(task_line, source_type, source_location)?;
            let completed_task: CompletedTask = current_task.complete()?;
            egress::add_completed_task(
                completed_task.raw,
                completed_task.source_type,
                completed_task.source_location,
            )?;
            Ok(())
        } else {
            Err(anyhow!("Could not obtain and complete current task."))
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    const TEST_DATA: &str = r"(C) alpha task 1 +alpha @context
(D) bravo task 1 @context +bravo
(B) bravo task 2 +bravo @context
an unprioritised task 1 +monday @week
(D) alpha task 2 +alpha";

    const DONE_DATA: &str = r"x 2025-01-11 done alpha task 1 +alpha
x 2025-01-10 done bravo task 2 +bravo";

    const VALID_TASKS: &str = r"(A) A description's _fine_ example-sentence. +alph2a @context
(B) description 2 @context +alph2a
(C) description 3 +alph2a
(D) description 4 @context
(E) description 5
description 6 +alph2a @context
(F) description 7 @context +alph2a
description 8 +alph2a
description 9 @context
description 10";

    const INVALID_TASKS: &str = r"(b) description 1 @context +alph2a
(C) description 2 +alph2a desc
() description & ? ! , ; 3 @context

(3) description 4
description 5 +alph2a description @context
description 6 +alph2a description
description @ 7
description + 8";

    fn get_test_sources(location: String, test_data: &str) -> Vec<TaskSrc> {
        let mut sources: Vec<TaskSrc> = vec![];
        for data in test_data.to_string().lines() {
            let test_task_src = TaskSrc {
                data: data.to_string(),
                kind: SrcType::File,
                location: location.clone(),
            };
            sources.push(test_task_src);
        }
        sources
    }

    fn get_test_tasklist(location: String) -> TaskList {
        let sources = get_test_sources(location.clone(), TEST_DATA);
        TaskList::new(sources).unwrap()
    }

    fn get_test_completedtasklist(location: String) -> CompletedTaskList {
        let sources = get_test_sources(location.clone(), DONE_DATA);
        CompletedTaskList::new(sources).unwrap()
    }

    #[test]
    fn test_search_project() {
        let name = "alpha".to_string();
        let location = "/path/to/source".to_string();

        let todo_tasks = get_test_tasklist(location.clone());
        let done_tasks = get_test_completedtasklist(location);
        let result = Project::search_project(name, todo_tasks.clone(), done_tasks).unwrap();

        assert_eq!(result.name, "alpha");
        assert_eq!(result.todo, 2);
        assert_eq!(result.done, 1);
    }

    #[test]
    fn test_project_get_current_task() {
        let name = "alpha".to_string();
        let location = "/path/to/source".to_string();

        let todo_tasks = get_test_tasklist(location.clone());
        let done_tasks = get_test_completedtasklist(location);
        let result = Project::search_project(name, todo_tasks.clone(), done_tasks)
            .unwrap()
            .clone()
            .get_current_task()
            .unwrap();

        assert_eq!(result.raw, "(C) alpha task 1 +alpha @context");
        assert_eq!(result.priority, 'C');
        assert_eq!(result.description, "alpha task 1");
        assert_eq!(result.project, "alpha");
        assert_eq!(result.context, "context");
        assert_eq!(result.source_type, SrcType::File);
        assert_eq!(result.source_location, "/path/to/source");
    }

    #[test]
    fn test_unprioritised_task() {
        let name = "monday".to_string();
        let location = "/path/to/source".to_string();

        let todo_tasks = get_test_tasklist(location.clone());
        let done_tasks = get_test_completedtasklist(location);
        let result = Project::search_project(name, todo_tasks.clone(), done_tasks)
            .unwrap()
            .clone()
            .get_current_task()
            .unwrap();

        assert_eq!(result.raw, "an unprioritised task 1 +monday @week");
        assert_eq!(result.priority, 'Z');
        assert_eq!(result.description, "an unprioritised task 1");
        assert_eq!(result.project, "monday");
        assert_eq!(result.context, "week");
        assert_eq!(result.source_type, SrcType::File);
        assert_eq!(result.source_location, "/path/to/source");
    }

    #[test]
    fn test_tasklist_get_current_task() {
        let location = "/path/to/source".to_string();

        let result = get_test_tasklist(location.clone())
            .get_current_task()
            .unwrap();

        assert_eq!(result.raw, "(B) bravo task 2 +bravo @context");
        assert_eq!(result.priority, 'B');
        assert_eq!(result.description, "bravo task 2");
        assert_eq!(result.project, "bravo");
        assert_eq!(result.context, "context");
        assert_eq!(result.source_type, SrcType::File);
        assert_eq!(result.source_location, "/path/to/source");
    }

    #[test]
    fn test_task_complete_output() {
        let location = "/path/to/source".to_string();

        let current_task = get_test_tasklist(location.clone())
            .get_current_task()
            .unwrap();

        let result = current_task.complete().unwrap();
        let today = Local::now().format("%Y-%m-%d").to_string();
        let mut raw = String::new();
        raw.push('x');
        raw.push(' ');
        raw.push_str(&today);
        raw.push(' ');
        raw.push_str("bravo task 2");
        raw.push(' ');
        raw.push_str("+bravo");
        raw.push(' ');
        raw.push_str("@context");

        assert_eq!(result.completion_date, today);
        assert_eq!(result.description, "bravo task 2");
        assert_eq!(result.raw, raw);
        assert_eq!(result.project, "bravo");
        assert_eq!(result.context, "context");
    }

    #[test]
    fn test_valid_tasks() {
        for line in VALID_TASKS.lines() {
            assert!(Task::validate_todo_task_line(line).is_ok());
        }
    }

    #[test]
    fn test_invalid_tasks() {
        for line in INVALID_TASKS.lines() {
            assert!(Task::validate_todo_task_line(line).is_err());
        }
    }
}