From 7ad611fc0c07ed653e5f6fe7f47b7f70aecb4262 Mon Sep 17 00:00:00 2001 From: Fran Tufro Date: Thu, 12 Nov 2026 18:00:11 -0300 Subject: [PATCH] refactor: add a Task store module behind find, tasks, create, move_to and remove Commands no longer repeat root discovery, scanning and slug resolution. mv, start and finish share one move path, and the roadmap commands take their slug-to-status lookup from the store. Behavior and output are unchanged. --- .cubil/done/deepen-the-task-store.md | 20 ++ CONTRIBUTING.md | 3 +- src/commands/edit.rs | 6 +- src/commands/finish.rs | 2 +- src/commands/list.rs | 14 +- src/commands/mod.rs | 46 +--- src/commands/mv.rs | 43 +--- src/commands/new.rs | 24 +- src/commands/rm.rs | 11 +- src/commands/roadmap/add.rs | 20 +- src/commands/roadmap/next.rs | 21 +- src/commands/roadmap/show.rs | 27 +- src/commands/show.rs | 12 +- src/commands/start.rs | 2 +- src/core/mod.rs | 1 + src/core/slug.rs | 129 ---------- src/core/store.rs | 366 +++++++++++++++++++++++++++ src/main.rs | 6 +- 18 files changed, 464 insertions(+), 289 deletions(-) create mode 100644 .cubil/done/deepen-the-task-store.md create mode 100644 src/core/store.rs diff --git a/.cubil/done/deepen-the-task-store.md b/.cubil/done/deepen-the-task-store.md new file mode 100644 index 0000000..ebf4984 --- /dev/null +++ b/.cubil/done/deepen-the-task-store.md @@ -0,0 +1,20 @@ +--- +created: 2026-11-12 +--- + +# Deepen the Task store + +Create a Task store module that owns finding, listing, creating, moving and removing Tasks across Statuses. + +## Problem +Every command repeats root discovery, scanning and slug resolution. `commands/mv.rs` repeats `transition()` in `commands/mod.rs` almost line for line. `roadmap/show.rs`, `roadmap/next.rs` and `roadmap/add.rs` each build their own slug-to-status lookup. The "backlog" literal appears in several files. + +## Scope +- Interface: find(slug), tasks(), create(slug, text), move_to(slug, status), remove(slug). +- Collision, ambiguity, reserved-directory and missing-Status rules live behind the interface. +- Files: src/core/slug.rs, src/commands/{mod,mv,rm,new,show,edit,start,finish,list}.rs, src/commands/roadmap/{show,next,add}.rs. + +## Done when +- mv and start/finish share one move path. +- The roadmap commands take their lookup from the Task store. +- Tests exercise the Task store through its interface against a tempdir. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 82da891..c5c2737 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -44,7 +44,8 @@ src/ ├── main.rs CLI definition (clap) and command dispatch ├── core/ │ ├── root.rs Find the .cubil/ directory from any working directory -│ ├── slug.rs Slugify titles, scan status folders, resolve a slug +│ ├── slug.rs Slugify titles into kebab-case slugs +│ ├── store.rs Task store: find, list, create, move and remove tasks │ ├── frontmatter.rs YAML frontmatter parse and assemble │ ├── roadmap.rs Roadmap line grammar: task lines, headings, milestones │ ├── updater.rs Self-update: target detection, download, atomic replace diff --git a/src/commands/edit.rs b/src/commands/edit.rs index d5bf178..b982d05 100644 --- a/src/commands/edit.rs +++ b/src/commands/edit.rs @@ -1,8 +1,7 @@ use std::process::Command; use crate::core::error::Result; -use crate::core::root::find_root; -use crate::core::slug::resolve_slug; +use crate::core::store::TaskStore; /// Open the task identified by `slug` in the user's editor. /// @@ -20,8 +19,7 @@ use crate::core::slug::resolve_slug; /// `:wq` from a deliberate `:cq`, so any successful spawn-and-wait is /// treated as success regardless of the editor's exit code. pub fn run(slug: &str) -> Result<()> { - let root = find_root(None)?; - let (_task_status, path) = resolve_slug(&root, slug)?; + let path = TaskStore::discover()?.find(slug)?.path; let editor = std::env::var("EDITOR").unwrap_or_default(); let mut parts = editor.split_ascii_whitespace(); diff --git a/src/commands/finish.rs b/src/commands/finish.rs index 75eb9a5..07110a8 100644 --- a/src/commands/finish.rs +++ b/src/commands/finish.rs @@ -1,6 +1,6 @@ use crate::core::error::Result; /// Move task `` from `doing/` to `done/`. -pub fn run(slug: String) -> Result<()> { +pub fn run(slug: &str) -> Result<()> { super::transition(slug, "doing", "done") } diff --git a/src/commands/list.rs b/src/commands/list.rs index 2361fad..41043c3 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -1,11 +1,9 @@ use std::cmp::Ordering; use std::fmt::Write as _; -use std::path::Path; use crate::core::error::{CubilError, Result}; use crate::core::frontmatter::parse_frontmatter; -use crate::core::root::find_root; -use crate::core::slug::{TaskEntry, scan_all}; +use crate::core::store::{TaskEntry, TaskStore}; const DONE: &str = "done"; @@ -17,8 +15,8 @@ struct Row { } pub fn run(all: bool, status: Option<&str>, json: bool) -> Result<()> { - let root = find_root(None)?; - let rows = collect_rows(&root, all, status)?; + let store = TaskStore::discover()?; + let rows = collect_rows(&store, all, status)?; if json { println!("{}", render_json(&rows)); } else { @@ -27,9 +25,9 @@ pub fn run(all: bool, status: Option<&str>, json: bool) -> Result<()> { Ok(()) } -fn collect_rows(root: &Path, all: bool, status: Option<&str>) -> Result> { +fn collect_rows(store: &TaskStore, all: bool, status: Option<&str>) -> Result> { if let Some(name) = status - && !root.join(name).is_dir() + && !store.has_status(name) { return Err(CubilError::StatusMissing(name.to_string())); } @@ -38,7 +36,7 @@ fn collect_rows(root: &Path, all: bool, status: Option<&str>) -> Result status: entry_status, slug, path, - } in scan_all(root)? + } in store.tasks()? { let keep = match status { Some(name) => entry_status == name, diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 1bae8d6..48eeedc 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -10,46 +10,14 @@ pub mod show; pub mod start; pub mod update; -use crate::core::error::{CubilError, Result}; -use crate::core::{root, slug as slug_mod}; +use crate::core::error::Result; +use crate::core::store::TaskStore; /// Move a task from `expected` status to `target` status. /// -/// Errors with [`CubilError::StatusMismatch`] if the task exists but is in a -/// different status folder. `SlugNotFound` / `SlugAmbiguous` propagate from -/// [`slug_mod::resolve_slug`]. Errors with [`CubilError::StatusMissing`] if -/// the destination folder does not exist, and [`CubilError::SlugCollision`] -/// if a file with the same slug already exists at the destination. -pub(crate) fn transition(slug: String, expected: &str, target: &str) -> Result<()> { - let root = root::find_root(None)?; - let (current_status, current_path) = slug_mod::resolve_slug(&root, &slug)?; - - if current_status != expected { - return Err(CubilError::StatusMismatch { - slug, - expected: expected.to_string(), - actual: current_status, - }); - } - - let dest_dir = root.join(target); - if !dest_dir.is_dir() { - return Err(CubilError::StatusMissing(target.to_string())); - } - - let file_name = current_path - .file_name() - .expect("resolve_slug returns a file path"); - let dest_path = dest_dir.join(file_name); - // NOTE: local single-user tool — TOCTOU window between exists() check and - // rename() is acceptable. - if dest_path.exists() { - return Err(CubilError::SlugCollision { - slug, - status: target.to_string(), - }); - } - - std::fs::rename(¤t_path, &dest_path)?; - Ok(()) +/// Errors with [`crate::core::error::CubilError::StatusMismatch`] if the task +/// exists but is in a different status folder. Every other rule lives in +/// [`TaskStore::transition`]. +pub(crate) fn transition(slug: &str, expected: &str, target: &str) -> Result<()> { + TaskStore::discover()?.transition(slug, expected, target) } diff --git a/src/commands/mv.rs b/src/commands/mv.rs index a78b8e1..38bd5fd 100644 --- a/src/commands/mv.rs +++ b/src/commands/mv.rs @@ -1,40 +1,11 @@ -use crate::core::error::{CubilError, Result}; -use crate::core::{root, slug as slug_mod}; +use crate::core::error::Result; +use crate::core::store::TaskStore; /// Move task `` into `//`. /// -/// - Errors with [`CubilError::SlugNotFound`] / [`CubilError::SlugAmbiguous`] -/// via [`slug_mod::resolve_slug`]. -/// - Errors with [`CubilError::StatusMissing`] if the destination folder does -/// not exist (users create status folders themselves). -/// - Errors with [`CubilError::SlugCollision`] if a file with the same slug -/// already exists in the destination. -/// - If the resolved status equals the target, returns `Ok(())` without -/// touching the file or printing anything. -/// - Otherwise, atomically renames the file via [`std::fs::rename`]. -pub fn run(slug: String, status: String) -> Result<()> { - let root = root::find_root(None)?; - let (current_status, current_path) = slug_mod::resolve_slug(&root, &slug)?; - - if current_status == status { - return Ok(()); - } - - let dest_dir = root.join(&status); - if !dest_dir.is_dir() { - return Err(CubilError::StatusMissing(status)); - } - - let file_name = current_path - .file_name() - .expect("resolve_slug returns a file path"); - let dest_path = dest_dir.join(file_name); - // NOTE: local single-user tool — TOCTOU window between exists() check and - // rename() is acceptable. - if dest_path.exists() { - return Err(CubilError::SlugCollision { slug, status }); - } - - std::fs::rename(¤t_path, &dest_path)?; - Ok(()) +/// If the task is already in `status`, returns `Ok(())` without touching the +/// file or printing anything. Every other rule (missing status folder, slug +/// collision, ambiguity) lives in [`TaskStore::move_to`]. +pub fn run(slug: &str, status: &str) -> Result<()> { + TaskStore::discover()?.move_to(slug, status) } diff --git a/src/commands/new.rs b/src/commands/new.rs index 39fca47..1694291 100644 --- a/src/commands/new.rs +++ b/src/commands/new.rs @@ -3,10 +3,8 @@ use std::path::Path; use crate::core::error::{CubilError, Result}; use crate::core::frontmatter::{TaskMeta, render_frontmatter}; -use crate::core::root::find_root; -use crate::core::slug::{scan_all, slugify}; - -const BACKLOG: &str = "backlog"; +use crate::core::slug::slugify; +use crate::core::store::TaskStore; /// Create a new task file under `.cubil/backlog/`. /// @@ -14,16 +12,15 @@ const BACKLOG: &str = "backlog"; /// mutually exclusive (enforced by clap); passing neither produces an empty /// body. When `file` is `Some("-")`, the body is read from stdin. pub fn run(title: &str, message: Option, file: Option<&Path>) -> Result<()> { - let root = find_root(None)?; + let store = TaskStore::discover()?; let slug = slugify(title)?; - for entry in scan_all(&root)? { - if entry.slug == slug { - return Err(CubilError::SlugCollision { - slug, - status: entry.status, - }); - } + // Fail on a collision before reading the body, which may block on stdin. + if let Some(existing) = store.lookup()?.get(&slug) { + return Err(CubilError::SlugCollision { + slug, + status: existing.status.clone(), + }); } let body = read_body(message, file)?; @@ -36,8 +33,7 @@ pub fn run(title: &str, message: Option, file: Option<&Path>) -> Result< let contents = assemble(&meta, title, &body); - let path = root.join(BACKLOG).join(format!("{slug}.md")); - std::fs::write(&path, contents)?; + store.create(&slug, &contents)?; println!("{slug}"); Ok(()) diff --git a/src/commands/rm.rs b/src/commands/rm.rs index 73c0c96..af2c7c5 100644 --- a/src/commands/rm.rs +++ b/src/commands/rm.rs @@ -1,13 +1,10 @@ use crate::core::error::Result; -use crate::core::{root, slug}; +use crate::core::store::TaskStore; /// Delete a task file. /// -/// Locates `.cubil/` by walking upward from cwd, resolves the slug across all -/// status folders, and removes the file. Silent on success. +/// Resolves the slug across all status folders and removes the file. Silent +/// on success. pub fn run(slug: &str) -> Result<()> { - let root = root::find_root(None)?; - let (_status, path) = slug::resolve_slug(&root, slug)?; - std::fs::remove_file(&path)?; - Ok(()) + TaskStore::discover()?.remove(slug) } diff --git a/src/commands/roadmap/add.rs b/src/commands/roadmap/add.rs index 66f964c..7347d4c 100644 --- a/src/commands/roadmap/add.rs +++ b/src/commands/roadmap/add.rs @@ -4,8 +4,7 @@ use crate::core::error::{CubilError, Result}; use crate::core::roadmap::{ parse_h2_heading, parse_milestone_heading, parse_task_line, resolve_roadmap, }; -use crate::core::root::find_root; -use crate::core::slug::scan_all; +use crate::core::store::TaskStore; /// Append `- [ ] ` to a roadmap. /// @@ -18,18 +17,11 @@ use crate::core::slug::scan_all; /// 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<()> { - let root = find_root(None)?; - let path = resolve_roadmap(&root, &roadmap_slug)?; - - // Validate task exists somewhere. - let mut found = false; - for entry in scan_all(&root)? { - if entry.slug == task_slug { - found = true; - break; - } - } - if !found { + let store = TaskStore::discover()?; + 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)); } diff --git a/src/commands/roadmap/next.rs b/src/commands/roadmap/next.rs index 592237e..64abdf1 100644 --- a/src/commands/roadmap/next.rs +++ b/src/commands/roadmap/next.rs @@ -2,8 +2,7 @@ use std::collections::HashMap; use crate::core::error::Result; use crate::core::roadmap::{TaskStatus, parse_task_line, resolve_roadmap}; -use crate::core::root::find_root; -use crate::core::slug::scan_all; +use crate::core::store::TaskStore; /// Print the slug of the next not-done task in the roadmap. /// @@ -12,23 +11,23 @@ use crate::core::slug::scan_all; /// skipped, since `next` exists to drive `cubil start `). Empty stdout /// + zero exit if all tasks are done. Designed for shell pipelines. pub fn run(slug: &str) -> Result<()> { - let root = find_root(None)?; - let path = resolve_roadmap(&root, slug)?; + let store = TaskStore::discover()?; + let path = resolve_roadmap(store.root(), slug)?; let src = std::fs::read_to_string(&path)?; - let lookup = build_status_lookup(&root)?; + let lookup = build_status_lookup(&store)?; if let Some(next) = first_not_done(&src, &lookup) { println!("{next}"); } Ok(()) } -fn build_status_lookup(root: &std::path::Path) -> Result> { - let mut map = HashMap::new(); - for entry in scan_all(root)? { - map.entry(entry.slug).or_insert(entry.status); - } - Ok(map) +fn build_status_lookup(store: &TaskStore) -> Result> { + Ok(store + .lookup()? + .into_iter() + .map(|(slug, entry)| (slug, entry.status)) + .collect()) } fn first_not_done(src: &str, lookup: &HashMap) -> Option { diff --git a/src/commands/roadmap/show.rs b/src/commands/roadmap/show.rs index cd53a00..a1fb86c 100644 --- a/src/commands/roadmap/show.rs +++ b/src/commands/roadmap/show.rs @@ -4,8 +4,7 @@ use std::path::{Path, PathBuf}; use crate::core::error::Result; use crate::core::roadmap::{TaskStatus, parse_task_line, read_task_title, resolve_roadmap}; -use crate::core::root::find_root; -use crate::core::slug::scan_all; +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. @@ -20,11 +19,11 @@ use crate::core::slug::scan_all; /// through byte-for-byte. Only lines parsed as `- [] ` checkbox /// items are rewritten. pub fn run(slug: &str) -> Result<()> { - let root = find_root(None)?; - let path = resolve_roadmap(&root, slug)?; + let store = TaskStore::discover()?; + let path = resolve_roadmap(store.root(), slug)?; let src = std::fs::read_to_string(&path)?; - let lookup = build_lookup(&root)?; + let lookup = build_lookup(&store)?; let new_src = rewrite(&src, &lookup)?; write_atomic(&path, new_src.as_bytes())?; @@ -40,15 +39,15 @@ struct TaskInfo { title: Option, } -fn build_lookup(root: &Path) -> Result> { - let mut map = HashMap::new(); - for entry in scan_all(root)? { - // 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`. - map.entry(entry.slug).or_insert((entry.status, entry.path)); - } - Ok(map) +fn build_lookup(store: &TaskStore) -> Result> { + // 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`. + Ok(store + .lookup()? + .into_iter() + .map(|(slug, entry)| (slug, (entry.status, entry.path))) + .collect()) } fn resolve(slug: &str, lookup: &HashMap) -> Result { diff --git a/src/commands/show.rs b/src/commands/show.rs index 81eac97..9ad114d 100644 --- a/src/commands/show.rs +++ b/src/commands/show.rs @@ -2,17 +2,15 @@ use std::fs::File; use std::io; use crate::core::error::Result; -use crate::core::{root, slug}; +use crate::core::store::TaskStore; /// Print a task's full markdown contents to stdout, byte-identical. /// -/// Walks upward from cwd to find `.cubil/`, resolves the slug across every -/// status folder, and streams the file bytes verbatim — no re-encoding, no -/// trailing newline injection. +/// Resolves the slug across every status folder and streams the file bytes +/// verbatim: no re-encoding, no trailing newline injection. pub fn run(slug: &str) -> Result<()> { - let root = root::find_root(None)?; - let (_status, path) = slug::resolve_slug(&root, slug)?; - let mut file = File::open(&path)?; + let entry = TaskStore::discover()?.find(slug)?; + let mut file = File::open(&entry.path)?; let stdout = io::stdout(); let mut handle = stdout.lock(); io::copy(&mut file, &mut handle)?; diff --git a/src/commands/start.rs b/src/commands/start.rs index 13ada78..a9db044 100644 --- a/src/commands/start.rs +++ b/src/commands/start.rs @@ -1,6 +1,6 @@ use crate::core::error::Result; /// Move task `` from `backlog/` to `doing/`. -pub fn run(slug: String) -> Result<()> { +pub fn run(slug: &str) -> Result<()> { super::transition(slug, "backlog", "doing") } diff --git a/src/core/mod.rs b/src/core/mod.rs index a16929b..80d36f6 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -3,4 +3,5 @@ pub mod frontmatter; pub mod roadmap; pub mod root; pub mod slug; +pub mod store; pub mod updater; diff --git a/src/core/slug.rs b/src/core/slug.rs index 36e75c2..8eb9f4c 100644 --- a/src/core/slug.rs +++ b/src/core/slug.rs @@ -1,14 +1,5 @@ -use std::path::{Path, PathBuf}; - use crate::core::error::{CubilError, Result}; -#[derive(Debug, Clone)] -pub struct TaskEntry { - pub status: String, - pub slug: String, - pub path: PathBuf, -} - /// Convert a human title into a kebab-case, lowercase, ASCII-only slug. /// /// Non-alphanumeric ASCII characters (including any non-ASCII) are treated as @@ -36,77 +27,9 @@ pub fn slugify(title: &str) -> Result { Ok(out) } -/// Reserved subdirectory names under `.cubil/` that are not status folders. -/// Files inside these directories are not surfaced by [`scan_all`]. -pub const RESERVED_DIRS: &[&str] = &["roadmaps"]; - -/// List every `(status, slug, absolute_path)` triple of `*.md` files under -/// the given `.cubil/` root. Each immediate subdirectory of `root` is treated -/// as a status folder, except for [`RESERVED_DIRS`] (e.g. `roadmaps/`). -pub fn scan_all(root: &Path) -> Result> { - let mut entries = Vec::new(); - for status_entry in std::fs::read_dir(root)? { - let status_entry = status_entry?; - if !status_entry.file_type()?.is_dir() { - continue; - } - let Ok(status) = status_entry.file_name().into_string() else { - continue; - }; - if RESERVED_DIRS.contains(&status.as_str()) { - continue; - } - let status_path = status_entry.path(); - for file in std::fs::read_dir(&status_path)? { - let file = file?; - if !file.file_type()?.is_file() { - continue; - } - let fname = file.file_name(); - let Some(fname_str) = fname.to_str() else { - continue; - }; - if let Some(slug) = fname_str.strip_suffix(".md") { - entries.push(TaskEntry { - status: status.clone(), - slug: slug.to_string(), - path: file.path(), - }); - } - } - } - Ok(entries) -} - -/// Locate a task file by exact slug across every status folder under -/// `.cubil/`. Returns `(status_name, absolute_path_to_md_file)`. Errors with -/// [`CubilError::SlugNotFound`] if no match, or -/// [`CubilError::SlugAmbiguous`] if the same slug exists in multiple status -/// folders. -pub fn resolve_slug(root: &Path, slug: &str) -> Result<(String, PathBuf)> { - let mut hits: Vec<(String, PathBuf)> = Vec::new(); - for entry in scan_all(root)? { - if entry.slug == slug { - hits.push((entry.status, entry.path)); - } - } - match hits.len() { - 0 => Err(CubilError::SlugNotFound(slug.to_string())), - 1 => Ok(hits.pop().expect("len checked")), - _ => { - let statuses = hits.into_iter().map(|(s, _)| s).collect(); - Err(CubilError::SlugAmbiguous { - slug: slug.to_string(), - statuses, - }) - } - } -} - #[cfg(test)] mod tests { use super::*; - use tempfile::tempdir; #[test] fn slugify_basic() { @@ -136,56 +59,4 @@ mod tests { )); assert!(matches!(slugify("").unwrap_err(), CubilError::InvalidSlug)); } - - #[test] - fn resolve_slug_finds_single_match() { - let dir = tempdir().unwrap(); - let root = dir.path(); - std::fs::create_dir(root.join("backlog")).unwrap(); - std::fs::create_dir(root.join("doing")).unwrap(); - std::fs::write(root.join("backlog").join("foo.md"), "x").unwrap(); - let (status, path) = resolve_slug(root, "foo").unwrap(); - assert_eq!(status, "backlog"); - assert_eq!(path, root.join("backlog").join("foo.md")); - } - - #[test] - fn resolve_slug_errors_when_missing() { - let dir = tempdir().unwrap(); - let root = dir.path(); - std::fs::create_dir(root.join("backlog")).unwrap(); - let err = resolve_slug(root, "nope").unwrap_err(); - assert!(matches!(err, CubilError::SlugNotFound(s) if s == "nope")); - } - - #[test] - fn resolve_slug_errors_when_ambiguous() { - let dir = tempdir().unwrap(); - let root = dir.path(); - std::fs::create_dir(root.join("backlog")).unwrap(); - std::fs::create_dir(root.join("done")).unwrap(); - std::fs::write(root.join("backlog").join("dup.md"), "x").unwrap(); - std::fs::write(root.join("done").join("dup.md"), "y").unwrap(); - let err = resolve_slug(root, "dup").unwrap_err(); - match err { - CubilError::SlugAmbiguous { slug, mut statuses } => { - assert_eq!(slug, "dup"); - statuses.sort(); - assert_eq!(statuses, vec!["backlog".to_string(), "done".to_string()]); - } - other => panic!("expected SlugAmbiguous, got {other:?}"), - } - } - - #[test] - fn scan_all_ignores_non_md_files() { - let dir = tempdir().unwrap(); - let root = dir.path(); - std::fs::create_dir(root.join("backlog")).unwrap(); - std::fs::write(root.join("backlog").join("a.md"), "x").unwrap(); - std::fs::write(root.join("backlog").join("notes.txt"), "x").unwrap(); - let entries = scan_all(root).unwrap(); - assert_eq!(entries.len(), 1); - assert_eq!(entries[0].slug, "a"); - } } diff --git a/src/core/store.rs b/src/core/store.rs new file mode 100644 index 0000000..a42b31b --- /dev/null +++ b/src/core/store.rs @@ -0,0 +1,366 @@ +//! The Task store: finding, listing, creating, moving and removing Tasks +//! across Statuses under a `.cubil/` root. +//! +//! Every Status is a subdirectory of the root, except the +//! [`RESERVED_DIRS`]. A Task is a `.md` file inside a Status folder. +//! Slug resolution, collision, ambiguity and missing-Status rules all live +//! here, so commands only state what they want done. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use crate::core::error::{CubilError, Result}; +use crate::core::root::find_root; + +/// Status that new Tasks start in. +pub const BACKLOG: &str = "backlog"; + +/// Reserved subdirectory names under `.cubil/` that are not Status folders. +/// Files inside these directories are not surfaced by [`TaskStore::tasks`]. +pub const RESERVED_DIRS: &[&str] = &["roadmaps"]; + +#[derive(Debug, Clone)] +pub struct TaskEntry { + pub status: String, + pub slug: String, + pub path: PathBuf, +} + +#[derive(Debug, Clone)] +pub struct TaskStore { + root: PathBuf, +} + +impl TaskStore { + /// Open the store whose `.cubil/` directory is at `root`. + #[must_use] + pub fn new(root: PathBuf) -> Self { + Self { root } + } + + /// Open the store found by walking upward from the working directory. + pub fn discover() -> Result { + Ok(Self::new(find_root(None)?)) + } + + /// The `.cubil/` directory this store reads and writes. + #[must_use] + pub fn root(&self) -> &Path { + &self.root + } + + /// Whether a Status folder named `status` exists. + #[must_use] + pub fn has_status(&self, status: &str) -> bool { + self.root.join(status).is_dir() + } + + /// Every Task, across all Statuses, in directory order. + pub fn tasks(&self) -> Result> { + let mut entries = Vec::new(); + for status_entry in std::fs::read_dir(&self.root)? { + let status_entry = status_entry?; + if !status_entry.file_type()?.is_dir() { + continue; + } + let Ok(status) = status_entry.file_name().into_string() else { + continue; + }; + if RESERVED_DIRS.contains(&status.as_str()) { + continue; + } + for file in std::fs::read_dir(status_entry.path())? { + let file = file?; + if !file.file_type()?.is_file() { + continue; + } + let fname = file.file_name(); + let Some(fname_str) = fname.to_str() else { + continue; + }; + if let Some(slug) = fname_str.strip_suffix(".md") { + entries.push(TaskEntry { + status: status.clone(), + slug: slug.to_string(), + path: file.path(), + }); + } + } + } + Ok(entries) + } + + /// Slug-to-Task map for callers that tolerate ambiguity. When a slug + /// exists in several Statuses, the first one scanned wins. + pub fn lookup(&self) -> Result> { + let mut map = HashMap::new(); + for entry in self.tasks()? { + map.entry(entry.slug.clone()).or_insert(entry); + } + Ok(map) + } + + /// Locate a Task by exact slug. Errors with + /// [`CubilError::SlugNotFound`] if there is no match and + /// [`CubilError::SlugAmbiguous`] if the slug exists in several Statuses. + pub fn find(&self, slug: &str) -> Result { + let mut hits: Vec = self + .tasks()? + .into_iter() + .filter(|e| e.slug == slug) + .collect(); + match hits.len() { + 0 => Err(CubilError::SlugNotFound(slug.to_string())), + 1 => Ok(hits.pop().expect("len checked")), + _ => Err(CubilError::SlugAmbiguous { + slug: slug.to_string(), + statuses: hits.into_iter().map(|e| e.status).collect(), + }), + } + } + + /// Create Task `slug` in [`BACKLOG`] with file contents `text`. Errors + /// with [`CubilError::SlugCollision`] if the slug exists in any Status. + pub fn create(&self, slug: &str, text: &str) -> Result { + if let Some(existing) = self.tasks()?.into_iter().find(|e| e.slug == slug) { + return Err(CubilError::SlugCollision { + slug: slug.to_string(), + status: existing.status, + }); + } + let path = self.root.join(BACKLOG).join(format!("{slug}.md")); + std::fs::write(&path, text)?; + Ok(path) + } + + /// Move Task `slug` into Status `status`. + /// + /// Moving a Task into the Status it is already in does nothing. Errors + /// with [`CubilError::StatusMissing`] if the destination folder does not + /// exist (users create Status folders themselves) and + /// [`CubilError::SlugCollision`] if the destination already holds a file + /// with that slug. + pub fn move_to(&self, slug: &str, status: &str) -> Result<()> { + let current = self.find(slug)?; + self.move_entry(¤t, status) + } + + /// Move Task `slug` from Status `expected` into `target`. Errors with + /// [`CubilError::StatusMismatch`] if the Task is in another Status; the + /// remaining errors are those of [`TaskStore::move_to`]. + pub fn transition(&self, slug: &str, expected: &str, target: &str) -> Result<()> { + let current = self.find(slug)?; + if current.status != expected { + return Err(CubilError::StatusMismatch { + slug: slug.to_string(), + expected: expected.to_string(), + actual: current.status, + }); + } + self.move_entry(¤t, target) + } + + fn move_entry(&self, current: &TaskEntry, status: &str) -> Result<()> { + if current.status == status { + return Ok(()); + } + let dest_dir = self.root.join(status); + if !dest_dir.is_dir() { + return Err(CubilError::StatusMissing(status.to_string())); + } + let file_name = current + .path + .file_name() + .expect("tasks() returns file paths"); + let dest_path = dest_dir.join(file_name); + // NOTE: local single-user tool: the TOCTOU window between exists() + // and rename() is acceptable. + if dest_path.exists() { + return Err(CubilError::SlugCollision { + slug: current.slug.clone(), + status: status.to_string(), + }); + } + std::fs::rename(¤t.path, &dest_path)?; + Ok(()) + } + + /// Delete Task `slug`. + pub fn remove(&self, slug: &str) -> Result<()> { + let entry = self.find(slug)?; + std::fs::remove_file(&entry.path)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::{TempDir, tempdir}; + + fn store_with(statuses: &[&str]) -> (TempDir, TaskStore) { + let dir = tempdir().unwrap(); + for s in statuses { + std::fs::create_dir(dir.path().join(s)).unwrap(); + } + let store = TaskStore::new(dir.path().to_path_buf()); + (dir, store) + } + + fn put(dir: &TempDir, status: &str, slug: &str) { + std::fs::write(dir.path().join(status).join(format!("{slug}.md")), "x").unwrap(); + } + + #[test] + fn find_returns_single_match() { + let (dir, store) = store_with(&["backlog", "doing"]); + put(&dir, "backlog", "foo"); + let entry = store.find("foo").unwrap(); + assert_eq!(entry.status, "backlog"); + assert_eq!(entry.path, dir.path().join("backlog").join("foo.md")); + } + + #[test] + fn find_errors_when_missing() { + let (_dir, store) = store_with(&["backlog"]); + let err = store.find("nope").unwrap_err(); + assert!(matches!(err, CubilError::SlugNotFound(s) if s == "nope")); + } + + #[test] + fn find_errors_when_ambiguous() { + let (dir, store) = store_with(&["backlog", "done"]); + put(&dir, "backlog", "dup"); + put(&dir, "done", "dup"); + match store.find("dup").unwrap_err() { + CubilError::SlugAmbiguous { slug, mut statuses } => { + assert_eq!(slug, "dup"); + statuses.sort(); + assert_eq!(statuses, vec!["backlog".to_string(), "done".to_string()]); + } + other => panic!("expected SlugAmbiguous, got {other:?}"), + } + } + + #[test] + fn tasks_ignores_non_md_files_and_reserved_dirs() { + let (dir, store) = store_with(&["backlog", "roadmaps"]); + put(&dir, "backlog", "a"); + put(&dir, "roadmaps", "r"); + std::fs::write(dir.path().join("backlog").join("notes.txt"), "x").unwrap(); + let entries = store.tasks().unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].slug, "a"); + } + + #[test] + fn lookup_maps_slug_to_entry() { + let (dir, store) = store_with(&["backlog", "doing"]); + put(&dir, "backlog", "a"); + put(&dir, "doing", "b"); + let map = store.lookup().unwrap(); + assert_eq!(map["a"].status, "backlog"); + assert_eq!(map["b"].status, "doing"); + assert!(!map.contains_key("c")); + } + + #[test] + fn create_writes_into_backlog() { + let (dir, store) = store_with(&["backlog"]); + let path = store.create("new-one", "hello").unwrap(); + assert_eq!(path, dir.path().join("backlog").join("new-one.md")); + assert_eq!(std::fs::read_to_string(path).unwrap(), "hello"); + } + + #[test] + fn create_rejects_slug_in_any_status() { + let (dir, store) = store_with(&["backlog", "done"]); + put(&dir, "done", "taken"); + let err = store.create("taken", "x").unwrap_err(); + assert!( + matches!(err, CubilError::SlugCollision { slug, status } if slug == "taken" && status == "done") + ); + } + + #[test] + fn move_to_renames_file() { + let (dir, store) = store_with(&["backlog", "doing"]); + put(&dir, "backlog", "t"); + store.move_to("t", "doing").unwrap(); + assert!(!dir.path().join("backlog").join("t.md").exists()); + assert!(dir.path().join("doing").join("t.md").exists()); + } + + #[test] + fn move_to_same_status_is_noop() { + let (dir, store) = store_with(&["backlog"]); + put(&dir, "backlog", "t"); + store.move_to("t", "backlog").unwrap(); + assert!(dir.path().join("backlog").join("t.md").exists()); + } + + #[test] + fn move_to_errors_when_status_missing() { + let (dir, store) = store_with(&["backlog"]); + put(&dir, "backlog", "t"); + let err = store.move_to("t", "doing").unwrap_err(); + assert!(matches!(err, CubilError::StatusMissing(s) if s == "doing")); + } + + #[test] + fn move_to_errors_when_destination_holds_slug() { + let (dir, store) = store_with(&["backlog", "doing"]); + put(&dir, "backlog", "t"); + // A directory named like the Task is not a Task, so find() ignores + // it, but it still blocks the rename. + std::fs::create_dir(dir.path().join("doing").join("t.md")).unwrap(); + let err = store.move_to("t", "doing").unwrap_err(); + assert!(matches!(err, CubilError::SlugCollision { status, .. } if status == "doing")); + } + + #[test] + fn move_to_errors_on_unknown_slug() { + let (_dir, store) = store_with(&["backlog", "doing"]); + let err = store.move_to("t", "doing").unwrap_err(); + assert!(matches!(err, CubilError::SlugNotFound(_))); + } + + #[test] + fn transition_moves_when_status_matches() { + let (dir, store) = store_with(&["backlog", "doing"]); + put(&dir, "backlog", "t"); + store.transition("t", "backlog", "doing").unwrap(); + assert!(dir.path().join("doing").join("t.md").exists()); + } + + #[test] + fn transition_errors_on_status_mismatch() { + let (dir, store) = store_with(&["backlog", "doing"]); + put(&dir, "doing", "t"); + let err = store.transition("t", "backlog", "doing").unwrap_err(); + assert!(matches!( + err, + CubilError::StatusMismatch { expected, actual, .. } + if expected == "backlog" && actual == "doing" + )); + } + + #[test] + fn remove_deletes_file() { + let (dir, store) = store_with(&["backlog"]); + put(&dir, "backlog", "t"); + store.remove("t").unwrap(); + assert!(!dir.path().join("backlog").join("t.md").exists()); + assert!(matches!( + store.remove("t").unwrap_err(), + CubilError::SlugNotFound(_) + )); + } + + #[test] + fn has_status_checks_directory() { + let (_dir, store) = store_with(&["backlog"]); + assert!(store.has_status("backlog")); + assert!(!store.has_status("doing")); + } +} diff --git a/src/main.rs b/src/main.rs index 59aea05..9947be2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -149,9 +149,9 @@ fn main() { Commands::List { all, status, json } => commands::list::run(all, status.as_deref(), json), Commands::Show { slug } => commands::show::run(&slug), Commands::Edit { slug } => commands::edit::run(&slug), - Commands::Mv { slug, status } => commands::mv::run(slug, status), - Commands::Start { slug } => commands::start::run(slug), - Commands::Finish { slug } => commands::finish::run(slug), + Commands::Mv { slug, status } => commands::mv::run(&slug, &status), + Commands::Start { slug } => commands::start::run(&slug), + Commands::Finish { slug } => commands::finish::run(&slug), Commands::Rm { slug } => commands::rm::run(&slug), Commands::Update => commands::update::run(), Commands::Roadmap { command } => match command {