tasks-cli-rs 0.6.1

Markdown-based TODO task management CLI: each task is a Markdown file with YAML front matter
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
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};
use crate::model::{Task, TaskMeta};

const FRONT_MATTER_DELIM: &str = "---";

#[derive(Deserialize)]
struct LegacyStep {
    title: String,
    #[serde(default)]
    status: String,
}

/// Parses a task file: YAML front matter followed by a Markdown body.
/// Migrates legacy YAML steps into body checkboxes when needed.
pub fn parse_task(content: &str) -> Result<Task> {
    let rest = content
        .strip_prefix(FRONT_MATTER_DELIM)
        .and_then(|r| r.strip_prefix('\n'))
        .ok_or_else(|| Error::InvalidTaskFile("missing front matter".into()))?;
    let end = rest
        .find("\n---")
        .ok_or_else(|| Error::InvalidTaskFile("unterminated front matter".into()))?;
    let yaml = &rest[..end];
    let body_start = rest[end + 1..]
        .find('\n')
        .map(|i| end + 1 + i + 1)
        .unwrap_or(rest.len());
    let mut body = rest[body_start..].trim_start_matches('\n').to_string();

    let raw: serde_yaml::Value = serde_yaml::from_str(yaml)?;
    let legacy_steps: Vec<LegacyStep> = raw
        .get("steps")
        .map(|v| serde_yaml::from_value(v.clone()).unwrap_or_default())
        .unwrap_or_default();
    let meta: TaskMeta = serde_yaml::from_value(raw)?;
    meta.validate().map_err(Error::InvalidTaskFile)?;

    // Migrate: legacy YAML steps become the TODO block above the content
    if !legacy_steps.is_empty() && crate::checkbox::parse_checkboxes(&body).is_empty() {
        let steps: Vec<(String, bool)> = legacy_steps
            .iter()
            .map(|s| (s.title.clone(), s.status == "done"))
            .collect();
        body = crate::checkbox::prepend_steps(&body, &steps);
    }

    let steps = crate::checkbox::parse_checkboxes(&body);
    Ok(Task { meta, body, steps })
}

/// Renders a task back to file content. Round-trips with `parse_task`.
pub fn render_task(task: &Task) -> Result<String> {
    let yaml = serde_yaml::to_string(&task.meta)?;
    let mut out = format!("{FRONT_MATTER_DELIM}\n{yaml}{FRONT_MATTER_DELIM}\n");
    if !task.body.is_empty() {
        out.push('\n');
        out.push_str(&task.body);
        if !task.body.ends_with('\n') {
            out.push('\n');
        }
    }
    Ok(out)
}

pub fn read_task(path: &Path) -> Result<Task> {
    let content = std::fs::read_to_string(path)?;
    parse_task(&content).map_err(|e| match e {
        Error::Yaml(y) => Error::InvalidTaskFile(format!("{}: {y}", path.display())),
        Error::InvalidTaskFile(msg) => Error::InvalidTaskFile(format!("{}: {msg}", path.display())),
        other => other,
    })
}

pub fn write_task(path: &Path, task: &Task) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, render_task(task)?)?;
    Ok(())
}

/// Converts a title into a filesystem-safe slug. Unicode alphanumeric
/// characters (including CJK) are kept; everything else becomes '-'.
pub fn slugify(title: &str) -> String {
    let mut slug = String::new();
    let mut prev_dash = true;
    for c in title.chars() {
        if c.is_alphanumeric() {
            slug.extend(c.to_lowercase());
            prev_dash = false;
        } else if !prev_dash {
            slug.push('-');
            prev_dash = true;
        }
    }
    slug.trim_end_matches('-').to_string()
}

/// Default filename template; `{short_id}` guarantees uniqueness.
pub const DEFAULT_FILENAME_FORMAT: &str = "{date}-{slug}-{short_id}";

