taskfinder 2.15.0

A terminal user interface that extracts and displays tasks from plain text files, hooking into your default terminal-based editor for editing.
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
#![forbid(unsafe_code)]
//! Working with files.

use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::env;
use std::fmt::{self, Display, Formatter};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
use std::str::FromStr;
use std::sync::LazyLock;
use std::time::SystemTime;

use chrono::NaiveDate;
use regex::Regex;

use crate::priority::make_priority_map;
use crate::{
    TASK_IDENTIFIERS, TfError,
    config::{Config, ConfigError},
    priority::Priority,
    tasks::{Task, TaskSet},
};

// Configure regex for finding due dates.
pub static DUE_DATE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?:(?:due:|📅 ))([0-9]{4}-[0-9]{2}-[0-9]{2})").unwrap());
pub static COMPLETED_DATE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?:(?:completed:|✅ ))([0-9]{4}-[0-9]{2}-[0-9]{2})").unwrap());
pub static RECURRING_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\([1-9]*[dwmy]\))").unwrap());

// regex for finding tags.
pub static TAG_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?<tag>#[\w&&[^\s]&&[^#]+]+)").unwrap());

// regex for order.
pub static ORDER_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?:::[0-9]*)").unwrap());

/// How a file can be categorized.
#[derive(PartialEq, Clone, Debug)]
pub enum FileStatus {
    Active,
    Archived,
    Stale,
}

impl Display for FileStatus {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            FileStatus::Active => write!(f, "active"),
            FileStatus::Archived => write!(f, "archived"),
            FileStatus::Stale => write!(f, "stale"),
        }
    }
}

/// A file that contains tasks.
#[derive(Debug, Clone)]
pub struct FileWithTasks {
    pub file: PathBuf,
    pub last_modified: SystemTime,
    pub priority: Option<Priority>,
    pub status: FileStatus,
    pub has_due_date: bool,
    pub head: Vec<String>,
    pub tags: Vec<String>,
    pub task_sets: Vec<TaskSet>,
}

impl FileWithTasks {
    /// Get all files from configured directory that contain tasks.
    pub fn collect(config: &Config) -> Result<Vec<FileWithTasks>, TfError> {
        // Gather all possible files to examine.
        let paths = collect_file_paths(&config.path, &config.file_extensions, vec![])?;

        let priority_map = make_priority_map(config.priority_markers.clone());

        // Extract the tasks.
        let mut files_with_tasks: Vec<FileWithTasks> = vec![];
        for path in &paths {
            if let Ok(Some(v)) = Self::extract(path, config.days_to_stale, priority_map.clone()) {
                files_with_tasks.push(v);
            }
        }
        // Sort tasks sets within files.
        for file in files_with_tasks.iter_mut() {
            file.task_sets
                .sort_unstable_by_key(|task_set| Reverse(task_set.priority))
        }

        Ok(files_with_tasks)
    }

