diff --git a/.opencode/agent/reviewing-agent.md b/.opencode/agent/reviewing-agent.md index d7415e6..97beca5 100644 --- a/.opencode/agent/reviewing-agent.md +++ b/.opencode/agent/reviewing-agent.md @@ -91,3 +91,5 @@ After adding the comment, recommend whether the ticket should: - Move to `done` if implementation is satisfactory - Stay in `reviewing` for another round of changes - Be moved back to `committed` if significant rework is needed + +## YOU MUST END YOUR RESPONSE BY ADDING A COMMENT TO THE TICKET REVIEWED diff --git a/src/handlers.rs b/src/handlers.rs new file mode 100644 index 0000000..860e796 --- /dev/null +++ b/src/handlers.rs @@ -0,0 +1,392 @@ +use anyhow::{Result, anyhow}; +use chrono::Local; +use std::fs; +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, 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 = collect_ticket_items(&status_path)?; + + 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 entries: Vec<_> = fs::read_dir(&status_path)?.filter_map(|e| e.ok()).collect(); + let count = entries.len(); + let label = if count == 1 { "ticket" } else { "tickets" }; + println!(" [{}] {} {}", status.to_uppercase(), count, label); + } + + // Show all tickets grouped by status + for status in &statuses { + 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) => items, + 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(()) +} + +pub fn cmd_add( + title: &str, + description: &Option, + acceptance: &[String], + plan: &[String], + tags: &[String], + due: &Option, + owner: &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 = description + .as_deref() + .unwrap_or("_No description provided._"); + + 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\ + - **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, + 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("%Y-%m-%d %H:%M:%S"), + ); + 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) +} + +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"); + + println!("{}", title); + println!("{}", "─".repeat(title.len())); + 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.", + current_status, + target_status + )); + } + + 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.", target_status); + 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 {}", current_status)); + } + + // Read and update the ticket content + let mut content = fs::read_to_string(current_path.join(&found_filename))?; + + // Update Status in Metadata section + if let Some(start_pos) = content.find("- **Status**") { + // Skip "- " to find "**Status**" + let status_start = start_pos + 2; + let after_status = &content[status_start + "**Status**".len()..]; // after "**Status**" + if after_status.starts_with(": ") { + let rest = &after_status[2..]; + let value_end = rest.find('\n').unwrap_or(rest.len()); + let _value = &rest[..value_end]; + let before = &content[..status_start]; + let after = &rest[value_end..]; + content = format!("{}**-Status**: {}\n{}", before, target_status, after); + } + } + + // Move the file + fs::rename( + current_path.join(&found_filename), + target_path.join(&found_filename), + )?; + + // Write back updated content + fs::write(target_path.join(&found_filename), content)?; + + println!( + "Moved ticket '{}' from {} to {}", + title, current_status, target_status + ); + + Ok(()) +} + +pub fn cmd_comment(ticket_id: &str, body: &str, 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 timestamp = Local::now().format("%Y%m%d_%H%M%S"); + let filename = format!("{}.md", timestamp); + let filepath = comments_dir.join(&filename); + + let author = 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("%Y-%m-%d %H:%M:%S") + ); + + fs::write(&filepath, comment_content)?; + + println!("Comment added to '{}' ({})", title, filename); + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index 666a2e0..2fb59c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,825 +1,13 @@ -use anyhow::{Result, anyhow}; -use chrono::Local; +use anyhow::Result; use clap::Parser; -use std::fs; -use std::io::IsTerminal; -use std::path::Path; mod command; +mod handlers; +mod util; use command::*; - -fn should_use_colors() -> bool { - std::io::stdout().is_terminal() -} - -fn get_color(color: &str) -> &'static str { - match color { - "red" => "\x1b[31m", - "cyan" => "\x1b[36m", - "orange" => "\x1b[33m", - "green" => "\x1b[32m", - "grey" => "\x1b[90m", - _ => "", - } -} - -fn color_text(text: &str, color: &str) -> String { - if should_use_colors() { - format!("{}{}{}", get_color(color), text, "\x1b[0m") - } else { - text.to_string() - } -} - -fn find_worklane_dir(start: &Path) -> Result { - let mut current = start.canonicalize()?; - - loop { - let worklane_dir = current.join(".worklane"); - if worklane_dir.exists() { - return Ok(worklane_dir); - } - - if !current.pop() { - break; - } - } - - Err(anyhow!( - "No .worklane directory found. Run `worklane init` first." - )) -} - -fn slug(title: &str) -> String { - title - .to_lowercase() - .chars() - .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_') - .map(|c| if c == ' ' { '-' } else { c }) - .collect() -} - -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(()) -} - -fn parse_ticket_field(content: &str, field: &str) -> String { - let pattern = format!("**{}**:", field); - content - .lines() - .find(|line| line.contains(&pattern)) - .map(|line| { - line.splitn(2, &pattern) - .nth(1) - .unwrap_or("_Not set_") - .trim() - .to_string() - }) - .unwrap_or("_Not set_".to_string()) -} - -fn format_created_at(created_at: &str) -> String { - if created_at == "_Not set_" || created_at.is_empty() { - return "".to_string(); - } - if created_at.len() < 16 { - return created_at.to_string(); - } - // Parse "YYYY-MM-DD HH:MM:SS" -> "YY-MM-DD:HH" - let year = &created_at[2..4]; - let month = &created_at[5..7]; - let day = &created_at[8..10]; - let hour = &created_at[11..13]; - format!("{}-{}-{}:{}", year, month, day, hour) -} - -fn status_dirs() -> Vec<&'static str> { - vec!["backlog", "committed", "reviewing", "done"] -} - -fn cmd_ls(status_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 entries: Vec<_> = fs::read_dir(&status_path)?.filter_map(|e| e.ok()).collect(); - - if entries.is_empty() { - println!("No tickets in '{}' status.", status); - return Ok(()); - } - - let mut items: Vec<_> = entries - .iter() - .filter_map(|e| { - let content = fs::read_to_string(e.path()).ok()?; - let title = content - .lines() - .find(|l| l.starts_with("# ")) - .map(|l| l[2..].trim()) - .unwrap_or("_No title_") - .to_string(); - let owner = parse_ticket_field(&content, "Owner"); - let due = parse_ticket_field(&content, "Due"); - let filename = e.path().file_stem()?.to_string_lossy().to_string(); - let uuid_short = if filename.len() > 7 { - &filename[..7] - } else { - &filename - }; - let created_at = parse_ticket_field(&content, "Created At"); - let short_date = format_created_at(&created_at); - - Some((title, owner, due, uuid_short.to_string(), short_date)) - }) - .collect(); - - items.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase())); - - println!("Tickets in '{}' status:\n", status); - for (title, owner, due, uuid, ts) in items { - let uuid_colored = color_text(&uuid, "red"); - if ts.is_empty() { - println!( - " ({}) {} | Owner: {} | Due: {}", - uuid_colored, title, owner, due - ); - } else { - let ts_colored = color_text(&ts, "cyan"); - println!( - " {} ({}) {} | Owner: {} | Due: {}", - ts_colored, uuid_colored, title, owner, due - ); - } - } - } 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 entries: Vec<_> = fs::read_dir(&status_path)?.filter_map(|e| e.ok()).collect(); - let count = entries.len(); - let label = if count == 1 { "ticket" } else { "tickets" }; - println!(" [{}] {} {}", status.to_uppercase(), count, label); - } - - // Show all tickets grouped by status - for status in &statuses { - let status_path = worklane_dir.join(status); - if !status_path.exists() { - continue; - } - let entries: Vec<_> = fs::read_dir(&status_path)?.filter_map(|e| e.ok()).collect(); - if entries.is_empty() { - continue; - } - let mut items: Vec<_> = entries - .iter() - .filter_map(|e| { - let content = fs::read_to_string(e.path()).ok()?; - let title = content - .lines() - .find(|l| l.starts_with("# ")) - .map(|l| l[2..].trim()) - .unwrap_or("_No title_") - .to_string(); - let owner = parse_ticket_field(&content, "Owner"); - let due = parse_ticket_field(&content, "Due"); - let filename = e.path().file_stem()?.to_string_lossy().to_string(); - let uuid_short = if filename.len() > 7 { - &filename[..7] - } else { - &filename - }; - let created_at = parse_ticket_field(&content, "Created At"); - let short_date = format_created_at(&created_at); - - Some((title, owner, due, uuid_short.to_string(), short_date)) - }) - .collect(); - items.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase())); - let status_header = color_text(&format!("[{}]", status.to_uppercase()), "orange"); - println!("\n{}", status_header); - for (title, owner, due, uuid, ts) in items { - let uuid_colored = color_text(&uuid, "red"); - if ts.is_empty() { - println!( - " ({}) {} | Owner: {} | Due: {}", - uuid_colored, title, owner, due - ); - } else { - let ts_colored = color_text(&ts, "cyan"); - println!( - " {} ({}) {} | Owner: {} | Due: {}", - ts_colored, uuid_colored, title, owner, due - ); - } - } - } - } - - Ok(()) -} - -fn get_git_user() -> Option { - std::process::Command::new("git") - .args(&["config", "user.name"]) - .output() - .ok() - .and_then(|out| { - if out.status.success() { - String::from_utf8(out.stdout) - .ok() - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - } else { - None - } - }) -} - -fn cmd_add( - title: &str, - description: &Option, - acceptance: &[String], - plan: &[String], - tags: &[String], - due: &Option, - owner: &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 = description - .as_deref() - .unwrap_or("_No description provided._"); - - 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\ - - **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, - 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("%Y-%m-%d %H:%M:%S"), - ); - body.push('\n'); - - fs::write(&filepath, body)?; - - println!("Created ticket: {}", filename); - Ok(()) -} - -fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> { - let statuses = status_dirs(); - let mut matches: Vec<(String, String, String)> = Vec::new(); - - for status in &statuses { - let status_path = worklane_dir.join(status); - if !status_path.exists() { - continue; - } - let entries = fs::read_dir(&status_path)?; - for entry in entries.filter_map(|e| e.ok()) { - let path = entry.path(); - if !path.extension().map_or(false, |e| e == "md") { - continue; - } - let content = match fs::read_to_string(&path) { - Ok(c) => c, - Err(_) => continue, - }; - let title = content - .lines() - .find(|l| l.starts_with("# ")) - .map(|l| l[2..].trim()) - .unwrap_or("") - .to_string(); - let filename = path - .file_stem() - .map(|s| s.to_string_lossy().to_string()) - .unwrap_or_default(); - let id = filename.split('_').next().unwrap_or(""); - - let search_lower = search.to_lowercase(); - let title_lower = title.to_lowercase(); - let filename_lower = filename.to_lowercase(); - - let id_match = id.to_lowercase().starts_with(&search_lower) && id.len() >= 8; - let title_match = title_lower.contains(&search_lower); - let filename_match = filename_lower.contains(&search_lower); - - if id_match || title_match || filename_match { - matches.push((status.to_string(), title, content)); - } - } - } - - if matches.is_empty() { - return Err(anyhow!("No ticket found matching '{}'", search)); - } - - if matches.len() > 1 { - println!("Multiple tickets found matching '{}':", search); - for (i, (status, title, _)) in matches.iter().enumerate() { - println!(" {}. {} ({})", i + 1, title, status); - } - println!("\nTry a more specific search term."); - std::process::exit(1); - } - - Ok(matches.remove(0)) -} - -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) -} - -fn format_comments(comments: &[(String, String, String, String)]) -> String { - if comments.is_empty() { - return color_text("No comments yet.", "grey"); - } - - let mut result = String::new(); - result.push_str("\n"); - result.push_str(&color_text("COMMENTS", "orange")); - result.push_str(&format!("\n{}\n", "─".repeat(20))); - - for (_filename, author, time, body) in comments { - result.push_str("\n"); - result.push_str(&color_text(&format!("From {} ({})", author, time), "cyan")); - result.push_str("\n"); - if !body.is_empty() { - result.push_str(&" ".to_string()); - result.push_str(body); - } - result.push('\n'); - } - - result -} - -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"); - - println!("{}", title); - println!("{}", "─".repeat(title.len())); - 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(()) -} - -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.", - current_status, - target_status - )); - } - - 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.", target_status); - 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 {}", current_status)); - } - - // Read and update the ticket content - let mut content = fs::read_to_string(current_path.join(&found_filename))?; - - // Update Status in Metadata section - if let Some(start_pos) = content.find("- **Status**") { - // Skip "- " to find "**Status**" - let status_start = start_pos + 2; - let after_status = &content[status_start + "**Status**".len()..]; // after "**Status**" - if after_status.starts_with(": ") { - let rest = &after_status[2..]; - let value_end = rest.find('\n').unwrap_or(rest.len()); - let _value = &rest[..value_end]; - let before = &content[..status_start]; - let after = &rest[value_end..]; - content = format!("{}**-Status**: {}\n{}", before, target_status, after); - } - } - - // Move the file - fs::rename( - current_path.join(&found_filename), - target_path.join(&found_filename), - )?; - - // Write back updated content - fs::write(target_path.join(&found_filename), content)?; - - println!( - "Moved ticket '{}' from {} to {}", - title, current_status, target_status - ); - - Ok(()) -} - -fn cmd_comment(ticket_id: &str, body: &str, 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 timestamp = Local::now().format("%Y%m%d_%H%M%S"); - let filename = format!("{}.md", timestamp); - let filepath = comments_dir.join(&filename); - - let author = 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("%Y-%m-%d %H:%M:%S") - ); - - fs::write(&filepath, comment_content)?; - - println!("Comment added to '{}' ({})", title, filename); - Ok(()) -} - -fn content_trim_colored(content: &str) -> String { - let lines: Vec<&str> = content.trim().lines().collect(); - let mut result = String::new(); - let mut current_section = ""; - - for (_, line) in lines.iter().enumerate() { - // Track current section - if line.starts_with("## ") { - current_section = line; - let section_name = &line[3..]; - result.push_str(&format!("\x1b[33m{}\x1b[0m", section_name)); - result.push('\n'); - result.push_str(&"─".repeat(line.len())); - result.push('\n'); - result.push('\n'); - continue; - } - - // First line is the title header - color it in green - if line.starts_with("# ") && current_section.is_empty() { - let header = &line[2..]; // Remove "# " - result.push_str(&format!("\x1b[32m{}\x1b[0m", header)); - result.push('\n'); - continue; - } - - // Implementation Plan - color numbers in cyan - if current_section == "## Implementation Plan" { - result.push_str(&colorize_ordered(line)); - result.push('\n'); - continue; - } - - // Metadata - color field names in RED - if current_section == "## Metadata" { - result.push_str(&colorize_metadata(line)); - result.push('\n'); - continue; - } - - // Acceptance Criteria checkboxes - if line.starts_with("- [ ]") { - result.push_str("\x1b[90m- [ ]\x1b[0m"); - result.push_str(&line[5..]); - result.push('\n'); - continue; - } - - // Standard markdown link colorization in cyan - if line.contains("[") && line.contains("(") && line.contains("]") { - if let Some(start) = line.find("[") { - let bracket_text = &line[start..]; - if let Some(end_bracket) = bracket_text.find("](") { - let link_start = start + end_bracket + 1; - if let Some(end) = line[link_start..].find(']') { - let absolute_end = link_start + end + 1; - result.push_str("\x1b[36m"); - result.push_str(&line[start..absolute_end]); - result.push_str("\x1b[0m"); - result.push('\n'); - continue; - } - } - } - } - - // Regular content - colorize **bold** in magenta - result.push_str(&colorize_line(line)); - result.push('\n'); - } - - result -} - -fn colorize_ordered(line: &str) -> String { - if line.chars().next().map_or(true, |c| !c.is_ascii_digit()) { - return line.to_string(); - } - - // Match "1. " pattern and color the number in cyan - let mut result = String::new(); - let chars: Vec = line.chars().collect(); - - for (i, c) in chars.iter().enumerate() { - if c.is_ascii_digit() { - // still scanning digits - } else if *c == '.' && i + 1 < chars.len() && chars[i + 1] == ' ' { - let number = &line[..i + 1]; - result.push_str(&format!("\x1b[36m{}\x1b[0m", number)); - result.push_str(&line[i + 1..]); - return result; - } else { - break; - } - } - - line.to_string() -} - -fn colorize_metadata(line: &str) -> String { - if !line.contains("**") { - return line.to_string(); - } - - let content = line; - let open_pos = match content.find("**") { - Some(p) => p, - None => return content.to_string(), - }; - - let after_open = open_pos + 2; - let remaining = &content[after_open..]; - let close_pos = match remaining.find("**") { - Some(p) => p, - None => return content.to_string(), - }; - - let field_name = &content[after_open..after_open + close_pos]; - let after_field = &content[after_open + close_pos + 2..]; - - format!( - "{}{}{}{}", - &content[..open_pos], - "\x1b[31m", - field_name, - "\x1b[0m" - ) + after_field -} - -fn colorize_line(line: &str) -> String { - let mut result = String::new(); - let chars: Vec = line.chars().collect(); - let len = chars.len(); - let mut i = 0; - - while i < len { - // Check for **bold** markdown - if i + 1 < len && chars[i] == '*' && chars[i + 1] == '*' { - // Find closing ** - let start = i + 2; - let mut end = start; - while end + 1 < len && !(chars[end] == '*' && chars[end + 1] == '*') { - if chars[end] == '\n' { - break; - } - end += 1; - } - - let bold_text: String = chars[start..end].iter().collect(); - result.push_str(&format!("\x1b[1;35m{}\x1b[0m", bold_text)); - i = end + 2; - continue; - } - - result.push(chars[i]); - i += 1; - } - - result -} +use handlers::*; +use util::*; fn main() -> Result<()> { let cli = Cli::parse(); diff --git a/src/util.rs b/src/util.rs new file mode 100644 index 0000000..40c0a7e --- /dev/null +++ b/src/util.rs @@ -0,0 +1,401 @@ +use anyhow::{Result, anyhow}; +use std::fs; +use std::io::IsTerminal; +use std::path::Path; + +pub fn should_use_colors() -> bool { + std::io::stdout().is_terminal() +} + +pub fn get_color(color: &str) -> &'static str { + match color { + "red" => "\x1b[31m", + "cyan" => "\x1b[36m", + "orange" => "\x1b[33m", + "green" => "\x1b[32m", + "grey" => "\x1b[90m", + _ => "", + } +} + +pub fn color_text(text: &str, color: &str) -> String { + if should_use_colors() { + format!("{}{}{}", get_color(color), text, "\x1b[0m") + } else { + text.to_string() + } +} + +pub fn find_worklane_dir(start: &Path) -> Result { + let mut current = start.canonicalize()?; + + loop { + let worklane_dir = current.join(".worklane"); + if worklane_dir.exists() { + return Ok(worklane_dir); + } + + if !current.pop() { + break; + } + } + + Err(anyhow!( + "No .worklane directory found. Run `worklane init` first." + )) +} + +pub fn slug(title: &str) -> String { + title + .to_lowercase() + .chars() + .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_') + .map(|c| if c == ' ' { '-' } else { c }) + .collect() +} + +pub fn get_git_user() -> Option { + std::process::Command::new("git") + .args(&["config", "user.name"]) + .output() + .ok() + .and_then(|out| { + if out.status.success() { + String::from_utf8(out.stdout) + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + } else { + None + } + }) +} +pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> { + let statuses = status_dirs(); + let mut matches: Vec<(String, String, String)> = Vec::new(); + + for status in &statuses { + let status_path = worklane_dir.join(status); + if !status_path.exists() { + continue; + } + let entries = fs::read_dir(&status_path)?; + for entry in entries.filter_map(|e| e.ok()) { + let path = entry.path(); + if !path.extension().map_or(false, |e| e == "md") { + continue; + } + let content = match fs::read_to_string(&path) { + Ok(c) => c, + Err(_) => continue, + }; + let title = content + .lines() + .find(|l| l.starts_with("# ")) + .map(|l| l[2..].trim()) + .unwrap_or("") + .to_string(); + let filename = path + .file_stem() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_default(); + let id = filename.split('_').next().unwrap_or(""); + + let search_lower = search.to_lowercase(); + let title_lower = title.to_lowercase(); + let filename_lower = filename.to_lowercase(); + + let id_match = id.to_lowercase().starts_with(&search_lower) && id.len() >= 8; + let title_match = title_lower.contains(&search_lower); + let filename_match = filename_lower.contains(&search_lower); + + if id_match || title_match || filename_match { + matches.push((status.to_string(), title, content)); + } + } + } + + if matches.is_empty() { + return Err(anyhow!("No ticket found matching '{}'", search)); + } + + if matches.len() > 1 { + println!("Multiple tickets found matching '{}':", search); + for (i, (status, title, _)) in matches.iter().enumerate() { + println!(" {}. {} ({})", i + 1, title, status); + } + println!("\nTry a more specific search term."); + std::process::exit(1); + } + + Ok(matches.remove(0)) +} +pub fn format_comments(comments: &[(String, String, String, String)]) -> String { + if comments.is_empty() { + return color_text("No comments yet.", "grey"); + } + + let mut result = String::new(); + result.push_str("\n"); + result.push_str(&color_text("COMMENTS", "orange")); + result.push_str(&format!("\n{}\n", "─".repeat(20))); + + for (_filename, author, time, body) in comments { + result.push_str("\n"); + result.push_str(&color_text(&format!("From {} ({})", author, time), "cyan")); + result.push_str("\n"); + if !body.is_empty() { + result.push_str(&" ".to_string()); + result.push_str(body); + } + result.push('\n'); + } + + result +} +pub fn content_trim_colored(content: &str) -> String { + let lines: Vec<&str> = content.trim().lines().collect(); + let mut result = String::new(); + let mut current_section = ""; + + for line in &lines { + // Track current section + if line.starts_with("## ") { + current_section = line; + let section_name = &line[3..]; + result.push_str(&format!("\x1b[33m{}\x1b[0m", section_name)); + result.push('\n'); + result.push_str(&"─".repeat(line.len())); + result.push('\n'); + result.push('\n'); + continue; + } + + // First line is the title header - color it in green + if line.starts_with("# ") && current_section.is_empty() { + let header = &line[2..]; // Remove "# " + result.push_str(&format!("\x1b[32m{}\x1b[0m", header)); + result.push('\n'); + continue; + } + + // Implementation Plan - color numbers in cyan + if current_section == "## Implementation Plan" { + result.push_str(&colorize_ordered(line)); + result.push('\n'); + continue; + } + + // Metadata - color field names in RED + if current_section == "## Metadata" { + result.push_str(&colorize_metadata(line)); + result.push('\n'); + continue; + } + + // Acceptance Criteria checkboxes + if line.starts_with("- [ ]") { + result.push_str("\x1b[90m- [ ]\x1b[0m"); + result.push_str(&line[5..]); + result.push('\n'); + continue; + } + + // Standard markdown link colorization in cyan + if line.contains("[") && line.contains("(") && line.contains("]") { + if let Some(start) = line.find("[") { + let bracket_text = &line[start..]; + if let Some(end_bracket) = bracket_text.find("](") { + let link_start = start + end_bracket + 1; + if let Some(end) = line[link_start..].find(']') { + let absolute_end = link_start + end + 1; + result.push_str("\x1b[36m"); + result.push_str(&line[start..absolute_end]); + result.push_str("\x1b[0m"); + result.push('\n'); + continue; + } + } + } + } + + // Regular content - colorize **bold** in magenta + result.push_str(&colorize_line(line)); + result.push('\n'); + } + + result +} + +pub fn colorize_ordered(line: &str) -> String { + if line.chars().next().map_or(true, |c| !c.is_ascii_digit()) { + return line.to_string(); + } + + // Match "1. " pattern and color the number in cyan + let mut result = String::new(); + let chars: Vec = line.chars().collect(); + + for (i, c) in chars.iter().enumerate() { + if c.is_ascii_digit() { + // still scanning digits + } else if *c == '.' && i + 1 < chars.len() && chars[i + 1] == ' ' { + let number = &line[..i + 1]; + result.push_str(&format!("\x1b[36m{}\x1b[0m", number)); + result.push_str(&line[i + 1..]); + return result; + } else { + break; + } + } + + line.to_string() +} + +pub fn colorize_metadata(line: &str) -> String { + if !line.contains("**") { + return line.to_string(); + } + + let content = line; + let open_pos = match content.find("**") { + Some(p) => p, + None => return content.to_string(), + }; + + let after_open = open_pos + 2; + let remaining = &content[after_open..]; + let close_pos = match remaining.find("**") { + Some(p) => p, + None => return content.to_string(), + }; + + let field_name = &content[after_open..after_open + close_pos]; + let after_field = &content[after_open + close_pos + 2..]; + + format!( + "{}{}{}{}", + &content[..open_pos], + "\x1b[31m", + field_name, + "\x1b[0m" + ) + after_field +} + +pub fn colorize_line(line: &str) -> String { + let mut result = String::new(); + let chars: Vec = line.chars().collect(); + let len = chars.len(); + let mut i = 0; + + while i < len { + // Check for **bold** markdown + if i + 1 < len && chars[i] == '*' && chars[i + 1] == '*' { + // Find closing ** + let start = i + 2; + let mut end = start; + while end + 1 < len && !(chars[end] == '*' && chars[end + 1] == '*') { + if chars[end] == '\n' { + break; + } + end += 1; + } + + let bold_text: String = chars[start..end].iter().collect(); + result.push_str(&format!("\x1b[1;35m{}\x1b[0m", bold_text)); + i = end + 2; + continue; + } + + result.push(chars[i]); + i += 1; + } + + result +} + +pub fn parse_ticket_field(content: &str, field: &str) -> String { + let pattern = format!("**{}**:", field); + content + .lines() + .find(|line| line.contains(&pattern)) + .map(|line| { + line.splitn(2, &pattern) + .nth(1) + .unwrap_or("_Not set_") + .trim() + .to_string() + }) + .unwrap_or("_Not set_".to_string()) +} + +// Format created_at for display with proper spacing and formatting. +pub fn format_created_at(created_at: &str) -> String { + if created_at == "_Not set_" || created_at.is_empty() { + return String::new(); + } + if created_at.len() < 16 { + return created_at.to_string(); + } + // Parse "YYYY-MM-DD HH:MM:SS" -> "YY-MM-DD:HH" + let year = &created_at[2..4]; + let month = &created_at[5..7]; + let day = &created_at[8..10]; + let hour = &created_at[11..13]; + format!("{}-{}-{}:{}", year, month, day, hour) +} + +pub fn status_dirs() -> Vec<&'static str> { + vec!["backlog", "committed", "reviewing", "done"] +} + +pub type TicketItem = (String, String, String, String, String); + +pub fn display_ticket_items(items: &Vec) { + for (title, owner, due, uuid, ts) in items { + let uuid_colored = color_text(uuid, "red"); + if ts.is_empty() { + println!( + " ({}) {} | Owner: {} | Due: {}", + uuid_colored, title, owner, due + ); + } else { + let ts_colored = color_text(ts, "cyan"); + println!( + " {} ({}) {} | Owner: {} | Due: {}", + ts_colored, uuid_colored, title, owner, due + ); + } + } +} + +pub fn collect_ticket_items(status_path: impl AsRef) -> Result> { + let entries: Vec<_> = fs::read_dir(status_path)?.filter_map(|e| e.ok()).collect(); + + let mut items: Vec = entries + .iter() + .filter_map(|e| { + let content = fs::read_to_string(e.path()).ok()?; + let title = content + .lines() + .find(|l| l.starts_with("# ")) + .map(|l| l[2..].trim().to_string()) + .unwrap_or_else(|| "_No title_".to_string()); + let owner = parse_ticket_field(&content, "Owner"); + let due = parse_ticket_field(&content, "Due"); + let filename = e.path().file_stem()?.to_string_lossy().to_string(); + let uuid_short = if filename.len() > 7 { + &filename[..7] + } else { + &filename + }; + let created_at = parse_ticket_field(&content, "Created At"); + let short_date = format_created_at(&created_at); + + Some((title, owner, due, uuid_short.to_string(), short_date)) + }) + .collect(); + + items.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase())); + Ok(items) +}