Layout only, no behaviour and no wording. 161 hunks across 22 files, 98 of them rustfmt joining a call or a message onto the one line it fits on. The config it formats to, and how its four numbers were arrived at, is the commit before this one. Separate so that it is reviewable by not being read: nothing here is a decision, and every decision is next door. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1416 lines
50 KiB
Rust
1416 lines
50 KiB
Rust
use anyhow::{Result, anyhow};
|
|
use chrono::Local;
|
|
use std::fs;
|
|
use std::io::{BufRead, IsTerminal, Write};
|
|
use std::path::Path;
|
|
|
|
use crate::campaign::*;
|
|
use crate::command::{
|
|
AddArgs, AppendArgs, CampaignAddArgs, CheckArgs, ChownArgs, LsArgs, RelateArgs, 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)?;
|
|
|
|
for folder in status_dirs() {
|
|
fs::create_dir_all(worklane_dir.join(folder))?;
|
|
}
|
|
|
|
// Beside the status directories, not among them: a campaign has no status. Created
|
|
// here for a new board, and on demand by `campaign add` for a board that predates
|
|
// campaigns, which is why `status_dirs()` is untouched.
|
|
fs::create_dir_all(campaigns_dir(&worklane_dir))?;
|
|
|
|
println!("Initialized worklane in: {}", worklane_dir.display());
|
|
Ok(())
|
|
}
|
|
|
|
pub fn cmd_ls(args: &LsArgs, worklane_dir: &Path) -> Result<()> {
|
|
// Resolved before anything is read, so an unknown campaign is refused rather than
|
|
// silently listing nothing, and the name is available for the heading. Ahead of the
|
|
// `--ids` branch too: a completion that quietly listed the whole board because the
|
|
// campaign was misspelled would be worse than one that printed nothing.
|
|
let campaign = match &args.campaign {
|
|
Some(search) => Some(resolve_campaign(search, worklane_dir)?),
|
|
None => None,
|
|
};
|
|
let uuid = campaign.as_ref().map(|campaign| campaign.uuid.as_str());
|
|
let tag = args.tag.as_deref();
|
|
let priority_filter = args.priority;
|
|
|
|
if args.ids {
|
|
return list_ids(args.status, priority_filter, uuid, tag, worklane_dir);
|
|
}
|
|
|
|
if let Some(campaign) = &campaign {
|
|
println!(
|
|
"Members of campaign ({}) {}\n",
|
|
color_text(short_id(&campaign.uuid), Color::Red),
|
|
color_text(&campaign.title, Color::Green),
|
|
);
|
|
}
|
|
|
|
if let Some(status) = args.status {
|
|
let status = status.as_str();
|
|
let status_path = worklane_dir.join(status);
|
|
if !status_path.exists() {
|
|
// The status itself is clap's to reject now, so reaching here means the
|
|
// board is missing a directory it should have rather than that the name was
|
|
// mistyped. `init` will not repair it: it leaves an existing `.worklane`
|
|
// alone.
|
|
return Err(anyhow!(
|
|
"No '{}' directory in {}. Every board has all four; creating it is enough.",
|
|
status,
|
|
worklane_dir.display()
|
|
));
|
|
}
|
|
|
|
let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid, tag);
|
|
|
|
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 = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid, tag);
|
|
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) => filtered(items, priority_filter, uuid, tag),
|
|
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(())
|
|
}
|
|
|
|
/// The machine-readable listing: one ticket per line, its short id then its title,
|
|
/// separated by a tab and unstyled.
|
|
///
|
|
/// Two fields rather than the id alone because both readers want both. Fish takes what
|
|
/// follows the tab as the description, which is what makes `worklane show <TAB>` a list
|
|
/// of titles rather than of hex, and a script takes the id back out with `cut -f1`. The
|
|
/// id is the same seven characters the listing prints, which is what a ticket is
|
|
/// addressed by.
|
|
///
|
|
/// Every status, done included, where the listing above leaves done out. A completion has
|
|
/// to be able to name a finished ticket, since `show` and `comment` are most often
|
|
/// pointed at one, and the status positional still narrows it.
|
|
///
|
|
/// A missing status directory is skipped rather than refused, which is the one place this
|
|
/// parts company with the listing. The caller is usually a shell filling in a candidate
|
|
/// list, and an error printed over the prompt is worse there than no candidates.
|
|
fn list_ids(
|
|
status: Option<Status>,
|
|
level: Option<u8>,
|
|
campaign: Option<&str>,
|
|
tag: Option<&str>,
|
|
worklane_dir: &Path,
|
|
) -> Result<()> {
|
|
let statuses = match status {
|
|
Some(status) => vec![status.as_str()],
|
|
None => status_dirs(),
|
|
};
|
|
|
|
for status in statuses {
|
|
let status_path = worklane_dir.join(status);
|
|
if !status_path.exists() {
|
|
continue;
|
|
}
|
|
for item in filtered(collect_ticket_items(&status_path)?, level, campaign, tag) {
|
|
println!("{}\t{}", item.id, item.title);
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// The listing filters in one call, so the three places `ls` collects a column cannot
|
|
/// end up applying a different set of them.
|
|
///
|
|
/// Every filter is `Option`, and none asked for is everything kept, which is what makes
|
|
/// them compose in any combination without a rule per pair.
|
|
fn filtered(
|
|
items: Vec<TicketItem>,
|
|
level: Option<u8>,
|
|
campaign: Option<&str>,
|
|
tag: Option<&str>,
|
|
) -> Vec<TicketItem> {
|
|
filter_by_tag(filter_by_campaign(filter_by_priority(items, level), campaign), tag)
|
|
}
|
|
|
|
/// Keep only the tickets carrying `tag`, or everything when none was asked for.
|
|
///
|
|
/// Matched against the whole values `parse_tags` split out of the field rather than as a
|
|
/// substring of it, so `--tag bug` is not answered by a ticket tagged `bugfix`, and a
|
|
/// ticket with no tags matches nothing at all.
|
|
///
|
|
/// Case sensitive, the opinion the field already takes everywhere else: `tag_color`
|
|
/// draws `Bug` and `bug` in two colours because they are two tags, and a filter that
|
|
/// folded them would list tickets carrying a tag nobody asked for.
|
|
fn filter_by_tag(items: Vec<TicketItem>, tag: Option<&str>) -> Vec<TicketItem> {
|
|
match tag {
|
|
Some(tag) => items
|
|
.into_iter()
|
|
.filter(|item| item.tags.iter().any(|carried| carried == tag))
|
|
.collect(),
|
|
None => items,
|
|
}
|
|
}
|
|
|
|
/// Keep only the members of `campaign`, or everything when none was asked for.
|
|
fn filter_by_campaign(items: Vec<TicketItem>, campaign: Option<&str>) -> Vec<TicketItem> {
|
|
match campaign {
|
|
Some(uuid) => items
|
|
.into_iter()
|
|
.filter(|item| item.campaign.as_deref() == Some(uuid))
|
|
.collect(),
|
|
None => items,
|
|
}
|
|
}
|
|
|
|
/// 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);
|
|
|
|
// 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');
|
|
|
|
// No existence check ahead of this. The name carries a uuid generated a few lines
|
|
// up, so a collision is not something that happens, and the branch that used to
|
|
// guard the write claimed the *title* was taken, which is the opposite of what the
|
|
// format allows: duplicate titles are supported and `add_allows_duplicate_titles`
|
|
// pins it. `cmd_campaign_add` deliberately does not carry it either. What is left is
|
|
// the write's own failure, named with the ticket and the path the way the other
|
|
// writes in the tree name them.
|
|
fs::write(&filepath, body).map_err(|e| {
|
|
anyhow!("Could not write ticket '{}' at {}: {}", title, filepath.display(), e)
|
|
})?;
|
|
|
|
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");
|
|
// Read before anything is printed, so a board that cannot be read fails instead of
|
|
// half printing a ticket.
|
|
let resolved = resolved_for(&content, worklane_dir, should_use_colors())?;
|
|
|
|
// 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, &resolved));
|
|
|
|
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))
|
|
}
|
|
|
|
/// Refuse a move while a ticket it is `blocked by` is not done.
|
|
///
|
|
/// Every move, not only the one into committed: an open blocker is a reason not to
|
|
/// start and a reason not to finish, and one rule is easier to hold than a table of
|
|
/// which transitions care. Called before anything is written, so a refusal leaves no
|
|
/// rename, no rewritten field and no half moved ticket.
|
|
///
|
|
/// A target the board does not have warns and allows the move. Refusing there would
|
|
/// wedge the ticket behind a bookkeeping fault with no way out but `--force`, and a
|
|
/// dangling uuid is not a dependency.
|
|
fn check_blockers(worklane_dir: &Path, content: &str, title: &str) -> Result<()> {
|
|
let blockers: Vec<Relation> = parse_relations(content, title)?
|
|
.into_iter()
|
|
.filter(|relation| relation.kind == RelationKind::BlockedBy)
|
|
.collect();
|
|
|
|
if blockers.is_empty() {
|
|
return Ok(());
|
|
}
|
|
|
|
let index = RelationIndex::load(worklane_dir)?;
|
|
let mut open: Vec<String> = Vec::new();
|
|
|
|
for blocker in &blockers {
|
|
match index.get(&blocker.target) {
|
|
Some(target) if target.status == DONE => {}
|
|
Some(target) => open.push(format!(
|
|
" ({}) {} [{}]",
|
|
color_text(short_id(&target.uuid), Color::Red),
|
|
target.title,
|
|
color_text(&target.status, Color::Orange),
|
|
)),
|
|
None => eprintln!(
|
|
"Warning: ticket '{}' is blocked by {}, which is not on the board.",
|
|
title,
|
|
short_id(&blocker.target),
|
|
),
|
|
}
|
|
}
|
|
|
|
if open.is_empty() {
|
|
return Ok(());
|
|
}
|
|
|
|
// Every open blocker, not the first: a ticket waiting on three of them is not
|
|
// unblocked by clearing the one the message happened to name.
|
|
Err(anyhow!(
|
|
"Cannot move '{}' while it is blocked by:\n{}\nUse --force (-f) to move it anyway.",
|
|
color_text(title, Color::Green),
|
|
open.join("\n"),
|
|
))
|
|
}
|
|
|
|
/// A status is a [`Status`] rather than a string, so an unknown one is clap's to refuse
|
|
/// and nothing here has to check. What is left is the order of the flow, which is
|
|
/// `Status::ALL`.
|
|
pub fn cmd_mv(ticket_id: &str, target: Status, force: bool, start: &Path) -> Result<()> {
|
|
let target_status = target.as_str();
|
|
|
|
let worklane_dir = find_worklane_dir(start)?;
|
|
let (current_status, title, resolved) = resolve_ticket(ticket_id, &worklane_dir)?;
|
|
|
|
let current_idx = Status::ALL
|
|
.iter()
|
|
.position(|status| status.as_str() == current_status)
|
|
.unwrap();
|
|
let target_idx = Status::ALL.iter().position(|status| *status == target).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(());
|
|
}
|
|
|
|
// After the no-op above, so a ticket is never refused for a move it is not making,
|
|
// and behind `force`, which is where the other two overrides of a rule the board
|
|
// keeps true already live.
|
|
if !force {
|
|
check_blockers(&worklane_dir, &resolved, &title)?;
|
|
}
|
|
|
|
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)?;
|
|
|
|
// Behind every refusal above, so a move that does not happen writes no stamp, and
|
|
// spliced in here rather than after the rename so it travels with the same
|
|
// crash-safe write the Status field does.
|
|
let content = set_status_stamp(
|
|
&content,
|
|
target,
|
|
&Local::now().format(TIMESTAMP_FORMAT).to_string(),
|
|
&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(())
|
|
}
|
|
|
|
/// Take an edit, or record that it changed nothing.
|
|
///
|
|
/// 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. That is also
|
|
/// what makes clearing an already unset field free: the sentinel it writes is the one
|
|
/// already there, so the strings match and nothing is written.
|
|
fn apply(content: &mut String, changed: &mut Vec<&'static str>, field: &'static str, next: String) {
|
|
if *content != next {
|
|
content.clone_from(&next);
|
|
changed.push(field);
|
|
}
|
|
}
|
|
|
|
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<()> {
|
|
if let Some(field) = args.contested() {
|
|
let name = field.name();
|
|
return Err(anyhow!(
|
|
"--{name} and --clear {name} contradict each other, so nothing was written"
|
|
));
|
|
}
|
|
|
|
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();
|
|
let mut cleared: Vec<&str> = Vec::new();
|
|
|
|
if let Some(new_title) = &args.title {
|
|
let next = set_title(&content, new_title)?;
|
|
apply(&mut content, &mut changed, "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 value is a paragraph break, not a way to empty the {}: use --clear {}",
|
|
section.label,
|
|
section.clear.map_or("", Clearable::name)
|
|
));
|
|
}
|
|
|
|
let next = set_section_body(&content, section, &items)?;
|
|
apply(&mut content, &mut changed, section.label, next);
|
|
}
|
|
|
|
if !args.tags.is_empty() {
|
|
let next = set_metadata_field(&content, "Tags", &args.tags.join(", "), &title)?;
|
|
apply(&mut content, &mut changed, "tags", next);
|
|
}
|
|
|
|
if let Some(due) = &args.due {
|
|
let next = set_metadata_field(&content, "Due", due, &title)?;
|
|
apply(&mut content, &mut changed, "due", next);
|
|
}
|
|
|
|
if let Some(priority) = args.priority {
|
|
let next = set_metadata_field(&content, "Priority", &priority.to_string(), &title)?;
|
|
apply(&mut content, &mut changed, "priority", next);
|
|
}
|
|
|
|
// Last, and into a list of their own. No field can be in both, since `contested`
|
|
// refused that above, so the order is free and the report is what decides it: a
|
|
// caller is told what was replaced and what was emptied in those words.
|
|
for field in &args.clear {
|
|
let next = match field.unset() {
|
|
Unset::Field { field, sentinel } => {
|
|
set_metadata_field(&content, field, sentinel, &title)?
|
|
}
|
|
Unset::Section(section) => clear_section_body(&content, section)?,
|
|
};
|
|
apply(&mut content, &mut cleared, field.label(), next);
|
|
}
|
|
|
|
if changed.is_empty() && cleared.is_empty() {
|
|
report(&[], &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);
|
|
if !changed.is_empty() {
|
|
report(&changed, &shown, "Updated");
|
|
}
|
|
if !cleared.is_empty() {
|
|
report(&cleared, &shown, "Cleared");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Rewrite the Owner field, the only writer of it.
|
|
///
|
|
/// The user comes first at the call site, after Unix `chown`, and the reasoning for
|
|
/// reversing the ticket-first order is on the `Chown` variant. A swapped call is left
|
|
/// to resolution: nothing here inspects `user` to see whether it also names a ticket,
|
|
/// since the check would only fire on the case resolution already refuses and would
|
|
/// stay silent on the one it cannot, a ticket whose title is the username.
|
|
///
|
|
/// No-op detection compares the whole file, the way `set` does, so an owner set to the
|
|
/// value it already holds is reported unchanged and nothing is written. The same
|
|
/// comparison is what makes clearing an already unset owner free.
|
|
///
|
|
/// **Clearing writes [`NOT_SET`], not the git user.** `add` falls back to the git user
|
|
/// for a ticket it is filing, which is a default for something new; an owner taken away
|
|
/// says nobody owns this, and putting the person running the command there instead would
|
|
/// hand them a ticket they were giving up.
|
|
pub fn cmd_chown(args: &ChownArgs, start: &Path) -> Result<()> {
|
|
let (ticket_id, user) = args.target().ok_or_else(|| {
|
|
anyhow!("chown takes a user and a ticket, or --clear with the ticket alone")
|
|
})?;
|
|
|
|
let worklane_dir = find_worklane_dir(start)?;
|
|
let (status, title, original) = resolve_ticket(ticket_id, &worklane_dir)?;
|
|
let uuid = parse_ticket_field(&original, "ID");
|
|
|
|
let content = set_metadata_field(&original, "Owner", user.unwrap_or(NOT_SET), &title)?;
|
|
|
|
if content == original {
|
|
report(&[], &title, "Updated");
|
|
return Ok(());
|
|
}
|
|
|
|
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
|
|
|
|
let verb = match user {
|
|
Some(_) => "Updated",
|
|
None => "Cleared",
|
|
};
|
|
report(&["owner"], &title, verb);
|
|
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(())
|
|
}
|
|
|
|
/// Record a relation from one ticket to another.
|
|
///
|
|
/// One side is written and the inverse is derived wherever it is shown. `blocked by`
|
|
/// goes on the gated ticket rather than `blocks` on the blocker: the gated ticket is the
|
|
/// one whose move is refused and whose author knows about the dependency. `relates to`
|
|
/// is symmetric, so it is written once, on whichever end the caller ran it from.
|
|
///
|
|
/// The kinds are a flag each rather than a `--kind` value, so an unknown kind is a
|
|
/// usage error at the door instead of a line written into the file and refused on the
|
|
/// way back out.
|
|
pub fn cmd_relate(args: &RelateArgs, 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 existing = parse_relations(&original, &title)?;
|
|
|
|
// Every target resolved and every refusal raised before a byte is written, so a
|
|
// call naming one good ticket and one bad one records neither.
|
|
let mut items: Vec<String> = Vec::new();
|
|
let mut changed: Vec<&str> = Vec::new();
|
|
|
|
for (kind, targets) in args.requested() {
|
|
for search in targets {
|
|
let (_target_status, target_title, target) = resolve_ticket(search, &worklane_dir)?;
|
|
let target_uuid = parse_ticket_field(&target, "ID");
|
|
|
|
if target_uuid.trim().is_empty() || is_unknown_value(&target_uuid) {
|
|
return Err(anyhow!(
|
|
"Ticket '{}' has no ID field, so nothing can point at it",
|
|
target_title
|
|
));
|
|
}
|
|
|
|
if target_uuid == uuid {
|
|
return Err(anyhow!(
|
|
"A ticket cannot relate to itself, and '{}' is the ticket being edited",
|
|
title
|
|
));
|
|
}
|
|
|
|
let relation = Relation { kind, target: target_uuid };
|
|
|
|
// Already held, either in the file or earlier in this call. Recording it
|
|
// twice would read as two dependencies on one ticket.
|
|
if existing.contains(&relation) || items.contains(&relation.item()) {
|
|
continue;
|
|
}
|
|
|
|
items.push(relation.item());
|
|
if !changed.contains(&kind.label()) {
|
|
changed.push(kind.label());
|
|
}
|
|
}
|
|
}
|
|
|
|
if items.is_empty() {
|
|
report(&[], &title, "Recorded");
|
|
return Ok(());
|
|
}
|
|
|
|
let content = append_section_body(&ensure_section(&original, &RELATIONS), &RELATIONS, &items)?;
|
|
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
|
|
|
|
report(&changed, &title, "Recorded");
|
|
Ok(())
|
|
}
|
|
|
|
// ------------------------------------------------------------------- campaigns --
|
|
|
|
/// File a new campaign.
|
|
///
|
|
/// Written through `write_then_replace` rather than `fs::write`, so a failure leaves no
|
|
/// half-written campaign behind. `cmd_add` predates that primitive and still uses the
|
|
/// plain write; the difference is noted on the ticket rather than fixed here.
|
|
pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path) -> Result<()> {
|
|
let CampaignAddArgs { title, description, owner } = args;
|
|
|
|
let worklane_dir = find_worklane_dir(start)?;
|
|
let dir = ensure_campaigns_dir(&worklane_dir)?;
|
|
|
|
let owner = match owner {
|
|
Some(owner) => Some(owner.clone()),
|
|
None => get_git_user(),
|
|
};
|
|
|
|
let id = uuid::Uuid::new_v4();
|
|
let filename = format!("{}_{}.md", id, slug(title));
|
|
let path = dir.join(&filename);
|
|
|
|
let body = campaign_body(
|
|
title,
|
|
description,
|
|
&id,
|
|
owner.as_deref(),
|
|
&Local::now().format(TIMESTAMP_FORMAT).to_string(),
|
|
);
|
|
|
|
write_then_replace(&worklane_dir, &path, &filename, &body, title)?;
|
|
|
|
println!("Created campaign: {}", filename);
|
|
Ok(())
|
|
}
|
|
|
|
/// List the campaigns with how far each has got.
|
|
///
|
|
/// The counts come from one pass over the status directories per campaign. That is a
|
|
/// scan per row rather than one scan reused, and it is deliberate: the alternative is a
|
|
/// map from campaign uuid to counts built in a single walk, which is worth writing when
|
|
/// a board has enough campaigns to notice and is premature now.
|
|
pub fn cmd_campaign_ls(worklane_dir: &Path) -> Result<()> {
|
|
let index = CampaignIndex::load(worklane_dir)?;
|
|
|
|
if index.is_empty() {
|
|
println!("No campaigns yet. `worklane campaign add --title` files one.");
|
|
return Ok(());
|
|
}
|
|
|
|
let colored = should_use_colors();
|
|
println!("Campaigns:\n");
|
|
|
|
for campaign in index.iter() {
|
|
let standing = Standing::of(&members(worklane_dir, &campaign.uuid)?);
|
|
let state = match standing.state() {
|
|
Some(state) => format!(" [{}]", paint(state, Color::Orange, colored)),
|
|
None => String::new(),
|
|
};
|
|
|
|
println!(
|
|
" ({}) {} | {}{}",
|
|
paint(short_id(&campaign.uuid), Color::Red, colored),
|
|
campaign.title,
|
|
standing.label(),
|
|
state,
|
|
);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Show a campaign, then its members grouped by status.
|
|
///
|
|
/// Every status is shown, done included, unlike `ls`, which leaves done out of its
|
|
/// listing. A campaign's whole point is what is finished against what is left, so
|
|
/// hiding the finished half would hide the answer.
|
|
pub fn cmd_campaign_show(search: &str, worklane_dir: &Path) -> Result<()> {
|
|
let campaign = resolve_campaign(search, worklane_dir)?;
|
|
|
|
println!("{}", color_text(&campaign.title, Color::Green));
|
|
println!("{}", "─".repeat(campaign.title.chars().count()));
|
|
// No relations and no campaign of its own: a campaign is not a ticket, and neither
|
|
// belongs to one.
|
|
println!("\n{}", content_trim_colored(&campaign.content, &Resolved::default()));
|
|
|
|
let grouped = members(worklane_dir, &campaign.uuid)?;
|
|
let standing = Standing::of(&grouped);
|
|
|
|
println!("{}", color_text("Members", Color::Orange));
|
|
println!("{}", "─".repeat("Members".chars().count()));
|
|
println!("\n{}", standing.label());
|
|
|
|
for (status, items) in &grouped {
|
|
if items.is_empty() {
|
|
continue;
|
|
}
|
|
println!("\n{}", color_text(&format!("[{}]", status.to_uppercase()), Color::Orange));
|
|
display_ticket_items(items);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Put a ticket in a campaign, the only writer of the Campaign field.
|
|
///
|
|
/// The campaign is resolved first, so a call naming a good ticket and a bad campaign
|
|
/// writes nothing. A ticket names at most one campaign because the field is rewritten
|
|
/// rather than added to, so assigning a ticket that is already in one moves it.
|
|
///
|
|
/// No-op detection compares the whole file, the way `set` and `chown` do, so assigning
|
|
/// a ticket to the campaign it already names writes nothing.
|
|
pub fn cmd_assign(campaign_search: &str, ticket_id: &str, start: &Path) -> Result<()> {
|
|
let worklane_dir = find_worklane_dir(start)?;
|
|
let campaign = resolve_campaign(campaign_search, &worklane_dir)?;
|
|
let (status, title, original) = resolve_ticket(ticket_id, &worklane_dir)?;
|
|
let uuid = parse_ticket_field(&original, "ID");
|
|
|
|
let content = set_or_insert_metadata_field(&original, CAMPAIGN_FIELD, &campaign.uuid, &title)?;
|
|
|
|
if content == original {
|
|
println!(
|
|
"Ticket '{}' is already in campaign '{}'",
|
|
color_text(&title, Color::Green),
|
|
campaign.title,
|
|
);
|
|
return Ok(());
|
|
}
|
|
|
|
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
|
|
|
|
println!(
|
|
"Assigned '{}' to campaign '{}'",
|
|
color_text(&title, Color::Green),
|
|
campaign.title,
|
|
);
|
|
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()
|
|
)),
|
|
}
|
|
}
|
|
|
|
/// Every criterion the terms name, in the order `show` numbers them and without
|
|
/// repeats.
|
|
///
|
|
/// Resolved before a byte is written, and one bad term refuses the whole batch. A call
|
|
/// that ticked the terms it understood and then failed would leave the ticket
|
|
/// half-marked, with nothing in the file to say which half the caller meant, and the
|
|
/// obvious retry would be reading the ticket back to find out.
|
|
///
|
|
/// The offending term is named on its own rather than every failure at once: each
|
|
/// message carries the criteria listing, so a batch of them would repeat the list per
|
|
/// bad term and bury the first one.
|
|
fn resolve_criteria(criteria: &[Criterion], terms: &[String], title: &str) -> Result<Vec<usize>> {
|
|
let mut chosen: Vec<usize> = Vec::new();
|
|
|
|
for term in terms {
|
|
if is_all_criteria(term) {
|
|
chosen.extend(0..criteria.len());
|
|
continue;
|
|
}
|
|
|
|
let found = find_criteria(criteria, term);
|
|
match found.len() {
|
|
1 => chosen.push(found[0]),
|
|
0 if is_index(term) => {
|
|
return Err(anyhow!(
|
|
"'{}' is not one of the {} criteria of '{}':\n{}",
|
|
term.trim(),
|
|
criteria.len(),
|
|
title,
|
|
criteria_list(criteria)
|
|
));
|
|
}
|
|
0 => {
|
|
return Err(anyhow!(
|
|
"No criterion of '{}' matches '{}'. Its criteria are:\n{}",
|
|
title,
|
|
term,
|
|
criteria_list(criteria)
|
|
));
|
|
}
|
|
_ => {
|
|
return Err(anyhow!(
|
|
"'{}' matches {} criteria of '{}':\n{}\n\nUse the number instead.",
|
|
term,
|
|
found.len(),
|
|
title,
|
|
numbered_criteria(criteria, &found)
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
// Sorted so the report reads in the order `show` numbers the criteria whatever
|
|
// order the terms arrived in, and deduped so a criterion named twice, or by both
|
|
// `all` and its own number, is reported once.
|
|
chosen.sort_unstable();
|
|
chosen.dedup();
|
|
Ok(chosen)
|
|
}
|
|
|
|
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.criteria.as_slice() {
|
|
[] => vec![ask_which_criterion(&criteria, &title)?],
|
|
terms => resolve_criteria(&criteria, terms, &title)?,
|
|
};
|
|
|
|
// Only the criteria that are not already in the target state, so a batch where
|
|
// every box is already ticked writes nothing, the way a single one always has.
|
|
let changing: Vec<usize> = chosen
|
|
.iter()
|
|
.copied()
|
|
.filter(|offset| criteria[*offset].checked != checked)
|
|
.collect();
|
|
|
|
if !changing.is_empty() {
|
|
let lines: Vec<usize> = changing.iter().map(|offset| criteria[*offset].line).collect();
|
|
let updated = set_criteria(&content, &lines, checked);
|
|
let uuid = parse_ticket_field(&content, "ID");
|
|
save_ticket(&worklane_dir, &status, &uuid, &title, None, &updated)?;
|
|
}
|
|
|
|
// Reported after the write, one line per criterion the call named, so nothing
|
|
// claims a mark the file does not carry.
|
|
let verb = if checked { "checked" } else { "unchecked" };
|
|
let past = if checked { "Checked" } else { "Unchecked" };
|
|
|
|
for offset in chosen {
|
|
let criterion = &criteria[offset];
|
|
let state = if criterion.checked == checked {
|
|
format!("Already {}", verb)
|
|
} else {
|
|
past.to_string()
|
|
};
|
|
|
|
println!("{} {}: {}", state, offset + 1, color_text(&criterion.text, Color::Green));
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Install the agent skills, or print one so a modified copy can be diffed.
|
|
///
|
|
/// No board is looked for. The documents are what teach an agent worklane, so needing
|
|
/// a `.worklane` to install them would put them out of reach exactly when they are
|
|
/// wanted.
|
|
///
|
|
/// With no name, every shipped document is installed. Narrowing to one is the
|
|
/// exception rather than the rule, so that a document added in a later version reaches
|
|
/// anyone who already knows the command.
|
|
pub fn cmd_install_skill(skill: Option<&str>, force: bool, print: bool) -> Result<()> {
|
|
if print {
|
|
// Printing every document would run them together into something that is not
|
|
// any of them, and the point of `--print` is to diff one against its copy.
|
|
let name = skill.ok_or_else(|| {
|
|
anyhow!(
|
|
"name the skill to print, as in `worklane install-skill worklane --print`. This binary ships {}",
|
|
install::skill_names()
|
|
)
|
|
})?;
|
|
print!("{}", install::skill_named(name)?.content);
|
|
return Ok(());
|
|
}
|
|
|
|
let chosen: Vec<&install::Asset> = match skill {
|
|
Some(name) => vec![install::skill_named(name)?],
|
|
None => install::SKILLS.iter().collect(),
|
|
};
|
|
|
|
let root = install::skills_root()?;
|
|
let mut written = false;
|
|
for asset in chosen {
|
|
match asset.install(&root, force)? {
|
|
install::Outcome::Written(path) => {
|
|
println!("Installed the {} {} to: {}", asset.name, asset.what, path.display());
|
|
written = true;
|
|
}
|
|
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",
|
|
asset.name
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Once, and only when something arrived: repeating it per document would make the
|
|
// instruction look like part of each outcome rather than the one thing to do next.
|
|
if written {
|
|
println!("Claude Code and opencode pick it up on their next session");
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|