    /// Extract data from a file.
    pub fn extract(
        path: &Path,
        days_to_stale: u64,
        priority_map: BTreeMap<Priority, String>,
    ) -> Result<Option<FileWithTasks>, TfError> {
        let contents = match fs::read_to_string(path) {
            Ok(v) => v,
            Err(_) => return Ok(None),
        };

        if !contents.contains("TODO") {
            return Ok(None);
        }

        let last_modified = fs::metadata(path)?.modified()?;

        // Set file status.
        let stale_threshold = std::time::Duration::from_secs(60 * 60 * 24 * days_to_stale);
        let status = if contents.contains("@archived") {
            FileStatus::Archived
        } else if last_modified.elapsed()? > stale_threshold {
            FileStatus::Stale
        } else {
            FileStatus::Active
        };

        // The first two lines of the file - the title and tags - are the head.
        let head: Vec<String> = contents.lines().take(2).map(String::from).collect();

        // File-level tags.
        let file_tags: Vec<String> = TAG_RE
            .find_iter(&head.join(""))
            .map(|m| m.as_str().strip_prefix("#").unwrap().to_string())
            .collect();

        // file-level priority
        let file_priority = Priority::extract(&head.join("\n"), priority_map.clone());

        // Create the FileWithTasks.
        let mut file_with_tasks = FileWithTasks {
            file: path.to_path_buf(),
            last_modified,
            priority: file_priority,
            status,
            has_due_date: false,
            head,
            tags: file_tags.clone(),
            task_sets: vec![],
        };

        let mut task_set: Option<TaskSet> = None;
        for (i, line) in contents.lines().enumerate() {
            // Don't do anything with a line until there's a taskset.
            if task_set.is_none() && !line.trim().contains("TODO") {
                continue;
            }

            // Create TaskSet if we come to a TODO section
            if line.trim().contains("TODO") {
                // If there was an existing TaskSet, we've come to a new one,
                // so save the existing one by appending it to Vec we're returning.
                if let Some(v) = task_set {
                    file_with_tasks.task_sets.push(v);
                }

                // Start new TaskSet.
                let mut task_set_priority = Priority::extract(line, priority_map.clone());
                let mut task_set_due_date = None;
                let mut task_set_completed_date = None;

                // If the task set has no priority, it inherits the priority of its file, if any.
                // (Unless it has the explicit no priority marker.)
                if task_set_priority.is_none()
                    && !matches!(file_priority, Some(Priority::NoPriority))
                {
                    task_set_priority = file_priority;
                }

                if let Some(dd) = DUE_DATE_RE.find(line.trim()) {
                    task_set_due_date = Some(make_date(dd.as_str()));
                }

                if let Some(cd) = COMPLETED_DATE_RE.find(line.trim()) {
                    task_set_completed_date = Some(make_date(cd.as_str()));
                }

                // Taskset-level tags, which inherit/include the file-level tags.
                let mut ts_tags: Vec<String> = TAG_RE
                    .find_iter(line.trim())
                    .map(|m| m.as_str().strip_prefix("#").unwrap().to_string())
                    .collect();
                ts_tags.append(&mut file_tags.clone());

                // Get the name of the task set only.
                let mut ts_text = line.to_string();

                if !ts_tags.is_empty() {
                    for tag in &ts_tags {
                        ts_text = ts_text.replace(&format!("#{tag}"), "");
                    }
                }
                if let Some(dd) = task_set_due_date {
                    ts_text = ts_text.replace(&format!("due:{dd}"), "");
                }
                if let Some(cd) = task_set_completed_date {
                    ts_text = ts_text.replace(&format!("completed:{cd}"), "");
                }
                if let Some(v) = task_set_priority {
                    ts_text = ts_text.replace(&v.as_string(priority_map.clone()), "");
                }
                ts_text = ts_text.trim_end().to_string();

                task_set = Some(TaskSet::new(
                    ts_text,
                    task_set_priority,
                    task_set_due_date,
                    task_set_completed_date,
                    ts_tags,
                ));
                continue;
            }

            // Extract tasks if we're in a task set.
            if let Some(ts) = &mut task_set {
                for ider in TASK_IDENTIFIERS {
                    if line.trim_start().starts_with(ider) {
                        // Set priority at the task level, inheriting if necessary.
                        let mut task_priority = Priority::extract(line, priority_map.clone());
                        if task_priority.is_none() {
                            if ts.priority.is_some() {
                                task_priority = ts.priority;
                            } else if file_priority.is_some() {
                                task_priority = file_priority;
                            }
                        }

                        // Set due date at the task level, inheriting if necessary.
                        let due_date = if let Some(dd) = DUE_DATE_RE.find(line) {
                            Some(make_date(dd.as_str()))
                        } else {
                            ts.due_date
                        };

                        // Set completed date at the task level, inheriting if necessary.
                        let completed_date = if let Some(cd) = COMPLETED_DATE_RE.find(line) {
                            Some(make_date(cd.as_str()))
                        } else {
                            ts.completed_date
                        };

                        let completed = line.trim().to_lowercase().starts_with("[x]")
                            || line.trim().to_lowercase().starts_with("- [x]");

                        // Set recurring status
                        let recurring = RECURRING_RE.is_match(line);

                        // Task-level tags, which inherit taskset-level tags (which in turn
                        // inherited file-level tags).
                        let mut task_tags: Vec<String> = TAG_RE
                            .find_iter(line.trim())
                            .map(|m| m.as_str().strip_prefix("#").unwrap().to_string())
                            .collect();
                        task_tags.append(&mut ts.tags.clone());

                        // Set order, if any
                        let order = if let Some(o) = ORDER_RE.find(line) {
                            o.as_str().strip_prefix("::").unwrap().parse().ok()
                        } else {
                            None
                        };

                        // Get task name only.
                        let mut task_text = line.to_string();
                        if let Some(dd) = due_date {
                            task_text = task_text.replace(&format!("due:{dd}"), "");
                            task_text = task_text.replace(&format!("📅 {dd}"), "");
                        }
                        if let Some(cd) = completed_date {
                            task_text = task_text.replace(&format!("completed:{cd}"), "");
                            task_text = task_text.replace(&format!("✅ {cd}"), "");
                        }
                        if !task_tags.is_empty() {
                            for tag in &task_tags {
                                task_text = task_text.replace(&format!("#{tag}"), "");
                            }
                        }
                        if let Some(o) = order {
                            task_text = task_text.replace(&format!("::{o}"), "");
                        }
                        if let Some(v) = task_priority {
                            task_text = task_text.replace(&v.as_string(priority_map.clone()), "");
                        }
                        task_text = task_text.trim_end().to_string();

                        let task = Task {
                            text: task_text,
                            completed,
                            recurring,
                            completed_date,
                            due_date,
                            priority: task_priority,
                            tags: task_tags,
                            line: i + 1,
                            order,
                        };

                        // Indicate if the file has a task with a due date, to ease work elsewhere.
                        if task.due_date.is_some() {
                            file_with_tasks.has_due_date = true;
                        }
                        ts.tasks.push(task);
                        break;
                    }
                }
            }
        }
        // Add last/only TaskSet to the FileWithTasks
        if let Some(v) = task_set {
            file_with_tasks.task_sets.push(v);
        }

        // If any task set contains tasks, return it. Otherwise (if all tasks sets are empty),
        // it falls through to returning None.
        for task_set in &file_with_tasks.task_sets {
            if !task_set.tasks.is_empty() {
                return Ok(Some(file_with_tasks));
            }
        }
        Ok(None)
    }
}