/// Renders a task filename from a template. Supported variables:
/// {date} {datetime} {seq} {slug} {short_id}. `{short_id}` is appended
/// automatically when missing. Returns the name with ".md" extension.
pub fn render_filename(template: &str, task: &Task) -> Result<String> {
    let mut template = template.to_string();
    if !template.contains("{short_id}") {
        template.push_str("-{short_id}");
    }
    let local = task.meta.created_at.with_timezone(&chrono::Local);
    let mut out = String::new();
    let mut rest = template.as_str();
    while let Some(start) = rest.find('{') {
        out.push_str(&rest[..start]);
        let Some(end) = rest[start..].find('}') else {
            return Err(Error::BadTemplate(format!("unclosed '{{' in '{template}'")));
        };
        let var = &rest[start + 1..start + end];
        match var {
            "date" => out.push_str(&local.format("%Y-%m-%d").to_string()),
            "datetime" => out.push_str(&local.format("%Y%m%d-%H%M").to_string()),
            "seq" => out.push_str(&task.meta.seq.to_string()),
            "slug" => out.push_str(&slugify(&task.meta.title)),
            "short_id" => out.push_str(&task.short_id()),
            other => {
                return Err(Error::BadTemplate(format!("unknown variable '{{{other}}}'")));
            }
        }
        rest = &rest[start + end + 1..];
    }
    out.push_str(rest);
    let name: String = out
        .chars()
        .map(|c| if c == '/' || c == '\\' { '-' } else { c })
        .collect();
    // Collapse consecutive dashes (e.g. from empty slug) and trim edges
    let mut collapsed = String::new();
    let mut prev_dash = false;
    for c in name.chars() {
        if c == '-' {
            if !prev_dash {
                collapsed.push(c);
            }
            prev_dash = true;
        } else {
            collapsed.push(c);
            prev_dash = false;
        }
    }
    let name = collapsed.trim_matches(|c| c == '-' || c == '.' || c == ' ').to_string();
    Ok(format!("{name}.md"))
}

/// Filename for a task using the default template.
#[cfg(test)]
pub fn task_filename(task: &Task) -> String {
    render_filename(DEFAULT_FILENAME_FORMAT, task).expect("default template is valid")
}

/// A task together with the file it was loaded from.
#[derive(Debug)]
pub struct StoredTask {
    pub path: std::path::PathBuf,
    pub task: Task,
}

/// Result of scanning a library: parsed tasks plus files that look like
/// tasks but could not be parsed (candidates for `tasks adopt`).
#[derive(Debug, Default)]
pub struct LoadOutcome {
    pub tasks: Vec<StoredTask>,
    pub skipped: Vec<std::path::PathBuf>,
}

fn is_ignored(patterns: &[glob::Pattern], root: &Path, path: &Path) -> bool {
    let rel = path.strip_prefix(root).unwrap_or(path);
    patterns.iter().any(|p| {
        p.matches_path(rel)
            || rel
                .file_name()
                .is_some_and(|n| p.matches(&n.to_string_lossy()))
    })
}

/// Recursively scans all *.md files under `root`, skipping hidden entries
/// and the library's `ignore` glob patterns. Unparseable files are collected
/// in `skipped` instead of being reported inline.
pub fn load_library(root: &Path) -> Result<LoadOutcome> {
    let meta = LibraryMeta::load(root)?;
    let mut patterns = Vec::new();
    for pat in &meta.ignore {
        patterns.push(
            glob::Pattern::new(pat)
                .map_err(|e| Error::BadTemplate(format!("bad ignore pattern '{pat}': {e}")))?,
        );
    }
    let mut outcome = LoadOutcome::default();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let path = entry.path();
            let name = entry.file_name();
            if name.to_string_lossy().starts_with('.') {
                continue;
            }
            // archived tasks are excluded from normal scans at any depth;
            // browse them explicitly via a scope like `--dir archive/2026-08`
            if path.is_dir() && name == "archive" {
                continue;
            }
            if is_ignored(&patterns, root, &path) {
                continue;
            }
            if path.is_dir() {
                stack.push(path);
            } else if path.extension().is_some_and(|e| e == "md") {
                match read_task(&path) {
                    Ok(task) => outcome.tasks.push(StoredTask { path, task }),
                    Err(_) => outcome.skipped.push(path),
                }
            }
        }
    }
    outcome.tasks.sort_by_key(|t| t.task.meta.seq);
    outcome.skipped.sort();
    Ok(outcome)
}

