Files
worklane/src/handlers.rs
T

415 lines
12 KiB
Rust

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<String>, 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 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) => 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: &[String],
acceptance: &[String],
plan: &[String],
tags: &[String],
due: &Option<String>,
owner: &Option<String>,
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\
- **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::<Vec<_>>()
.join("\n")
},
if plan.is_empty() {
"_No implementation plan provided._".to_string()
} else {
plan.iter()
.enumerate()
.map(|(i, s)| format!("{}. {}", i + 1, s))
.collect::<Vec<_>>()
.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<Vec<(String, String, String, String)>> {
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.",
color_text(&current_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(&current_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(&current_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(&current_status, "orange")
));
}
// 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 {}",
color_text(&title, "green"),
color_text(&current_status, "orange"),
color_text(target_status, "orange"),
);
Ok(())
}
pub fn cmd_comment(
ticket_id: &str,
body: &str,
owner: &Option<String>,
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 = 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("%Y-%m-%d %H:%M:%S")
);
fs::write(&filepath, comment_content)?;
println!("Comment added to '{}' ({})", title, filename);
Ok(())
}