use anyhow::{Result, anyhow}; use chrono::Local; use std::fs; use std::io::Write; use std::path::Path; use crate::util::*; pub fn cmd_init(start: &Path) -> Result<()> { let dir = start.canonicalize().unwrap_or_else(|_| start.to_path_buf()); let worklane_dir = dir.join(".worklane"); if worklane_dir.exists() { println!( "worklane already initialized in: {}", worklane_dir.display() ); return Ok(()); } fs::create_dir_all(&worklane_dir)?; let folders = ["backlog", "committed", "reviewing", "done"]; for folder in &folders { fs::create_dir_all(worklane_dir.join(folder))?; } println!("Initialized worklane in: {}", worklane_dir.display()); Ok(()) } pub fn cmd_ls( status_filter: &Option, priority_filter: Option, worklane_dir: &Path, ) -> Result<()> { if let Some(status) = status_filter { let status_path = worklane_dir.join(status); if !status_path.exists() { return Err(anyhow!( "Status '{}' not found. Valid statuses: backlog, committed, reviewing, done", status )); } let items = filter_by_priority(collect_ticket_items(&status_path)?, priority_filter); if items.is_empty() { println!("No tickets in '{}' status.", status); return Ok(()); } println!("Tickets in '{}' status:\n", status); display_ticket_items(&items); } else { // List all statuses with their ticket counts let statuses = status_dirs(); println!("Tickets by status:\n"); for status in &statuses { let status_path = worklane_dir.join(status); if !status_path.exists() { continue; } let items = filter_by_priority(collect_ticket_items(&status_path)?, priority_filter); let count = items.len(); let label = if count == 1 { "ticket" } else { "tickets" }; println!(" [{}] {} {}", status.to_uppercase(), count, label); } // Show all tickets except done grouped by status for status in &statuses { if *status == "done" { continue; } let status_path = worklane_dir.join(status); if !status_path.exists() || !fs::metadata(&status_path)?.is_dir() { continue; } let items = match collect_ticket_items(&status_path) { Ok(items) => filter_by_priority(items, priority_filter), Err(_) => continue, }; if items.is_empty() { continue; } let status_header = color_text(&format!("[{}]", status.to_uppercase()), "orange"); println!("\n{}", status_header); display_ticket_items(&items); } } Ok(()) } /// Keep only the tickets at `level`, or everything when no level was asked for. fn filter_by_priority(items: Vec, level: Option) -> Vec { match level { Some(level) => items .into_iter() .filter(|item| item.priority == Priority::Level(level)) .collect(), None => items, } } pub fn cmd_add( title: &str, description: &[String], acceptance: &[String], plan: &[String], tags: &[String], due: &Option, owner: &Option, priority: Option, start: &Path, ) -> Result<()> { let owner = match owner { Some(o) => Some(o.clone()), None => get_git_user(), }; let worklane_dir = find_worklane_dir(start)?; let backlog_dir = worklane_dir.join("backlog"); if !backlog_dir.exists() { return Err(anyhow!( "Backlog directory not found. Run `worklane init` first." )); } let id = uuid::Uuid::new_v4(); let slug = slug(title); let filename = format!("{}_{}.md", id, slug); let filepath = backlog_dir.join(&filename); if filepath.exists() { return Err(anyhow!("A ticket with this title already exists.")); } let description_text = if description.is_empty() { "_No description provided._".to_string() } else { description.join("\n") }; let mut body = format!( "# {}\n\ \n\ ## Description\n\ {}\n\ \n\ ## Acceptance Criteria\n\ {}\n\ \n\ ## Implementation Plan\n\ {}\n\ \n\ ## Metadata\n\ \n\ - **ID**: {}\n\ - **Priority**: {}\n\ - **Tags**: {}\n\ - **Due**: {}\n\ - **Owner**: {}\n\ - **Created At**: {}\n\ - **Status**: backlog\n\ ", title, description_text, if acceptance.is_empty() { "_No acceptance criteria provided._".to_string() } else { acceptance .iter() .map(|c| format!("- [ ] {}", c)) .collect::>() .join("\n") }, if plan.is_empty() { "_No implementation plan provided._".to_string() } else { plan.iter() .enumerate() .map(|(i, s)| format!("{}. {}", i + 1, s)) .collect::>() .join("\n") }, id, match priority { Some(level) => level.to_string(), None => "_Not set_".to_string(), }, if tags.is_empty() { "_None_".to_string() } else { tags.join(", ") }, due.as_deref().unwrap_or("_Not set_"), owner.as_deref().unwrap_or("_Not set_"), Local::now().format(TIMESTAMP_FORMAT), ); body.push('\n'); fs::write(&filepath, body)?; println!("Created ticket: {}", filename); Ok(()) } fn read_comments(comments_dir: &Path) -> Result> { if !comments_dir.exists() { return Ok(vec![]); } let mut comments: Vec<(String, String, String, String)> = Vec::new(); for entry in fs::read_dir(comments_dir)? { let entry = entry?; let path = entry.path(); if path.extension().map_or(false, |e| e == "md") { let content = fs::read_to_string(&path)?; let filename = path .file_stem() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_default(); let author = content .lines() .find(|l| l.starts_with("**Author**")) .and_then(|l| l.splitn(2, "**Author**:").nth(1)) .map(|s| s.trim().to_string()) .unwrap_or_else(|| "unknown".to_string()); let time = content .lines() .find(|l| l.starts_with("**Time**")) .and_then(|l| l.splitn(2, "**Time**:").nth(1)) .map(|s| s.trim().to_string()) .unwrap_or_else(|| "unknown".to_string()); let body = if let Some(after_comment) = content.strip_prefix("**Comment**\n") { if let Some(end) = after_comment.find("\n\n**Author**") { after_comment[..end].trim() } else { after_comment.trim() } } else { "" }; comments.push((filename, author, time, body.to_string())); } } comments.sort_by(|a, b| a.0.cmp(&b.0)); Ok(comments) } /// Write a comment under the first free name derived from `stem`. /// /// `create_new` rather than `fs::write`: a name that already exists means another /// comment landed in the same microsecond, and truncating it is exactly the data /// loss this guards against. The suffix is zero padded so the names keep sorting /// in the order they were written. fn write_new_comment(comments_dir: &Path, stem: &str, content: &str) -> Result { for attempt in 0..100 { let filename = match attempt { 0 => format!("{}.md", stem), n => format!("{}_{:02}.md", stem, n), }; match fs::OpenOptions::new() .write(true) .create_new(true) .open(comments_dir.join(&filename)) { Ok(mut file) => { file.write_all(content.as_bytes())?; return Ok(filename); } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(e.into()), } } Err(anyhow!( "No free comment filename for '{}' in {}", stem, comments_dir.display() )) } pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> { let (_status, title, content) = resolve_ticket(search, worklane_dir)?; let ticket_uuid = parse_ticket_field(&content, "ID"); // The only title in the output: content_trim_colored used to print it a second // time from the file content. Green per the colour guideline, and the rule is // measured in characters so a non-ASCII title is not over-drawn. println!("{}", color_text(&title, "green")); println!("{}", "─".repeat(title.chars().count())); println!("\n{}", content_trim_colored(&content)); if ticket_uuid != "_Not set_" { let comments_dir = worklane_dir.join("comments").join(&ticket_uuid); let comments = read_comments(&comments_dir)?; let formatted = format_comments(&comments); println!("{}", formatted); } Ok(()) } pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -> Result<()> { let valid_statuses = ["backlog", "committed", "reviewing", "done"]; let forward_order = ["backlog", "committed", "reviewing", "done"]; if !valid_statuses.contains(&target_status) { return Err(anyhow!( "Invalid target status '{}'. Valid statuses: {}", target_status, valid_statuses.join(", ") )); } let worklane_dir = find_worklane_dir(start)?; let (current_status, title, _) = resolve_ticket(ticket_id, &worklane_dir)?; let current_idx = forward_order .iter() .position(|&s| s == current_status) .unwrap(); let target_idx = forward_order .iter() .position(|&s| s == target_status) .unwrap(); if !force && target_idx < current_idx { return Err(anyhow!( "Cannot move backward from {} to {}. Use --force (-f) to allow.", color_text(¤t_status, "orange"), color_text(target_status, "orange"), )); } if !force && target_idx != current_idx + 1 && target_idx != current_idx { return Err(anyhow!( "Can only move one stage forward at a time. Use --force (-f) to skip stages." )); } if current_status == target_status { println!( "Ticket is already in '{}' status.", color_text(&target_status, "orange") ); return Ok(()); } let current_path = worklane_dir.join(¤t_status); let target_path = worklane_dir.join(target_status); // Find the ticket file let mut found_filename = String::new(); for entry in fs::read_dir(¤t_path)? { let entry = entry?; let path = entry.path(); if path.extension().map_or(false, |e| e == "md") { let file_content = fs::read_to_string(&path)?; let file_title = file_content .lines() .find(|l| l.starts_with("# ")) .map(|l| l[2..].trim()) .unwrap_or("") .to_string(); if file_title == title { found_filename = path.file_name().unwrap().to_string_lossy().to_string(); break; } } } if found_filename.is_empty() { return Err(anyhow!( "Could not find ticket file in {}", color_text(¤t_status, "orange") )); } // Read and update the ticket content before touching the filesystem, so a ticket // without a Status field is never half-moved. let source_path = current_path.join(&found_filename); let content = fs::read_to_string(&source_path)?; let content = set_status_field(&content, target_status, &title)?; // Move the file let dest_path = target_path.join(&found_filename); fs::rename(&source_path, &dest_path)?; // Write back updated content fs::write(&dest_path, content)?; println!( "Moved ticket '{}' from {} to {}", color_text(&title, "green"), color_text(¤t_status, "orange"), color_text(target_status, "orange"), ); Ok(()) } #[cfg(test)] mod tests { use super::*; /// The collision path cannot be provoked from the CLI, since two processes /// will not share a microsecond, but it is the whole point of the guard. #[test] fn a_colliding_stem_takes_the_next_name_and_keeps_the_first() { let dir = std::env::temp_dir().join(format!("worklane-test-{}", uuid::Uuid::new_v4())); fs::create_dir_all(&dir).unwrap(); let first = write_new_comment(&dir, "20260820_143012_123456", "first").unwrap(); let second = write_new_comment(&dir, "20260820_143012_123456", "second").unwrap(); let third = write_new_comment(&dir, "20260820_143012_123456", "third").unwrap(); assert_eq!(first, "20260820_143012_123456.md"); assert_eq!(second, "20260820_143012_123456_01.md"); assert_eq!(third, "20260820_143012_123456_02.md"); // Nothing was truncated on the way through assert_eq!(fs::read_to_string(dir.join(&first)).unwrap(), "first"); assert_eq!(fs::read_to_string(dir.join(&second)).unwrap(), "second"); assert_eq!(fs::read_to_string(dir.join(&third)).unwrap(), "third"); // read_comments sorts on the stem, so the names must sort in write order let mut names = vec![second.clone(), third.clone(), first.clone()]; names.sort(); assert_eq!(names, vec![first, second, third]); fs::remove_dir_all(&dir).unwrap(); } } pub fn cmd_comment( ticket_id: &str, body: &str, owner: &Option, start: &Path, ) -> Result<()> { if body.is_empty() { return Err(anyhow!("Comment body is required.")); } let worklane_dir = find_worklane_dir(start)?; let (_status, title, content) = resolve_ticket(ticket_id, &worklane_dir)?; let ticket_uuid = parse_ticket_field(&content, "ID"); if ticket_uuid == "_Not set_" { return Err(anyhow!("Could not determine ticket ID.")); } let comments_dir = worklane_dir.join("comments").join(&ticket_uuid); fs::create_dir_all(&comments_dir)?; let stem = Local::now().format(COMMENT_FILE_FORMAT).to_string(); let author = match owner { Some(o) => o.clone(), None => get_git_user().unwrap_or_else(|| "unknown".to_string()), }; let comment_content = format!( "**Comment**\n\ {}\n\ \n\ **Author**: {}\n\ **Time**: {}\n\ ", body, author, Local::now().format(TIMESTAMP_FORMAT) ); let filename = write_new_comment(&comments_dir, &stem, &comment_content)?; println!("Comment added to '{}' ({})", title, filename); Ok(()) }