/// Resolves a user-supplied identifier (seq, #seq, short id, or UUID) to a
/// single task.
pub fn resolve_task(root: &Path, query: &str) -> Result<StoredTask> {
    let mut matches: Vec<StoredTask> = load_library(root)?
        .tasks
        .into_iter()
        .filter(|t| t.task.matches_identifier(query))
        .collect();
    match matches.len() {
        0 => Err(Error::TaskNotFound(query.to_string())),
        1 => Ok(matches.remove(0)),
        _ => Err(Error::AmbiguousId(query.to_string())),
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct LibraryMeta {
    #[serde(default = "default_next_seq")]
    pub next_seq: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filename_format: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ignore: Vec<String>,
}

fn default_next_seq() -> u64 {
    1
}

impl LibraryMeta {
    pub fn path(library_root: &Path) -> std::path::PathBuf {
        library_root.join(".tasks-meta.toml")
    }

    /// Creates the meta file with defaults if it does not exist yet.
    pub fn default_init(library_root: &Path) -> Result<()> {
        if !Self::path(library_root).exists() {
            LibraryMeta { next_seq: 1, filename_format: None, ignore: Vec::new() }
                .save(library_root)?;
        }
        Ok(())
    }

    pub fn load(library_root: &Path) -> Result<Self> {
        let path = Self::path(library_root);
        if !path.exists() {
            return Ok(LibraryMeta { next_seq: 1, filename_format: None, ignore: Vec::new() });
        }
        Ok(toml::from_str(&std::fs::read_to_string(path)?)?)
    }

    pub fn save(&self, library_root: &Path) -> Result<()> {
        std::fs::create_dir_all(library_root)?;
        let content =
            toml::to_string(self).map_err(|e| Error::InvalidTaskFile(e.to_string()))?;
        std::fs::write(Self::path(library_root), content)?;
        Ok(())
    }

    /// Returns the next sequence number and persists the incremented counter.
    pub fn allocate_seq(library_root: &Path) -> Result<u64> {
        let mut meta = Self::load(library_root)?;
        let seq = meta.next_seq;
        meta.next_seq += 1;
        meta.save(library_root)?;
        Ok(seq)
    }
}

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

    fn sample_task() -> Task {
        let mut task = Task::new(7, "Fix login bug");
        task.meta.tags = vec!["backend".into(), "bugfix".into()];
        task.body = "## Notes\n\nSome details here.\n\n- [x] Reproduce\n".to_string();
        task.steps = crate::checkbox::parse_checkboxes(&task.body);
        task
    }

    #[test]
    fn round_trip_preserves_everything() {
        let task = sample_task();
        let rendered = render_task(&task).unwrap();
        let parsed = parse_task(&rendered).unwrap();
        assert_eq!(parsed, task);
    }

    #[test]
    fn round_trip_empty_body() {
        let task = Task::new(1, "no body");
        let parsed = parse_task(&render_task(&task).unwrap()).unwrap();
        assert_eq!(parsed, task);
    }

    #[test]
    fn parse_rejects_missing_front_matter() {
        assert!(parse_task("just some text").is_err());
        assert!(parse_task("---\nid: x").is_err());
    }

    #[test]
    fn migration_converts_yaml_steps_to_checkboxes() {
        let content = "---\nid: 550e8400-e29b-41d4-a716-446655440000\nseq: 1\ntitle: Old task\ncreated_at: 2026-01-01T00:00:00Z\nsteps:\n  - id: s1\n    title: Design\n    status: done\n  - id: s2\n    title: Implement\n    status: todo\n---\n\nSome body.\n";
        let task = parse_task(content).unwrap();
        assert_eq!(task.steps.len(), 2);
        assert!(task.steps[0].done);
        assert!(!task.steps[1].done);
        assert!(task.body.contains("- [x] Design"));
        assert!(task.body.contains("- [ ] Implement"));
    }

    #[test]
    fn migration_skipped_when_body_has_checkboxes() {
        let content = "---\nid: 550e8400-e29b-41d4-a716-446655440000\nseq: 1\ntitle: T\ncreated_at: 2026-01-01T00:00:00Z\nsteps:\n  - id: s1\n    title: Old\n    status: todo\n---\n\n- [ ] Already here\n";
        let task = parse_task(content).unwrap();
        assert_eq!(task.steps.len(), 1);
        assert_eq!(task.steps[0].title, "Already here");
    }

    #[test]
    fn validation_rejects_empty_title() {
        let content = "---\nid: 550e8400-e29b-41d4-a716-446655440000\nseq: 1\ntitle: \"  \"\ncreated_at: 2026-01-01T00:00:00Z\n---\n";
        assert!(parse_task(content).is_err());
    }

    #[test]
    fn validation_rejects_zero_seq() {
        let content = "---\nid: 550e8400-e29b-41d4-a716-446655440000\nseq: 0\ntitle: T\ncreated_at: 2026-01-01T00:00:00Z\n---\n";
        assert!(parse_task(content).is_err());
    }

    #[test]
    fn slugify_handles_english() {
        assert_eq!(slugify("Fix Login Bug!"), "fix-login-bug");
        assert_eq!(slugify("  spaces   everywhere  "), "spaces-everywhere");
    }

    #[test]
    fn slugify_keeps_cjk() {
        assert_eq!(slugify("修复登录 bug"), "修复登录-bug");
    }

    #[test]
    fn slugify_special_chars_only_yields_empty() {
        assert_eq!(slugify("!!! ???"), "");
        let task = Task::new(1, "!!!");
        let name = task_filename(&task);
        assert!(name.ends_with(&format!("{}.md", task.short_id())), "{name}");
        assert!(!name.contains("--"), "no double dash from empty slug: {name}");
    }

    #[test]
    fn render_filename_variables() {
        let mut task = Task::new(7, "Fix Bug");
        task.meta.created_at = chrono::DateTime::parse_from_rfc3339("2026-07-30T12:00:00Z")
            .unwrap()
            .to_utc();
        let sid = task.short_id();
        let local_date = task
            .meta
            .created_at
            .with_timezone(&chrono::Local)
            .format("%Y-%m-%d")
            .to_string();

        assert_eq!(
            render_filename("{date}-{slug}-{short_id}", &task).unwrap(),
            format!("{local_date}-fix-bug-{sid}.md")
        );
        assert_eq!(
            render_filename("{seq}-{slug}", &task).unwrap(),
            format!("7-fix-bug-{sid}.md"),
            "short_id auto-appended when missing"
        );
    }

    #[test]
    fn render_filename_rejects_bad_templates() {
        let task = Task::new(1, "t");
        assert!(render_filename("{typo}-{short_id}", &task).is_err());
        assert!(render_filename("{date-{short_id}", &task).is_err());
    }

    #[test]
    fn render_filename_sanitizes_separators() {
        let task = Task::new(1, "t");
        let name = render_filename("a/b\\c-{short_id}", &task).unwrap();
        assert!(!name.contains('/') && !name.contains('\\'), "{name}");
    }

    #[test]
    fn render_filename_is_idempotent_for_same_task() {
        let task = Task::new(3, "stable name");
        let a = render_filename("{date}-{slug}-{short_id}", &task).unwrap();
        let b = render_filename("{date}-{slug}-{short_id}", &task).unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn seq_allocation_is_monotonic() {
        let dir = std::env::temp_dir().join(format!("tasks-test-{}", uuid::Uuid::new_v4()));
        assert_eq!(LibraryMeta::allocate_seq(&dir).unwrap(), 1);
        assert_eq!(LibraryMeta::allocate_seq(&dir).unwrap(), 2);
        assert_eq!(LibraryMeta::allocate_seq(&dir).unwrap(), 3);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn file_write_read_round_trip() {
        let dir = std::env::temp_dir().join(format!("tasks-test-{}", uuid::Uuid::new_v4()));
        let task = sample_task();
        let path = dir.join(task_filename(&task));
        write_task(&path, &task).unwrap();
        let loaded = read_task(&path).unwrap();
        assert_eq!(loaded, task);
        std::fs::remove_dir_all(&dir).unwrap();
    }
}