diff --git a/.cubil/done/deepen-the-roadmap-module.md b/.cubil/done/deepen-the-roadmap-module.md new file mode 100644 index 0000000..e235b21 --- /dev/null +++ b/.cubil/done/deepen-the-roadmap-module.md @@ -0,0 +1,22 @@ +--- +created: 2026-11-12 +--- + +# Deepen the Roadmap module + +Create a Roadmap module that parses a roadmap once and offers render_resolved, add_task and next_not_done. + +## Problem +The task-line and Milestone grammar lives in `core/roadmap.rs`, while rewriting (`roadmap/show.rs`), inserting (`roadmap/add.rs`) and next-task selection (`roadmap/next.rs`) each re-read it. `write_atomic` is copied in show and add. `root_for_roadmap` forwards to `find_root`. About 40 unit tests pin private helpers. + +## Scope +- Interface: Roadmap::parse(src), .render_resolved(tasks), .add_task(slug, milestone), .next_not_done(tasks), plus one atomic save. +- Move `TaskStatus` next to the Task store. +- Commands parse, call one method and print. + +## Done when +- One copy of write_atomic. +- Unit tests for line handling move to the Roadmap interface. +- tests/roadmap.rs passes unchanged. + +Depends on: deepen-the-task-store. diff --git a/src/commands/roadmap/add.rs b/src/commands/roadmap/add.rs index 7347d4c..2275d4d 100644 --- a/src/commands/roadmap/add.rs +++ b/src/commands/roadmap/add.rs @@ -1,324 +1,22 @@ -use std::path::Path; - use crate::core::error::{CubilError, Result}; -use crate::core::roadmap::{ - parse_h2_heading, parse_milestone_heading, parse_task_line, resolve_roadmap, -}; +use crate::core::roadmap::{Roadmap, resolve_roadmap}; use crate::core::store::TaskStore; /// Append `- [ ] ` to a roadmap. /// -/// With `milestone == None`, appends to the end of the last milestone in the -/// file. If the file has no milestones, appends to end of file. With -/// `milestone == Some(name)`, appends to the end of that named milestone's -/// section (errors if missing or ambiguous). -/// /// Validates that `task_slug` exists in some status folder (backlog, doing, -/// done, or any custom one). No forward references. Errors if the task is -/// already listed anywhere in this roadmap. -pub fn run(roadmap_slug: String, task_slug: String, milestone: Option<&str>) -> Result<()> { +/// done, or any custom one). No forward references. See +/// [`Roadmap::add_task`] for placement and duplicate rules. +pub fn run(roadmap_slug: &str, task_slug: String, milestone: Option<&str>) -> Result<()> { let store = TaskStore::discover()?; - let path = resolve_roadmap(store.root(), &roadmap_slug)?; + let path = resolve_roadmap(store.root(), roadmap_slug)?; // Validate task exists somewhere. Ambiguity is tolerated here. if !store.lookup()?.contains_key(&task_slug) { return Err(CubilError::SlugNotFound(task_slug)); } - let src = std::fs::read_to_string(&path)?; - - // Reject duplicate task in the same roadmap. - if find_existing_task(&src, &task_slug) { - return Err(CubilError::TaskAlreadyInRoadmap { - roadmap: roadmap_slug, - task: task_slug, - }); - } - - let new_src = insert_task_line(&src, milestone, &roadmap_slug, &task_slug)?; - write_atomic(&path, new_src.as_bytes())?; - Ok(()) -} - -fn find_existing_task(src: &str, task_slug: &str) -> bool { - for line in src.lines() { - if let Some(parsed) = parse_task_line(line) - && parsed.slug == task_slug - { - return true; - } - } - false -} - -fn insert_task_line( - src: &str, - milestone: Option<&str>, - roadmap_slug: &str, - task_slug: &str, -) -> Result { - let lines: Vec<&str> = src.split_inclusive('\n').collect(); - - let section = match milestone { - Some(name) => Some(find_named_milestone(&lines, name, roadmap_slug)?), - None => find_last_milestone(&lines), - }; - - let insert_line_idx = match section { - Some((start, end)) => insert_position_in_section(&lines, start, end), - None => lines.len(), - }; - - let byte_offset: usize = lines[..insert_line_idx].iter().map(|l| l.len()).sum(); - - let needs_leading_newline = byte_offset > 0 && src.as_bytes()[byte_offset - 1] != b'\n'; - - let mut out = String::with_capacity(src.len() + task_slug.len() + 8); - out.push_str(&src[..byte_offset]); - if needs_leading_newline { - out.push('\n'); - } - out.push_str("- [ ] "); - out.push_str(task_slug); - out.push('\n'); - out.push_str(&src[byte_offset..]); - Ok(out) -} - -/// Find the line indices `(start, end)` of the section beginning at the named -/// milestone heading. Errors if missing or ambiguous. -fn find_named_milestone( - lines: &[&str], - target: &str, - roadmap_slug: &str, -) -> Result<(usize, usize)> { - let mut hits: Vec = Vec::new(); - for (i, line) in lines.iter().enumerate() { - let stripped = strip_eol(line); - if let Some(name) = parse_milestone_heading(stripped) - && name == target - { - hits.push(i); - } - } - match hits.len() { - 0 => Err(CubilError::MilestoneNotFound { - roadmap: roadmap_slug.to_string(), - milestone: target.to_string(), - available: collect_milestone_names(lines), - }), - 1 => { - let start = hits[0]; - Ok((start, section_end(lines, start))) - } - _ => Err(CubilError::MilestoneAmbiguous { - roadmap: roadmap_slug.to_string(), - milestone: target.to_string(), - }), - } -} - -fn find_last_milestone(lines: &[&str]) -> Option<(usize, usize)> { - let mut last: Option = None; - for (i, line) in lines.iter().enumerate() { - if parse_milestone_heading(strip_eol(line)).is_some() { - last = Some(i); - } - } - last.map(|start| (start, section_end(lines, start))) -} - -/// A section runs from its `## ` heading line (inclusive) to the next `## ` -/// heading line (exclusive), or end of file. -fn section_end(lines: &[&str], start: usize) -> usize { - for (i, line) in lines.iter().enumerate().skip(start + 1) { - if parse_h2_heading(strip_eol(line)).is_some() { - return i; - } - } - lines.len() -} - -/// Insertion line index: just after the last non-blank line in the section -/// (excluding the heading itself). If the section has no body content, insert -/// right after the heading. -fn insert_position_in_section(lines: &[&str], start: usize, end: usize) -> usize { - let mut last_non_blank = start; - for (i, line) in lines.iter().enumerate().take(end).skip(start + 1) { - if !strip_eol(line).trim().is_empty() { - last_non_blank = i; - } - } - last_non_blank + 1 -} - -fn collect_milestone_names(lines: &[&str]) -> Vec { - lines - .iter() - .filter_map(|l| parse_milestone_heading(strip_eol(l)).map(str::to_string)) - .collect() -} - -fn strip_eol(s: &str) -> &str { - s.trim_end_matches('\n').trim_end_matches('\r') -} - -/// Atomic-ish write: write to a tempfile in the same directory and rename. -/// Survives crashes mid-write — readers never see a half-written roadmap. -fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> { - let parent = path.parent().expect("roadmap path has parent"); - let tmp = parent.join(format!( - ".{}.tmp", - path.file_name() - .expect("roadmap has filename") - .to_string_lossy() - )); - std::fs::write(&tmp, bytes)?; - std::fs::rename(&tmp, path)?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn insert_into_file_with_no_milestones_appends_at_eof() { - let src = "# Roadmap\n\nNarrative.\n"; - let out = insert_task_line(src, None, "r", "task-1").unwrap(); - assert_eq!(out, "# Roadmap\n\nNarrative.\n- [ ] task-1\n"); - } - - #[test] - fn insert_into_file_with_no_trailing_newline_adds_one() { - let src = "# Roadmap"; - let out = insert_task_line(src, None, "r", "task-1").unwrap(); - assert_eq!(out, "# Roadmap\n- [ ] task-1\n"); - } - - #[test] - fn default_appends_to_last_milestone() { - let src = "\ -# Roadmap - -## Milestone: A -- [ ] task-1 - -## Milestone: B -- [ ] task-3 -"; - let out = insert_task_line(src, None, "r", "task-4").unwrap(); - let expected = "\ -# Roadmap - -## Milestone: A -- [ ] task-1 - -## Milestone: B -- [ ] task-3 -- [ ] task-4 -"; - assert_eq!(out, expected); - } - - #[test] - fn named_milestone_inserts_before_trailing_blank() { - let src = "\ -# Roadmap - -## Milestone: A -- [ ] task-1 -- [ ] task-2 - -## Milestone: B -- [ ] task-3 -"; - let out = insert_task_line(src, Some("A"), "r", "task-x").unwrap(); - let expected = "\ -# Roadmap - -## Milestone: A -- [ ] task-1 -- [ ] task-2 -- [ ] task-x - -## Milestone: B -- [ ] task-3 -"; - assert_eq!(out, expected); - } - - #[test] - fn named_milestone_with_no_body_inserts_right_after_heading() { - let src = "\ -## Milestone: A -## Milestone: B -- [ ] task-3 -"; - let out = insert_task_line(src, Some("A"), "r", "task-x").unwrap(); - let expected = "\ -## Milestone: A -- [ ] task-x -## Milestone: B -- [ ] task-3 -"; - assert_eq!(out, expected); - } - - #[test] - fn named_milestone_missing_lists_available() { - let src = "## Milestone: A\n- [ ] x\n## Milestone: B\n"; - let err = insert_task_line(src, Some("Z"), "rmap", "task-x").unwrap_err(); - match err { - CubilError::MilestoneNotFound { - roadmap, - milestone, - available, - } => { - assert_eq!(roadmap, "rmap"); - assert_eq!(milestone, "Z"); - assert_eq!(available, vec!["A".to_string(), "B".to_string()]); - } - other => panic!("expected MilestoneNotFound, got {other:?}"), - } - } - - #[test] - fn named_milestone_ambiguous_errors() { - let src = "## Milestone: A\n- [ ] x\n## Milestone: A\n"; - let err = insert_task_line(src, Some("A"), "rmap", "task-x").unwrap_err(); - assert!(matches!(err, CubilError::MilestoneAmbiguous { .. })); - } - - #[test] - fn case_sensitive_milestone_match() { - let src = "## Milestone: Schema ready\n"; - let err = insert_task_line(src, Some("schema ready"), "rmap", "task-x").unwrap_err(); - assert!(matches!(err, CubilError::MilestoneNotFound { .. })); - } - - #[test] - fn find_existing_task_detects_anywhere() { - let src = "## Milestone: A\n- [ ] foo\n## Milestone: B\n- [✓] bar — Title\n"; - assert!(find_existing_task(src, "foo")); - assert!(find_existing_task(src, "bar")); - assert!(!find_existing_task(src, "baz")); - } - - #[test] - fn find_existing_task_ignores_non_slug_checkboxes() { - // A free-form checkbox like "- [ ] todo something" should not be - // treated as a task slug — its first whitespace-delimited token is - // not slug-shaped. - let src = "- [ ] write the docs\n"; - assert!(!find_existing_task(src, "write")); - } - - #[test] - fn insert_into_section_with_narrative_no_tasks() { - let src = "## Milestone: A\nSome notes.\n## Milestone: B\n"; - let out = insert_task_line(src, Some("A"), "r", "task-x").unwrap(); - let expected = "## Milestone: A\nSome notes.\n- [ ] task-x\n## Milestone: B\n"; - assert_eq!(out, expected); - } + let mut roadmap = Roadmap::load(roadmap_slug, &path)?; + roadmap.add_task(&task_slug, milestone)?; + roadmap.save(&path) } diff --git a/src/commands/roadmap/next.rs b/src/commands/roadmap/next.rs index 64abdf1..1979afb 100644 --- a/src/commands/roadmap/next.rs +++ b/src/commands/roadmap/next.rs @@ -1,22 +1,25 @@ use std::collections::HashMap; use crate::core::error::Result; -use crate::core::roadmap::{TaskStatus, parse_task_line, resolve_roadmap}; +use crate::core::roadmap::{Roadmap, TaskStatus, resolve_roadmap}; use crate::core::store::TaskStore; /// Print the slug of the next not-done task in the roadmap. /// -/// Walks task lines in file order and prints the first one whose status is -/// not `done` (and which has a corresponding task file — missing slugs are -/// skipped, since `next` exists to drive `cubil start `). Empty stdout -/// + zero exit if all tasks are done. Designed for shell pipelines. +/// See [`Roadmap::next_not_done`]. Empty stdout + zero exit if all tasks are +/// done. Designed for shell pipelines. pub fn run(slug: &str) -> Result<()> { let store = TaskStore::discover()?; let path = resolve_roadmap(store.root(), slug)?; - let src = std::fs::read_to_string(&path)?; + let roadmap = Roadmap::load(slug, &path)?; let lookup = build_status_lookup(&store)?; - if let Some(next) = first_not_done(&src, &lookup) { + let next = roadmap.next_not_done(|task| { + lookup + .get(task) + .map_or(TaskStatus::Missing, |s| TaskStatus::from_status_name(s)) + }); + if let Some(next) = next { println!("{next}"); } Ok(()) @@ -29,79 +32,3 @@ fn build_status_lookup(store: &TaskStore) -> Result> { .map(|(slug, entry)| (slug, entry.status)) .collect()) } - -fn first_not_done(src: &str, lookup: &HashMap) -> Option { - for line in src.lines() { - let Some(parsed) = parse_task_line(line) else { - continue; - }; - let status = match lookup.get(&parsed.slug) { - Some(s) => TaskStatus::from_status_name(s), - None => continue, // missing task — not a candidate - }; - if !status.is_done() { - return Some(parsed.slug); - } - } - None -} - -#[cfg(test)] -mod tests { - use super::*; - - fn lookup(items: &[(&str, &str)]) -> HashMap { - items - .iter() - .map(|(s, t)| ((*s).to_string(), (*t).to_string())) - .collect() - } - - #[test] - fn returns_first_backlog_task() { - let map = lookup(&[("a", "done"), ("b", "backlog"), ("c", "backlog")]); - let src = "- [ ] a\n- [ ] b\n- [ ] c\n"; - assert_eq!(first_not_done(src, &map).as_deref(), Some("b")); - } - - #[test] - fn returns_first_doing_task_over_later_backlog() { - let map = lookup(&[("a", "done"), ("b", "doing"), ("c", "backlog")]); - let src = "- [ ] a\n- [ ] b\n- [ ] c\n"; - assert_eq!(first_not_done(src, &map).as_deref(), Some("b")); - } - - #[test] - fn returns_none_when_all_done() { - let map = lookup(&[("a", "done"), ("b", "done")]); - let src = "- [ ] a\n- [ ] b\n"; - assert_eq!(first_not_done(src, &map), None); - } - - #[test] - fn returns_none_for_empty_roadmap() { - let map = lookup(&[]); - assert_eq!(first_not_done("# Just a title\n", &map), None); - } - - #[test] - fn skips_missing_tasks() { - let map = lookup(&[("a", "done"), ("c", "backlog")]); - let src = "- [ ] a\n- [ ] missing\n- [ ] c\n"; - assert_eq!(first_not_done(src, &map).as_deref(), Some("c")); - } - - #[test] - fn ignores_milestone_headings_and_narrative() { - let map = lookup(&[("first-task", "backlog")]); - let src = "\ -# Roadmap - -Narrative. - -## Milestone: M -- [ ] first-task -"; - assert_eq!(first_not_done(src, &map).as_deref(), Some("first-task")); - } -} diff --git a/src/commands/roadmap/show.rs b/src/commands/roadmap/show.rs index a1fb86c..cfc211e 100644 --- a/src/commands/roadmap/show.rs +++ b/src/commands/roadmap/show.rs @@ -1,32 +1,24 @@ use std::collections::HashMap; use std::io::Write as _; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use crate::core::error::Result; -use crate::core::roadmap::{TaskStatus, parse_task_line, read_task_title, resolve_roadmap}; +use crate::core::roadmap::{Roadmap, TaskInfo, TaskStatus, read_task_title, resolve_roadmap}; use crate::core::store::TaskStore; /// Render the roadmap with task statuses resolved from the actual task files, /// then write the resolved view back to disk. /// -/// Resolution rules: -/// - Done task → `- [✓] — ` -/// - Doing → `- [~] <slug> — <title>` -/// - Backlog or any other status folder → `- [ ] <slug> — <title>` -/// - Slug with no task file → `- [?] <slug> — (missing)` -/// -/// Non-task content (headings, narrative, sub-bullets, blank lines) passes -/// through byte-for-byte. Only lines parsed as `- [<x>] <slug>` checkbox -/// items are rewritten. +/// See [`Roadmap::render_resolved`] for the resolution rules. pub fn run(slug: &str) -> Result<()> { let store = TaskStore::discover()?; let path = resolve_roadmap(store.root(), slug)?; - let src = std::fs::read_to_string(&path)?; + let roadmap = Roadmap::load(slug, &path)?; let lookup = build_lookup(&store)?; - let new_src = rewrite(&src, &lookup)?; + let new_src = roadmap.render_resolved(|task| resolve(task, &lookup))?; - write_atomic(&path, new_src.as_bytes())?; + Roadmap::parse(slug, &new_src).save(&path)?; let stdout = std::io::stdout(); let mut handle = stdout.lock(); @@ -34,12 +26,10 @@ pub fn run(slug: &str) -> Result<()> { Ok(()) } -struct TaskInfo { - status: TaskStatus, - title: Option<String>, -} +/// Slug to `(status folder name, task file path)`. +type Lookup = HashMap<String, (String, PathBuf)>; -fn build_lookup(store: &TaskStore) -> Result<HashMap<String, (String, PathBuf)>> { +fn build_lookup(store: &TaskStore) -> Result<Lookup> { // First-write-wins for ambiguous slugs. Roadmap rendering is robust // to ambiguity: it just picks one. Users discover the duplicate via // `cubil list` or `cubil show`. @@ -50,169 +40,15 @@ fn build_lookup(store: &TaskStore) -> Result<HashMap<String, (String, PathBuf)>> .collect()) } -fn resolve(slug: &str, lookup: &HashMap<String, (String, PathBuf)>) -> Result<TaskInfo> { +fn resolve(slug: &str, lookup: &Lookup) -> Result<TaskInfo> { match lookup.get(slug) { None => Ok(TaskInfo { status: TaskStatus::Missing, title: None, }), - Some((status_name, path)) => { - let status = TaskStatus::from_status_name(status_name); - let title = read_task_title(path)?; - Ok(TaskInfo { status, title }) - } - } -} - -fn rewrite(src: &str, lookup: &HashMap<String, (String, PathBuf)>) -> Result<String> { - let mut out = String::with_capacity(src.len()); - for line in src.split_inclusive('\n') { - let eol_len = if line.ends_with("\r\n") { - 2 - } else { - usize::from(line.ends_with('\n')) - }; - let body = &line[..line.len() - eol_len]; - let eol = &line[line.len() - eol_len..]; - - match parse_task_line(body) { - Some(parsed) => { - let info = resolve(&parsed.slug, lookup)?; - let new_body = render_task_line(&parsed.indent, &parsed.slug, &info); - out.push_str(&new_body); - out.push_str(eol); - } - None => { - out.push_str(line); - } - } - } - Ok(out) -} - -fn render_task_line(indent: &str, slug: &str, info: &TaskInfo) -> String { - let checkbox = info.status.checkbox(); - let suffix = if info.status.is_missing() { - "(missing)".to_string() - } else { - info.title - .clone() - .unwrap_or_else(|| "(untitled)".to_string()) - }; - format!("{indent}- [{checkbox}] {slug} \u{2014} {suffix}") -} - -fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> { - let parent = path.parent().expect("roadmap path has parent"); - let tmp = parent.join(format!( - ".{}.tmp", - path.file_name() - .expect("roadmap has filename") - .to_string_lossy() - )); - std::fs::write(&tmp, bytes)?; - std::fs::rename(&tmp, path)?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn lookup(items: &[(&str, &str, Option<&str>)]) -> HashMap<String, (String, PathBuf)> { - // Build a lookup whose values point to per-test temp files containing - // the desired title. We use tempdir per test instead. - let dir = tempfile::tempdir().unwrap(); - let mut map = HashMap::new(); - for (slug, status, title) in items { - let dir_path = dir.path().join(status); - std::fs::create_dir_all(&dir_path).unwrap(); - let path = dir_path.join(format!("{slug}.md")); - let body = match title { - Some(t) => format!("# {t}\n"), - None => String::new(), - }; - std::fs::write(&path, body).unwrap(); - map.insert((*slug).to_string(), ((*status).to_string(), path)); - } - // Leak the tempdir so files survive the rest of the test. - std::mem::forget(dir); - map - } - - #[test] - fn rewrite_resolves_all_status_markers() { - let map = lookup(&[ - ("a", "done", Some("Task A")), - ("b", "doing", Some("Task B")), - ("c", "backlog", Some("Task C")), - ]); - let src = "\ -# Roadmap - -## Milestone: M -- [ ] a -- [ ] b -- [ ] c -- [ ] missing-task -"; - let out = rewrite(src, &map).unwrap(); - let expected = "\ -# Roadmap - -## Milestone: M -- [\u{2713}] a \u{2014} Task A -- [~] b \u{2014} Task B -- [ ] c \u{2014} Task C -- [?] missing-task \u{2014} (missing) -"; - assert_eq!(out, expected); - } - - #[test] - fn rewrite_preserves_non_task_lines_byte_for_byte() { - let map = lookup(&[("a", "done", Some("A"))]); - let src = "\ -# Title - -Some narrative. - -## Milestone: First -Notes inside section. -- [ ] a - - sub bullet -- not a checkbox -"; - let out = rewrite(src, &map).unwrap(); - // Everything except the `- [ ] a` line is unchanged. - assert!(out.contains("Some narrative.\n")); - assert!(out.contains("Notes inside section.\n")); - assert!(out.contains(" - sub bullet\n")); - assert!(out.contains("- not a checkbox\n")); - assert!(out.contains("- [\u{2713}] a \u{2014} A\n")); - } - - #[test] - fn rewrite_handles_already_resolved_lines() { - let map = lookup(&[("a", "done", Some("New Title"))]); - let src = "- [ ] a — Old Title\n"; - let out = rewrite(src, &map).unwrap(); - assert_eq!(out, "- [\u{2713}] a \u{2014} New Title\n"); - } - - #[test] - fn rewrite_uses_untitled_when_task_has_no_h1() { - let map = lookup(&[("a", "done", None)]); - let src = "- [ ] a\n"; - let out = rewrite(src, &map).unwrap(); - assert_eq!(out, "- [\u{2713}] a \u{2014} (untitled)\n"); - } - - #[test] - fn rewrite_treats_unknown_status_as_backlog_marker() { - let map = lookup(&[("a", "review", Some("A"))]); - let src = "- [✓] a — Old\n"; - let out = rewrite(src, &map).unwrap(); - assert_eq!(out, "- [ ] a \u{2014} A\n"); + Some((status_name, path)) => Ok(TaskInfo { + status: TaskStatus::from_status_name(status_name), + title: read_task_title(path)?, + }), } } diff --git a/src/core/roadmap.rs b/src/core/roadmap.rs index fcb2621..2fd19be 100644 --- a/src/core/roadmap.rs +++ b/src/core/roadmap.rs @@ -1,7 +1,7 @@ +use std::io::Write as _; use std::path::{Path, PathBuf}; use crate::core::error::{CubilError, Result}; -use crate::core::root::find_root; pub const ROADMAPS_DIR: &str = "roadmaps"; pub const MILESTONE_PREFIX: &str = "## Milestone: "; @@ -55,12 +55,6 @@ pub fn list_roadmap_slugs(root: &Path) -> Result<Vec<String>> { Ok(slugs) } -/// Walk upward to find `.cubil/`, mirroring [`find_root`]. Convenience for -/// roadmap commands that all start with the same dance. -pub fn root_for_roadmap() -> Result<PathBuf> { - find_root(None) -} - /// Resolved status of a task slug referenced by a roadmap. #[derive(Debug, Clone, PartialEq, Eq)] pub enum TaskStatus { @@ -102,11 +96,280 @@ impl TaskStatus { } } +/// Task details a caller supplies for a slug when rendering a roadmap. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TaskInfo { + pub status: TaskStatus, + pub title: Option<String>, +} + /// A line parsed as a checkbox-style task reference. #[derive(Debug, Clone, PartialEq, Eq)] -pub struct TaskLine { - pub indent: String, - pub slug: String, +struct TaskLine { + indent: String, + slug: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum LineKind { + Task(TaskLine), + Milestone(String), + /// Any other `## ` heading; it closes the preceding Milestone section. + Heading, + Other, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Line { + /// Raw text including its line terminator. + raw: String, + kind: LineKind, +} + +impl Line { + fn body(&self) -> &str { + strip_eol(&self.raw) + } + + fn eol(&self) -> &str { + &self.raw[self.body().len()..] + } +} + +fn strip_eol(s: &str) -> &str { + s.trim_end_matches('\n').trim_end_matches('\r') +} + +/// A roadmap file parsed once into classified lines. +/// +/// The task-line and Milestone grammar lives here. Every operation works on +/// the parsed lines and leaves non-task content byte-for-byte intact. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Roadmap { + slug: String, + lines: Vec<Line>, +} + +impl Roadmap { + /// Parse the contents of the roadmap file `slug`. The slug appears in + /// error messages. + pub fn parse(slug: &str, src: &str) -> Self { + let lines = src + .split_inclusive('\n') + .map(|raw| { + let body = strip_eol(raw); + let kind = if let Some(t) = parse_task_line(body) { + LineKind::Task(t) + } else if let Some(name) = parse_milestone_heading(body) { + LineKind::Milestone(name.to_string()) + } else if parse_h2_heading(body).is_some() { + LineKind::Heading + } else { + LineKind::Other + }; + Line { + raw: raw.to_string(), + kind, + } + }) + .collect(); + Roadmap { + slug: slug.to_string(), + lines, + } + } + + /// Read and parse the roadmap file at `path`. + pub fn load(slug: &str, path: &Path) -> Result<Self> { + Ok(Self::parse(slug, &std::fs::read_to_string(path)?)) + } + + /// The roadmap title: its first `# ` heading. + pub fn title(&self) -> Option<&str> { + self.lines.iter().find_map(|l| parse_top_heading(l.body())) + } + + /// The file contents, with any edits applied. + pub fn render(&self) -> String { + self.lines.iter().map(|l| l.raw.as_str()).collect() + } + + /// Render with every task line rewritten from `tasks`, which returns the + /// status and title for a slug. + /// + /// - Done task: `- [✓] <slug> — <title>` + /// - Doing: `- [~] <slug> — <title>` + /// - Backlog or any other status folder: `- [ ] <slug> — <title>` + /// - Slug with no task file: `- [?] <slug> — (missing)` + /// + /// Non-task content passes through byte-for-byte. + pub fn render_resolved( + &self, + mut tasks: impl FnMut(&str) -> Result<TaskInfo>, + ) -> Result<String> { + let mut out = String::new(); + for line in &self.lines { + match &line.kind { + LineKind::Task(t) => { + let info = tasks(&t.slug)?; + out.push_str(&render_task_line(&t.indent, &t.slug, &info)); + out.push_str(line.eol()); + } + _ => out.push_str(&line.raw), + } + } + Ok(out) + } + + /// Whether the roadmap lists `task_slug` as a task line. + pub fn contains_task(&self, task_slug: &str) -> bool { + self.lines + .iter() + .any(|l| matches!(&l.kind, LineKind::Task(t) if t.slug == task_slug)) + } + + /// Append `- [ ] <task_slug>` to a Milestone section. + /// + /// With `milestone == None` the line goes at the end of the last + /// Milestone, or at end of file when there are none. With `Some(name)` + /// it goes at the end of that Milestone (an error if it is missing or + /// ambiguous). Errors if the task is already listed. + pub fn add_task(&mut self, task_slug: &str, milestone: Option<&str>) -> Result<()> { + if self.contains_task(task_slug) { + return Err(CubilError::TaskAlreadyInRoadmap { + roadmap: self.slug.clone(), + task: task_slug.to_string(), + }); + } + let section = match milestone { + Some(name) => Some(self.find_named_milestone(name)?), + None => self.find_last_milestone(), + }; + let at = match section { + Some((start, end)) => self.insert_position_in_section(start, end), + None => self.lines.len(), + }; + // A final line without a terminator gets one before the new line. + if at > 0 && at == self.lines.len() && self.lines[at - 1].eol().is_empty() { + self.lines[at - 1].raw.push('\n'); + } + self.lines.insert( + at, + Line { + raw: format!("- [ ] {task_slug}\n"), + kind: LineKind::Task(TaskLine { + indent: String::new(), + slug: task_slug.to_string(), + }), + }, + ); + Ok(()) + } + + /// Slug of the first task line, in file order, whose task exists and is + /// not done. `tasks` returns the status for a slug. Missing slugs are + /// skipped, since `next` drives `cubil start <slug>`. + pub fn next_not_done(&self, mut tasks: impl FnMut(&str) -> TaskStatus) -> Option<&str> { + self.lines.iter().find_map(|l| match &l.kind { + LineKind::Task(t) => { + let status = tasks(&t.slug); + (!status.is_missing() && !status.is_done()).then_some(t.slug.as_str()) + } + _ => None, + }) + } + + /// Write the roadmap to `path` atomically: a temp file in the same + /// directory is renamed over the target, so readers never see a partial + /// file. + pub fn save(&self, path: &Path) -> Result<()> { + let parent = path.parent().expect("roadmap path has parent"); + let tmp = parent.join(format!( + ".{}.tmp", + path.file_name() + .expect("roadmap has filename") + .to_string_lossy() + )); + let mut f = std::fs::File::create(&tmp)?; + f.write_all(self.render().as_bytes())?; + drop(f); + std::fs::rename(&tmp, path)?; + Ok(()) + } + + fn milestone_names(&self) -> Vec<String> { + self.lines + .iter() + .filter_map(|l| match &l.kind { + LineKind::Milestone(n) => Some(n.clone()), + _ => None, + }) + .collect() + } + + /// Line indices `(start, end)` of the section under the named Milestone. + fn find_named_milestone(&self, target: &str) -> Result<(usize, usize)> { + let hits: Vec<usize> = self + .lines + .iter() + .enumerate() + .filter(|(_, l)| matches!(&l.kind, LineKind::Milestone(n) if n == target)) + .map(|(i, _)| i) + .collect(); + match hits.as_slice() { + [] => Err(CubilError::MilestoneNotFound { + roadmap: self.slug.clone(), + milestone: target.to_string(), + available: self.milestone_names(), + }), + [start] => Ok((*start, self.section_end(*start))), + _ => Err(CubilError::MilestoneAmbiguous { + roadmap: self.slug.clone(), + milestone: target.to_string(), + }), + } + } + + fn find_last_milestone(&self) -> Option<(usize, usize)> { + let start = self + .lines + .iter() + .rposition(|l| matches!(l.kind, LineKind::Milestone(_)))?; + Some((start, self.section_end(start))) + } + + /// A section runs from its `## ` heading (inclusive) to the next `## ` + /// heading (exclusive), or end of file. + fn section_end(&self, start: usize) -> usize { + self.lines + .iter() + .enumerate() + .skip(start + 1) + .find(|(_, l)| matches!(l.kind, LineKind::Milestone(_) | LineKind::Heading)) + .map_or(self.lines.len(), |(i, _)| i) + } + + /// Insertion index: just after the last non-blank line of the section + /// body, or right after the heading when the body is empty. + fn insert_position_in_section(&self, start: usize, end: usize) -> usize { + let mut last_non_blank = start; + for (i, line) in self.lines.iter().enumerate().take(end).skip(start + 1) { + if !line.body().trim().is_empty() { + last_non_blank = i; + } + } + last_non_blank + 1 + } +} + +fn render_task_line(indent: &str, slug: &str, info: &TaskInfo) -> String { + let checkbox = info.status.checkbox(); + let suffix = if info.status.is_missing() { + "(missing)" + } else { + info.title.as_deref().unwrap_or("(untitled)") + }; + format!("{indent}- [{checkbox}] {slug} \u{2014} {suffix}") } /// Recognize `<indent>- [<x>] <slug>` optionally followed by ` — <anything>`. @@ -120,7 +383,7 @@ pub struct TaskLine { /// 2. The text after the slug (whitespace-trimmed) must be empty or start /// with `—` (U+2014, em-dash). This is the form `add` and `show` write, /// so anything else is treated as prose. -pub fn parse_task_line(line: &str) -> Option<TaskLine> { +fn parse_task_line(line: &str) -> Option<TaskLine> { let indent_end = line .find(|c: char| c != ' ' && c != '\t') .unwrap_or(line.len()); @@ -172,7 +435,7 @@ fn is_slug_shaped(s: &str) -> bool { } /// If `line` is a `## Milestone: <name>` heading, return the name (trimmed). -pub fn parse_milestone_heading(line: &str) -> Option<&str> { +fn parse_milestone_heading(line: &str) -> Option<&str> { let rest = line.strip_prefix(MILESTONE_PREFIX)?; let trimmed = rest.trim(); if trimmed.is_empty() { @@ -183,7 +446,7 @@ pub fn parse_milestone_heading(line: &str) -> Option<&str> { } /// If `line` is a top-level `# <title>` heading, return the title (trimmed). -pub fn parse_top_heading(line: &str) -> Option<&str> { +fn parse_top_heading(line: &str) -> Option<&str> { let rest = line.strip_prefix("# ")?; let trimmed = rest.trim(); if trimmed.is_empty() { @@ -194,8 +457,8 @@ pub fn parse_top_heading(line: &str) -> Option<&str> { } /// If `line` is any `## ` heading, return its text. Used to find section -/// boundaries (a milestone section ends at the next `## ` heading). -pub fn parse_h2_heading(line: &str) -> Option<&str> { +/// boundaries (a Milestone section ends at the next `## ` heading). +fn parse_h2_heading(line: &str) -> Option<&str> { let rest = line.strip_prefix("## ")?; let trimmed = rest.trim(); if trimmed.is_empty() { @@ -209,27 +472,64 @@ pub fn parse_h2_heading(line: &str) -> Option<&str> { /// such heading exists. Used by roadmap rendering to enrich task references. pub fn read_task_title(path: &Path) -> Result<Option<String>> { let src = std::fs::read_to_string(path)?; - Ok(extract_first_h1(&src).map(str::to_string)) -} - -fn extract_first_h1(src: &str) -> Option<&str> { - for line in src.lines() { - if let Some(t) = parse_top_heading(line) { - return Some(t); - } - } - None + Ok(src.lines().find_map(parse_top_heading).map(str::to_string)) } /// Extract the roadmap title (first `# ` heading) from raw file contents. pub fn extract_roadmap_title(src: &str) -> Option<String> { - extract_first_h1(src).map(str::to_string) + Roadmap::parse("", src).title().map(str::to_string) } #[cfg(test)] mod tests { use super::*; + fn rm(src: &str) -> Roadmap { + Roadmap::parse("rmap", src) + } + + fn info(status: TaskStatus, title: Option<&str>) -> TaskInfo { + TaskInfo { + status, + title: title.map(String::from), + } + } + + fn resolver(items: &[(&str, &str, Option<&str>)]) -> impl FnMut(&str) -> Result<TaskInfo> { + let items: Vec<(String, String, Option<String>)> = items + .iter() + .map(|(s, st, t)| ((*s).into(), (*st).into(), t.map(String::from))) + .collect(); + move |slug| { + Ok(match items.iter().find(|(s, _, _)| s == slug) { + Some((_, st, t)) => TaskInfo { + status: TaskStatus::from_status_name(st), + title: t.clone(), + }, + None => info(TaskStatus::Missing, None), + }) + } + } + + fn statuses(items: &[(&str, &str)]) -> impl FnMut(&str) -> TaskStatus { + let items: Vec<(String, String)> = items + .iter() + .map(|(s, t)| ((*s).into(), (*t).into())) + .collect(); + move |slug| match items.iter().find(|(s, _)| s == slug) { + Some((_, st)) => TaskStatus::from_status_name(st), + None => TaskStatus::Missing, + } + } + + fn added(src: &str, milestone: Option<&str>, slug: &str) -> String { + let mut r = rm(src); + r.add_task(slug, milestone).unwrap(); + r.render() + } + + // ---- line grammar ---- + #[test] fn parse_task_line_bare() { let l = parse_task_line("- [ ] foo").unwrap(); @@ -318,15 +618,40 @@ mod tests { } #[test] - fn extract_roadmap_title_finds_first_h1() { - let src = "# Migrate\n\n## Milestone: A\n"; - assert_eq!(extract_roadmap_title(src).as_deref(), Some("Migrate")); + fn is_slug_shaped_accepts_normal() { + assert!(is_slug_shaped("foo")); + assert!(is_slug_shaped("foo-bar")); + assert!(is_slug_shaped("a1b2")); + assert!(is_slug_shaped("foo-bar-baz-1-2-3")); + } + + #[test] + fn is_slug_shaped_rejects_bad() { + assert!(!is_slug_shaped("")); + assert!(!is_slug_shaped("Foo")); + assert!(!is_slug_shaped("foo bar")); + assert!(!is_slug_shaped("-foo")); + assert!(!is_slug_shaped("foo-")); + assert!(!is_slug_shaped("foo--bar")); + } + + // ---- title ---- + + #[test] + fn title_finds_first_h1() { + assert_eq!( + rm("# Migrate\n\n## Milestone: A\n").title(), + Some("Migrate") + ); + assert_eq!( + extract_roadmap_title("# Migrate\n").as_deref(), + Some("Migrate") + ); } #[test] - fn extract_roadmap_title_none_when_absent() { - let src = "## Milestone: A\n- [ ] x\n"; - assert_eq!(extract_roadmap_title(src), None); + fn title_none_when_absent() { + assert_eq!(rm("## Milestone: A\n- [ ] x\n").title(), None); } #[test] @@ -338,21 +663,285 @@ mod tests { assert_eq!(TaskStatus::Missing.checkbox(), '?'); } + // ---- render_resolved ---- + #[test] - fn is_slug_shaped_accepts_normal() { - assert!(is_slug_shaped("foo")); - assert!(is_slug_shaped("foo-bar")); - assert!(is_slug_shaped("a1b2")); - assert!(is_slug_shaped("foo-bar-baz-1-2-3")); + fn render_resolved_resolves_all_status_markers() { + let tasks = resolver(&[ + ("a", "done", Some("Task A")), + ("b", "doing", Some("Task B")), + ("c", "backlog", Some("Task C")), + ]); + let src = "\ +# Roadmap + +## Milestone: M +- [ ] a +- [ ] b +- [ ] c +- [ ] missing-task +"; + let expected = "\ +# Roadmap + +## Milestone: M +- [\u{2713}] a \u{2014} Task A +- [~] b \u{2014} Task B +- [ ] c \u{2014} Task C +- [?] missing-task \u{2014} (missing) +"; + assert_eq!(rm(src).render_resolved(tasks).unwrap(), expected); } #[test] - fn is_slug_shaped_rejects_bad() { - assert!(!is_slug_shaped("")); - assert!(!is_slug_shaped("Foo")); - assert!(!is_slug_shaped("foo bar")); - assert!(!is_slug_shaped("-foo")); - assert!(!is_slug_shaped("foo-")); - assert!(!is_slug_shaped("foo--bar")); + fn render_resolved_preserves_non_task_lines_byte_for_byte() { + let tasks = resolver(&[("a", "done", Some("A"))]); + let src = "\ +# Title + +Some narrative. + +## Milestone: First +Notes inside section. +- [ ] a + - sub bullet +- not a checkbox +"; + let out = rm(src).render_resolved(tasks).unwrap(); + assert!(out.contains("Some narrative.\n")); + assert!(out.contains("Notes inside section.\n")); + assert!(out.contains(" - sub bullet\n")); + assert!(out.contains("- not a checkbox\n")); + assert!(out.contains("- [\u{2713}] a \u{2014} A\n")); + } + + #[test] + fn render_resolved_handles_already_resolved_lines() { + let tasks = resolver(&[("a", "done", Some("New Title"))]); + let out = rm("- [ ] a — Old Title\n").render_resolved(tasks).unwrap(); + assert_eq!(out, "- [\u{2713}] a \u{2014} New Title\n"); + } + + #[test] + fn render_resolved_uses_untitled_when_task_has_no_h1() { + let tasks = resolver(&[("a", "done", None)]); + let out = rm("- [ ] a\n").render_resolved(tasks).unwrap(); + assert_eq!(out, "- [\u{2713}] a \u{2014} (untitled)\n"); + } + + #[test] + fn render_resolved_treats_unknown_status_as_backlog_marker() { + let tasks = resolver(&[("a", "review", Some("A"))]); + let out = rm("- [✓] a — Old\n").render_resolved(tasks).unwrap(); + assert_eq!(out, "- [ ] a \u{2014} A\n"); + } + + #[test] + fn render_resolved_keeps_crlf_endings() { + let tasks = resolver(&[("a", "done", Some("A"))]); + let out = rm("# T\r\n- [ ] a\r\n").render_resolved(tasks).unwrap(); + assert_eq!(out, "# T\r\n- [\u{2713}] a \u{2014} A\r\n"); + } + + // ---- add_task ---- + + #[test] + fn add_into_file_with_no_milestones_appends_at_eof() { + let out = added("# Roadmap\n\nNarrative.\n", None, "task-1"); + assert_eq!(out, "# Roadmap\n\nNarrative.\n- [ ] task-1\n"); + } + + #[test] + fn add_into_file_with_no_trailing_newline_adds_one() { + assert_eq!( + added("# Roadmap", None, "task-1"), + "# Roadmap\n- [ ] task-1\n" + ); + } + + #[test] + fn add_default_appends_to_last_milestone() { + let src = "\ +# Roadmap + +## Milestone: A +- [ ] task-1 + +## Milestone: B +- [ ] task-3 +"; + let expected = "\ +# Roadmap + +## Milestone: A +- [ ] task-1 + +## Milestone: B +- [ ] task-3 +- [ ] task-4 +"; + assert_eq!(added(src, None, "task-4"), expected); + } + + #[test] + fn add_named_milestone_inserts_before_trailing_blank() { + let src = "\ +# Roadmap + +## Milestone: A +- [ ] task-1 +- [ ] task-2 + +## Milestone: B +- [ ] task-3 +"; + let expected = "\ +# Roadmap + +## Milestone: A +- [ ] task-1 +- [ ] task-2 +- [ ] task-x + +## Milestone: B +- [ ] task-3 +"; + assert_eq!(added(src, Some("A"), "task-x"), expected); + } + + #[test] + fn add_named_milestone_with_no_body_inserts_right_after_heading() { + let src = "## Milestone: A\n## Milestone: B\n- [ ] task-3\n"; + let expected = "## Milestone: A\n- [ ] task-x\n## Milestone: B\n- [ ] task-3\n"; + assert_eq!(added(src, Some("A"), "task-x"), expected); + } + + #[test] + fn add_stops_section_at_any_h2_heading() { + let src = "## Milestone: A\n- [ ] one\n## Notes\nprose\n"; + let expected = "## Milestone: A\n- [ ] one\n- [ ] two\n## Notes\nprose\n"; + assert_eq!(added(src, None, "two"), expected); + } + + #[test] + fn add_named_milestone_missing_lists_available() { + let src = "## Milestone: A\n- [ ] x\n## Milestone: B\n"; + let err = rm(src).add_task("task-x", Some("Z")).unwrap_err(); + match err { + CubilError::MilestoneNotFound { + roadmap, + milestone, + available, + } => { + assert_eq!(roadmap, "rmap"); + assert_eq!(milestone, "Z"); + assert_eq!(available, vec!["A".to_string(), "B".to_string()]); + } + other => panic!("expected MilestoneNotFound, got {other:?}"), + } + } + + #[test] + fn add_named_milestone_ambiguous_errors() { + let src = "## Milestone: A\n- [ ] x\n## Milestone: A\n"; + let err = rm(src).add_task("task-x", Some("A")).unwrap_err(); + assert!(matches!(err, CubilError::MilestoneAmbiguous { .. })); + } + + #[test] + fn add_milestone_match_is_case_sensitive() { + let err = rm("## Milestone: Schema ready\n") + .add_task("task-x", Some("schema ready")) + .unwrap_err(); + assert!(matches!(err, CubilError::MilestoneNotFound { .. })); + } + + #[test] + fn add_rejects_task_already_listed() { + let err = rm("## Milestone: A\n- [✓] foo — T\n") + .add_task("foo", None) + .unwrap_err(); + assert!(matches!(err, CubilError::TaskAlreadyInRoadmap { .. })); + } + + #[test] + fn add_into_section_with_narrative_no_tasks() { + let src = "## Milestone: A\nSome notes.\n## Milestone: B\n"; + let expected = "## Milestone: A\nSome notes.\n- [ ] task-x\n## Milestone: B\n"; + assert_eq!(added(src, Some("A"), "task-x"), expected); + } + + #[test] + fn contains_task_detects_anywhere() { + let r = rm("## Milestone: A\n- [ ] foo\n## Milestone: B\n- [✓] bar — Title\n"); + assert!(r.contains_task("foo")); + assert!(r.contains_task("bar")); + assert!(!r.contains_task("baz")); + } + + #[test] + fn contains_task_ignores_non_slug_checkboxes() { + assert!(!rm("- [ ] write the docs\n").contains_task("write")); + } + + // ---- next_not_done ---- + + #[test] + fn next_returns_first_backlog_task() { + let r = rm("- [ ] a\n- [ ] b\n- [ ] c\n"); + let t = statuses(&[("a", "done"), ("b", "backlog"), ("c", "backlog")]); + assert_eq!(r.next_not_done(t), Some("b")); + } + + #[test] + fn next_returns_first_doing_task_over_later_backlog() { + let r = rm("- [ ] a\n- [ ] b\n- [ ] c\n"); + let t = statuses(&[("a", "done"), ("b", "doing"), ("c", "backlog")]); + assert_eq!(r.next_not_done(t), Some("b")); + } + + #[test] + fn next_returns_none_when_all_done() { + let r = rm("- [ ] a\n- [ ] b\n"); + assert_eq!( + r.next_not_done(statuses(&[("a", "done"), ("b", "done")])), + None + ); + } + + #[test] + fn next_returns_none_for_empty_roadmap() { + assert_eq!(rm("# Just a title\n").next_not_done(statuses(&[])), None); + } + + #[test] + fn next_skips_missing_tasks() { + let r = rm("- [ ] a\n- [ ] missing\n- [ ] c\n"); + let t = statuses(&[("a", "done"), ("c", "backlog")]); + assert_eq!(r.next_not_done(t), Some("c")); + } + + #[test] + fn next_ignores_milestone_headings_and_narrative() { + let src = "# Roadmap\n\nNarrative.\n\n## Milestone: M\n- [ ] first-task\n"; + let t = statuses(&[("first-task", "backlog")]); + assert_eq!(rm(src).next_not_done(t), Some("first-task")); + } + + // ---- save ---- + + #[test] + fn save_writes_edits_atomically() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("r.md"); + std::fs::write(&path, "## Milestone: A\n").unwrap(); + let mut r = Roadmap::load("r", &path).unwrap(); + r.add_task("x", None).unwrap(); + r.save(&path).unwrap(); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "## Milestone: A\n- [ ] x\n" + ); + assert!(!dir.path().join(".r.md.tmp").exists()); } } diff --git a/src/main.rs b/src/main.rs index 9947be2..2087152 100644 --- a/src/main.rs +++ b/src/main.rs @@ -166,7 +166,7 @@ fn main() { roadmap, task, milestone, - } => commands::roadmap::add::run(roadmap, task, milestone.as_deref()), + } => commands::roadmap::add::run(&roadmap, task, milestone.as_deref()), RoadmapCommands::Next { slug } => commands::roadmap::next::run(&slug), RoadmapCommands::Rm { slug } => commands::roadmap::rm::run(&slug), },