/// Create date from text.
///
/// If the date is invalid, this sets it to one long in the past to indicate that to the user.
fn make_date(s: &str) -> NaiveDate {
    let date_reversed = s.chars().rev().take(10).collect::<String>();
    let date = date_reversed.chars().rev().collect::<String>();

    match NaiveDate::from_str(&date) {
        Ok(v) => v,
        Err(_) => NaiveDate::from_str("1900-01-01").unwrap(),
    }
}

/// Collect all paths within configured directory and with specified extensions, ignoring any
/// full paths listed in the ignore file.
fn collect_file_paths(
    dir: &Path,
    extensions: &Vec<String>,
    mut results: Vec<PathBuf>,
) -> Result<Vec<PathBuf>, TfError> {
    // Get ignored directories.
    let mut config_dir = match dirs::config_dir() {
        Some(v) => v,
        None => return Err(ConfigError::LocateConfigDir)?,
    };
    config_dir.push("taskfinder/ignore");
    let ignored_dirs = match fs::read_to_string(config_dir) {
        Ok(v) => v
            .lines()
            .filter(|l| !l.is_empty())
            .map(Path::new)
            .map(|p| p.to_path_buf())
            .collect::<Vec<_>>(),
        Err(_) => vec![],
    };

    // Loop through directories, excluding ignored, and
    if dir.is_dir() {
        'outer: for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                if !ignored_dirs.is_empty() {
                    for ignored_dir in &ignored_dirs {
                        if path.starts_with(ignored_dir) {
                            continue 'outer;
                        }
                    }
                }
                results = collect_file_paths(&path, extensions, results)?;
            } else if let Some(v) = path.extension()
                && extensions.contains(&v.to_str().unwrap().to_owned())
            {
                results.push(path)
            }
        }
    }
    Ok(results)
}

/// Open a file for editing.
pub fn edit(file: PathBuf, line: Option<usize>) -> io::Result<ExitStatus> {
    let editor = match env::var("EDITOR") {
        Ok(v) => v,
        Err(_) => String::from("vim"),
    };

    if let Some(v) = line {
        if ["helix", "hx", "vi", "vim", "nvim"].contains(&editor.as_str()) {
            Command::new(editor)
                .args([file, format!("+{v}").into()])
                .status()
        } else {
            Command::new(editor).args([file]).status()
        }
    } else {
        Command::new(editor).args([file]).status()
    }
}

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

    #[test]
    fn make_date_due_date() {
        assert_eq!(
            make_date("due:2025-11-01"),
            NaiveDate::from_str("2025-11-01").unwrap()
        )
    }
    #[test]
    fn make_date_due_emoji_date() {
        assert_eq!(
            make_date("✅ 2025-11-01"),
            NaiveDate::from_str("2025-11-01").unwrap()
        )
    }
    #[test]
    fn make_date_completed_date() {
        assert_eq!(
            make_date("completed:2025-11-01"),
            NaiveDate::from_str("2025-11-01").unwrap()
        )
    }
    #[test]
    fn make_date_completed_emoji_date() {
        assert_eq!(
            make_date("📅 2025-11-01"),
            NaiveDate::from_str("2025-11-01").unwrap()
        )
    }
    #[test]
    fn make_date_handles_invalid_date() {
        assert_eq!(
            make_date("due:2025-04-31"),
            NaiveDate::from_str("1900-01-01").unwrap()
        )
    }
}