Done only grows. It already holds more tickets than the other three columns
together, so a quarter of the width was going to the column least often read
while the ones being worked got squeezed for it.
Not a new opinion: `ls` already counts done in its summary and leaves it out of
the listing below. The board now does the same, and the footer carries the
count while the column is hidden, which is the board's version of that summary
line. It reads `d show done (17)` while hidden and `d hide done` while shown,
so the count only appears where a column heading is not already carrying it.
The modal footer names the key too, since it works with a ticket open.
Hiding is a change to what is drawn, never to what is read. `reload` still
scans the done directory and `digest` still watches it, so the count is right
and revealing the column needs no rescan.
`visible()` returns a prefix of the columns rather than a filter, which is what
keeps `column` and `offsets` valid as indices into either. It is derived from
where DONE actually sits rather than assuming the last slot, and a test pins
done as last: a status inserted after it would otherwise hide two columns in
silence. DONE is now a constant, since `ls` and the board are two readers of
the same rule.
Hiding the column under the selection moves the selection to the last drawn
column and closes an open detail view. Refreshing the modal onto whichever
ticket the selection landed on was the alternative, and it swaps what someone
is reading without saying so, which is how a person acts on the wrong ticket.
Showing done again is a no-op for the selection, since a column is appended
rather than inserted.
Three existing tests asserted a column heading with `screen.contains("done
(0)")` over the whole render, and the new footer holds that string whether the
column is drawn or not, so all three passed for the wrong reason the moment
done was hidden. They now assert against the top border row through a
`headings()` helper, with `footer()` beside it.
The choice is not remembered between runs: worklane has no config file, and one
flag is not a reason to start one.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
905 lines
29 KiB
Rust
905 lines
29 KiB
Rust
use anyhow::{Result, anyhow};
|
|
use chrono::Local;
|
|
use std::fs;
|
|
use std::io::{BufRead, IsTerminal, Write};
|
|
use std::path::Path;
|
|
|
|
use crate::command::{AddArgs, AppendArgs, CheckArgs, SetArgs};
|
|
use crate::install;
|
|
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>,
|
|
priority_filter: Option<u8>,
|
|
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()), Color::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<TicketItem>, level: Option<u8>) -> Vec<TicketItem> {
|
|
match level {
|
|
Some(level) => items
|
|
.into_iter()
|
|
.filter(|item| item.priority == Priority::Level(level))
|
|
.collect(),
|
|
None => items,
|
|
}
|
|
}
|
|
|
|
pub fn cmd_add(args: &AddArgs, start: &Path) -> Result<()> {
|
|
let AddArgs {
|
|
title,
|
|
description,
|
|
acceptance,
|
|
plan,
|
|
tags,
|
|
due,
|
|
owner,
|
|
priority,
|
|
} = args;
|
|
|
|
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."));
|
|
}
|
|
|
|
// Joined with a single newline, so an empty value is how a caller spells a
|
|
// paragraph break and an all-blank description is no description at all.
|
|
let description = trim_blank_ends(description);
|
|
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::<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,
|
|
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(())
|
|
}
|
|
|
|
/// Public for the TUI's detail view, which shows the same comments `show` does.
|
|
pub 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().is_some_and(|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.split_once("**Author**:"))
|
|
.map(|(_, value)| value)
|
|
.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.split_once("**Time**:"))
|
|
.map(|(_, value)| value)
|
|
.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<String> {
|
|
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, Color::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(())
|
|
}
|
|
|
|
/// Write `content` over `path`, without ever leaving half a file behind.
|
|
///
|
|
/// Staged in a temp file and renamed into place, because `fs::write` truncates before
|
|
/// it writes and a partial write would corrupt the ticket. The temp sits under
|
|
/// `.worklane/` rather than beside the ticket, so a leftover from a hard kill is
|
|
/// invisible to ticket lookup and to the listing instead of showing up as a stray
|
|
/// untitled ticket.
|
|
fn write_then_replace(
|
|
worklane_dir: &Path,
|
|
path: &Path,
|
|
filename: &str,
|
|
content: &str,
|
|
title: &str,
|
|
) -> Result<()> {
|
|
let temp = worklane_dir.join(format!(".wl-{}.tmp", filename));
|
|
|
|
if let Err(e) = fs::write(&temp, content) {
|
|
let _ = fs::remove_file(&temp);
|
|
return Err(anyhow!(
|
|
"Could not stage the update for ticket '{}' at {}: {}",
|
|
title,
|
|
temp.display(),
|
|
e
|
|
));
|
|
}
|
|
|
|
if let Err(e) = fs::rename(&temp, path) {
|
|
let _ = fs::remove_file(&temp);
|
|
return Err(anyhow!(
|
|
"Could not write ticket '{}' at {}: {}",
|
|
title,
|
|
path.display(),
|
|
e
|
|
));
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// The ticket file in `dir` carrying `uuid`.
|
|
///
|
|
/// Matched on the uuid, not the title. Titles are not unique, `add` allows duplicates
|
|
/// on purpose, so a title scan could land on a different ticket than the one that was
|
|
/// resolved: `mv <uuid-of-second>` moved the first ticket sharing its title.
|
|
fn find_ticket_file(dir: &Path, uuid: &str, title: &str) -> Result<String> {
|
|
if uuid.trim().is_empty() || is_unknown_value(uuid) {
|
|
return Err(anyhow!(
|
|
"Ticket '{}' has no ID field, so its file cannot be located",
|
|
title
|
|
));
|
|
}
|
|
|
|
for entry in fs::read_dir(dir)? {
|
|
let entry = entry?;
|
|
let path = entry.path();
|
|
if !path.extension().is_some_and(|e| e == "md") {
|
|
continue;
|
|
}
|
|
|
|
let name = match path.file_name() {
|
|
Some(name) => name.to_string_lossy().to_string(),
|
|
None => continue,
|
|
};
|
|
|
|
if name.starts_with(uuid) {
|
|
return Ok(name);
|
|
}
|
|
}
|
|
|
|
Err(anyhow!(
|
|
"Could not find the file for ticket '{}' in {}",
|
|
title,
|
|
dir.display()
|
|
))
|
|
}
|
|
|
|
/// Put `content` in `filename` and move it from `from` to `to`, without ever
|
|
/// leaving the ticket in two status directories or with half a file in it.
|
|
///
|
|
/// Two atomic steps, in this order. The content is staged in a temp file and
|
|
/// renamed over the source, so a partial write is thrown away and the original is
|
|
/// untouched. Only then is the file renamed into the target directory.
|
|
///
|
|
/// The old order renamed first and wrote second, so a failure in between left the
|
|
/// ticket sitting in its new directory still claiming the old status. Writing
|
|
/// straight to the target and deleting the source afterwards would instead have it
|
|
/// in both directories at once. Neither happens here. The worst case is a ticket
|
|
/// still in its old directory carrying a Status field one move ahead, which the
|
|
/// next `mv` corrects, since the directory is what decides the current status.
|
|
fn move_ticket_file(
|
|
worklane_dir: &Path,
|
|
from: &Path,
|
|
to: &Path,
|
|
filename: &str,
|
|
content: &str,
|
|
title: &str,
|
|
) -> Result<()> {
|
|
let source = from.join(filename);
|
|
let dest = to.join(filename);
|
|
|
|
write_then_replace(worklane_dir, &source, filename, content, title)?;
|
|
|
|
// The content is correct and in one place by now, so a failure here leaves the
|
|
// ticket where it started rather than half moved.
|
|
fs::rename(&source, &dest).map_err(|e| {
|
|
anyhow!(
|
|
"Could not move ticket '{}' to {}: {}",
|
|
title,
|
|
dest.display(),
|
|
e
|
|
)
|
|
})
|
|
}
|
|
|
|
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, resolved) = 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, Color::Orange),
|
|
color_text(target_status, Color::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, Color::Orange)
|
|
);
|
|
return Ok(());
|
|
}
|
|
|
|
let current_path = worklane_dir.join(¤t_status);
|
|
let target_path = worklane_dir.join(target_status);
|
|
|
|
// Updated before the file is even located, so a ticket without a Status field is
|
|
// refused for that reason rather than for whatever the lookup notices first.
|
|
let content = set_status_field(&resolved, target_status, &title)?;
|
|
|
|
let found_filename =
|
|
find_ticket_file(¤t_path, &parse_ticket_field(&resolved, "ID"), &title)?;
|
|
|
|
move_ticket_file(
|
|
&worklane_dir,
|
|
¤t_path,
|
|
&target_path,
|
|
&found_filename,
|
|
&content,
|
|
&title,
|
|
)?;
|
|
|
|
println!(
|
|
"Moved ticket '{}' from {} to {}",
|
|
color_text(&title, Color::Green),
|
|
color_text(¤t_status, Color::Orange),
|
|
color_text(target_status, Color::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 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(())
|
|
}
|
|
|
|
/// The sections `set` and `append` can rewrite, paired with the flag that carries them.
|
|
///
|
|
/// One list, so both commands walk the same table and a section added later needs no
|
|
/// change here.
|
|
fn section_args<'a>(
|
|
description: &'a [String],
|
|
acceptance: &'a [String],
|
|
plan: &'a [String],
|
|
) -> [(&'static Section, &'a [String]); 3] {
|
|
[
|
|
(&DESCRIPTION, description),
|
|
(&ACCEPTANCE, acceptance),
|
|
(&PLAN, plan),
|
|
]
|
|
}
|
|
|
|
/// Write the ticket back, renaming the file when a new title changes its slug.
|
|
///
|
|
/// The content goes down first and the rename second, the same order and for the same
|
|
/// reason as `mv`: a failure at the rename leaves a correct ticket under a stale name,
|
|
/// which lookup still finds by uuid or title, rather than a half-written one.
|
|
fn save_ticket(
|
|
worklane_dir: &Path,
|
|
status: &str,
|
|
uuid: &str,
|
|
title: &str,
|
|
new_title: Option<&String>,
|
|
content: &str,
|
|
) -> Result<()> {
|
|
let status_path = worklane_dir.join(status);
|
|
let filename = find_ticket_file(&status_path, uuid, title)?;
|
|
let path = status_path.join(&filename);
|
|
|
|
write_then_replace(worklane_dir, &path, &filename, content, title)?;
|
|
|
|
// The uuid is kept, so the new name cannot collide with another ticket, and an
|
|
// unchanged slug means there is nothing to rename.
|
|
if let Some(new_title) = new_title {
|
|
let renamed = format!("{}_{}.md", uuid, slug(new_title));
|
|
if renamed != filename {
|
|
let destination = status_path.join(&renamed);
|
|
fs::rename(&path, &destination).map_err(|e| {
|
|
anyhow!(
|
|
"Ticket '{}' was updated but could not be renamed to {}: {}",
|
|
title,
|
|
destination.display(),
|
|
e
|
|
)
|
|
})?;
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn report(fields: &[&str], title: &str, verb: &str) {
|
|
if fields.is_empty() {
|
|
println!("No changes to '{}'", color_text(title, Color::Green));
|
|
return;
|
|
}
|
|
|
|
println!(
|
|
"{} {} on '{}'",
|
|
verb,
|
|
fields.join(", "),
|
|
color_text(title, Color::Green)
|
|
);
|
|
}
|
|
|
|
pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
|
|
let worklane_dir = find_worklane_dir(start)?;
|
|
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
|
|
let uuid = parse_ticket_field(&original, "ID");
|
|
|
|
let mut content = original.clone();
|
|
let mut changed: Vec<&str> = Vec::new();
|
|
|
|
// Each edit is compared against the content going in, so a field set to the value
|
|
// it already holds is reported as unchanged rather than claimed as an update.
|
|
let mut apply = |content: &mut String, field: &'static str, next: String| {
|
|
if *content != next {
|
|
content.clone_from(&next);
|
|
changed.push(field);
|
|
}
|
|
};
|
|
|
|
if let Some(new_title) = &args.title {
|
|
let next = set_title(&content, new_title)?;
|
|
apply(&mut content, "title", next);
|
|
}
|
|
|
|
for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) {
|
|
if values.is_empty() {
|
|
continue;
|
|
}
|
|
|
|
let items = section.normalise(values);
|
|
if items.is_empty() {
|
|
return Err(anyhow!(
|
|
"An empty {} is not a way to clear the section, and clearing is not supported yet",
|
|
section.label
|
|
));
|
|
}
|
|
|
|
let next = set_section_body(&content, section, &items)?;
|
|
apply(&mut content, section.label, next);
|
|
}
|
|
|
|
if !args.tags.is_empty() {
|
|
let next = set_metadata_field(&content, "Tags", &args.tags.join(", "), &title)?;
|
|
apply(&mut content, "tags", next);
|
|
}
|
|
|
|
if let Some(due) = &args.due {
|
|
let next = set_metadata_field(&content, "Due", due, &title)?;
|
|
apply(&mut content, "due", next);
|
|
}
|
|
|
|
if let Some(priority) = args.priority {
|
|
let next = set_metadata_field(&content, "Priority", &priority.to_string(), &title)?;
|
|
apply(&mut content, "priority", next);
|
|
}
|
|
|
|
if changed.is_empty() {
|
|
report(&changed, &title, "Updated");
|
|
return Ok(());
|
|
}
|
|
|
|
let renamed = changed.contains(&"title").then_some(()).and(args.title.as_ref());
|
|
save_ticket(&worklane_dir, &status, &uuid, &title, renamed, &content)?;
|
|
|
|
let shown = args.title.clone().unwrap_or(title);
|
|
report(&changed, &shown, "Updated");
|
|
Ok(())
|
|
}
|
|
|
|
pub fn cmd_append(args: &AppendArgs, start: &Path) -> Result<()> {
|
|
let worklane_dir = find_worklane_dir(start)?;
|
|
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
|
|
let uuid = parse_ticket_field(&original, "ID");
|
|
|
|
let mut content = original.clone();
|
|
let mut changed: Vec<&str> = Vec::new();
|
|
|
|
for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) {
|
|
if values.is_empty() {
|
|
continue;
|
|
}
|
|
|
|
let items = section.normalise(values);
|
|
if items.is_empty() {
|
|
return Err(anyhow!(
|
|
"Nothing to append to the {}: every value given was blank",
|
|
section.label
|
|
));
|
|
}
|
|
|
|
content = append_section_body(&content, section, &items)?;
|
|
changed.push(section.label);
|
|
}
|
|
|
|
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
|
|
|
|
report(&changed, &title, "Appended to");
|
|
Ok(())
|
|
}
|
|
|
|
/// Which criterion to act on, asked for when the caller did not say.
|
|
///
|
|
/// A terminal gets the list and a prompt. Anything else gets the same list as an
|
|
/// error, which is what `resolve_ticket` does for an ambiguous match and for the same
|
|
/// reason: the opencode wrapper throws on the exit code and keeps stderr, so a list
|
|
/// printed to stdout would be discarded and an agent would learn nothing. Prompting
|
|
/// regardless would leave it blocked on a stdin that never closes.
|
|
fn ask_which_criterion(criteria: &[Criterion], title: &str) -> Result<usize> {
|
|
let listing = criteria_list(criteria);
|
|
|
|
if !std::io::stdin().is_terminal() {
|
|
return Err(anyhow!(
|
|
"Which criterion of '{}'?\n{}\n\nRe-run with the number, or a substring of the text.",
|
|
title,
|
|
listing
|
|
));
|
|
}
|
|
|
|
println!("Acceptance criteria of '{}':", color_text(title, Color::Green));
|
|
println!("{}", listing);
|
|
// Either form, since find_criteria takes both.
|
|
print!("Number or text: ");
|
|
std::io::stdout().flush()?;
|
|
|
|
let mut answer = String::new();
|
|
std::io::stdin().lock().read_line(&mut answer)?;
|
|
|
|
// An empty needle matches every criterion, so it would otherwise be reported as
|
|
// ambiguous rather than as nothing having been chosen.
|
|
if answer.trim().is_empty() {
|
|
return Err(anyhow!("No criterion chosen"));
|
|
}
|
|
|
|
let chosen = find_criteria(criteria, &answer);
|
|
match chosen.len() {
|
|
1 => Ok(chosen[0]),
|
|
0 => Err(anyhow!(
|
|
"'{}' matches none of the {} criteria",
|
|
answer.trim(),
|
|
criteria.len()
|
|
)),
|
|
_ => Err(anyhow!(
|
|
"'{}' matches more than one criterion, use the number",
|
|
answer.trim()
|
|
)),
|
|
}
|
|
}
|
|
|
|
pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path) -> Result<()> {
|
|
let worklane_dir = find_worklane_dir(start)?;
|
|
let (status, title, content) = resolve_ticket(&args.ticket, &worklane_dir)?;
|
|
|
|
let criteria = criteria(&content);
|
|
if criteria.is_empty() {
|
|
return Err(anyhow!("Ticket '{}' has no acceptance criteria", title));
|
|
}
|
|
|
|
let chosen = match &args.criterion {
|
|
None => ask_which_criterion(&criteria, &title)?,
|
|
Some(search) => {
|
|
let found = find_criteria(&criteria, search);
|
|
match found.len() {
|
|
1 => found[0],
|
|
0 if is_index(search) => {
|
|
return Err(anyhow!(
|
|
"'{}' is not one of the {} criteria of '{}':\n{}",
|
|
search.trim(),
|
|
criteria.len(),
|
|
title,
|
|
criteria_list(&criteria)
|
|
));
|
|
}
|
|
0 => {
|
|
return Err(anyhow!(
|
|
"No criterion of '{}' matches '{}'. Its criteria are:\n{}",
|
|
title,
|
|
search,
|
|
criteria_list(&criteria)
|
|
));
|
|
}
|
|
_ => {
|
|
return Err(anyhow!(
|
|
"'{}' matches {} criteria of '{}':\n{}\n\nUse the number instead.",
|
|
search,
|
|
found.len(),
|
|
title,
|
|
numbered_criteria(&criteria, &found)
|
|
));
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
let criterion = &criteria[chosen];
|
|
let verb = if checked { "checked" } else { "unchecked" };
|
|
|
|
if criterion.checked == checked {
|
|
println!(
|
|
"Already {}: {}",
|
|
verb,
|
|
color_text(&criterion.text, Color::Green)
|
|
);
|
|
return Ok(());
|
|
}
|
|
|
|
let updated = set_criterion(&content, criterion.line, checked);
|
|
let uuid = parse_ticket_field(&content, "ID");
|
|
save_ticket(&worklane_dir, &status, &uuid, &title, None, &updated)?;
|
|
|
|
println!(
|
|
"{} {}: {}",
|
|
if checked { "Checked" } else { "Unchecked" },
|
|
chosen + 1,
|
|
color_text(&criterion.text, Color::Green)
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
/// Install the agent skill, or print it so a modified copy can be diffed.
|
|
///
|
|
/// No board is looked for. The document is what teaches an agent worklane, so needing
|
|
/// a `.worklane` to install it would put it out of reach exactly when it is wanted.
|
|
pub fn cmd_install_skill(force: bool, print: bool) -> Result<()> {
|
|
if print {
|
|
print!("{}", install::SKILL.content);
|
|
return Ok(());
|
|
}
|
|
|
|
let root = install::skills_root()?;
|
|
match install::SKILL.install(&root, force)? {
|
|
install::Outcome::Written(path) => {
|
|
println!("Installed the worklane {} to: {}", install::SKILL.what, path.display());
|
|
println!("Claude Code and opencode pick it up on their next session");
|
|
}
|
|
install::Outcome::Unchanged(path) => {
|
|
println!("Already up to date: {}", path.display());
|
|
}
|
|
install::Outcome::Refused(path) => {
|
|
println!("Differs from the version in this binary: {}", path.display());
|
|
println!(
|
|
"Compare with `worklane install-skill --print`, or overwrite with --force"
|
|
);
|
|
}
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|