use anyhow::{Result, anyhow}; use chrono::Local; use clap::Parser; use std::fs; use std::io::IsTerminal; use std::path::Path; mod command; 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 cmd_add( title: &str, description: &Option, acceptance: &[String], plan: &[String], tags: &[String], due: &Option, owner: &Option, start: &Path, ) -> Result<()> { 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 cmd_show(search: &str, worklane_dir: &Path) -> Result<()> { let (_status, title, content) = resolve_ticket(search, worklane_dir)?; println!("{}", title); println!("{}", "─".repeat(title.len())); println!("\n{}", content_trim_colored(&content)); 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 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 } fn main() -> Result<()> { let cli = Cli::parse(); let start = std::env::current_dir()?; match cli.command { Command::Init => cmd_init(&start), Command::Add { title, description, acceptance, plan, tags, due, owner, } => cmd_add( &title, &description, &acceptance, &plan, &tags, &due, &owner, &start, ), Command::Ls { status } => { let worklane_dir = find_worklane_dir(&start)?; cmd_ls(&status, &worklane_dir) } Command::Show { id } => { let worklane_dir = find_worklane_dir(&start)?; cmd_show(&id, &worklane_dir) } Command::Mv { ticket, status, force } => { cmd_mv(&ticket, &status, force, &start) } } }