`.opencode/tools/worklane.ts` was the second agent asset and the only one that existed nowhere but a checkout. `cargo install` places binaries and nothing else, so anyone who installed worklane got the skills and never the tools, and the copy that did exist was reachable only from this repo. It is now `assets/TOOL.ts`, embedded with `include_str!` like every other asset, and `install-tool` writes it where opencode looks. Its own command rather than a flag on `install-skill`, because the two artifacts are not alike. A skill is inert markdown and one path serves both agents. The tool is executable TypeScript and serves one: Claude Code has no directory it scans for a tool definition, `claude mcp add` is the only way a tool enters its list, and its plugin system adopts agents, hooks, monitors, workflows, output-styles and themes and nothing named tools. Reaching it would mean an MCP server, which is a different artifact and not this file. So somebody on Claude Code takes the documents and never the wrapper, which is the choice this command exists to give them. The path was measured rather than guessed, as the ticket asked. 1.15.10 loads `~/.config/opencode/tool/` and `~/.config/opencode/tools/` both: each was served in turn from a directory outside any project and `/experimental/tool/ids` came back with all eleven worklane tools. Singular is the target, the spelling opencode's own documentation puts first the way it writes `agent(s)` and `skill(s)`. `tools_root()` follows `XDG_CONFIG_HOME` where `skills_root()` does not, because opencode's config root is an XDG path and `~/.claude` is not; `opencode debug paths` reports `$XDG_CONFIG_HOME/opencode` with it set. An empty value counts as unset, the convention `colors_wanted` already follows. `opencode_tool_dir` takes both variables as arguments for the reason `colors_wanted` does: a threaded test binary cannot mutate the process environment to reach one branch at a time. The file name is load bearing and now pinned by a test. opencode builds each tool id as the file name then the export, so `worklane.ts` plus eleven `export const` lines is what makes them `worklane_add` through `worklane_uncheck`. Renaming the file renames every tool and every permission rule naming one. The closing line is not the skills' "on their next session". opencode reads its config once at startup and never reloads it, so a running one keeps the tools it began with and the honest instruction is to restart it. Nothing else has to be installed, which is worth saying because the file is executable and reads as though it wants a toolchain. Criterion 6 asked the command to name the plugin package and Bun as runtime requirements and both are wrong: a copy in a project with no `node_modules` above it registered all eleven tools on a machine with no `bun` on `PATH`. opencode is a Bun binary and the import resolves inside it. The message says the opposite, and the reasoning is on the ticket. `install_each` is the outcome loop both commands now share, with the compare-and-refuse invocation passed in: that line is the only part of an outcome that has to name the command it came from. What each command says after the loop stays with the command. `every_tool_the_wrapper_exports_is_a_real_subcommand` guards the direction that breaks at call time, a tool wrapping a command that has been renamed or dropped. Deliberately not the reverse: the wrapper has no tool for `relate`, `campaign`, `assign` or `tags`, so an agent holding the tools cannot reach campaigns or relations at all, and a test asserting that gap would fail on a decision nobody has taken rather than on a mistake. Its own ticket. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1678 lines
61 KiB
Rust
1678 lines
61 KiB
Rust
use anyhow::{Result, anyhow};
|
|
use chrono::Local;
|
|
use std::collections::BTreeMap;
|
|
use std::fs;
|
|
use std::io::{BufRead, IsTerminal, Write};
|
|
use std::path::Path;
|
|
|
|
use crate::campaign::*;
|
|
use crate::command::{
|
|
AddArgs, AppendArgs, CampaignAddArgs, CampaignSetArgs, 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 {
|
|
// The `Status` is kept alongside its name: the directory is joined from the
|
|
// name, and the order the column prints in is keyed on the status itself.
|
|
let name = status.as_str();
|
|
let status_path = worklane_dir.join(name);
|
|
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.",
|
|
name,
|
|
worklane_dir.display()
|
|
));
|
|
}
|
|
|
|
let mut items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid, tag);
|
|
items.sort_by(|a, b| by_status_order(status, a, b));
|
|
|
|
if items.is_empty() {
|
|
println!("No tickets in '{}' status.", name);
|
|
return Ok(());
|
|
}
|
|
|
|
println!("Tickets in '{}' status:\n", name);
|
|
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. Over `Status::ALL` rather
|
|
// than the names, because each column is ordered by its own entry stamp and the
|
|
// comparator is keyed on the status, not on the directory it was read from.
|
|
for status in Status::ALL {
|
|
if status.as_str() == DONE {
|
|
continue;
|
|
}
|
|
let status_path = worklane_dir.join(status.as_str());
|
|
if !status_path.exists() || !fs::metadata(&status_path)?.is_dir() {
|
|
continue;
|
|
}
|
|
let mut items = match collect_ticket_items(&status_path) {
|
|
Ok(items) => filtered(items, priority_filter, uuid, tag),
|
|
Err(_) => continue,
|
|
};
|
|
items.sort_by(|a, b| by_status_order(status, a, b));
|
|
if items.is_empty() {
|
|
continue;
|
|
}
|
|
let status_header =
|
|
color_text(&format!("[{}]", status.as_str().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],
|
|
None => Status::ALL.to_vec(),
|
|
};
|
|
|
|
for status in statuses {
|
|
let status_path = worklane_dir.join(status.as_str());
|
|
if !status_path.exists() {
|
|
continue;
|
|
}
|
|
// The same order the listing prints, so a completion and the board agree on
|
|
// which ticket is at the head of a column.
|
|
let mut items = filtered(collect_ticket_items(&status_path)?, level, campaign, tag);
|
|
items.sort_by(|a, b| by_status_order(status, a, b));
|
|
for item in items {
|
|
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(())
|
|
}
|
|
|
|
/// What is being written, for the messages a failure carries.
|
|
///
|
|
/// A `&str` naming the thing rather than two copies of the write path: a campaign file is
|
|
/// a ticket file in every way that matters here, `<uuid>_<slug>.md` in a directory, and the
|
|
/// only difference is the word a failure has to use. Every message below puts it
|
|
/// mid-sentence so there is no capital to case.
|
|
const TICKET: &str = "ticket";
|
|
const CAMPAIGN: &str = "campaign";
|
|
|
|
/// 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 file. 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,
|
|
kind: &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 {} '{}' at {}: {}",
|
|
kind,
|
|
title,
|
|
temp.display(),
|
|
e
|
|
));
|
|
}
|
|
|
|
if let Err(e) = fs::rename(&temp, path) {
|
|
let _ = fs::remove_file(&temp);
|
|
return Err(anyhow!(
|
|
"Could not write {} '{}' at {}: {}",
|
|
kind,
|
|
title,
|
|
path.display(),
|
|
e
|
|
));
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// The file in `dir` carrying `uuid`, ticket or campaign.
|
|
///
|
|
/// 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. The same holds
|
|
/// for a campaign, whose file is named the same way.
|
|
fn find_entry_file(dir: &Path, kind: &str, uuid: &str, title: &str) -> Result<String> {
|
|
if uuid.trim().is_empty() || is_unknown_value(uuid) {
|
|
return Err(anyhow!(
|
|
"Could not locate the file for {} '{}': it has no ID field",
|
|
kind,
|
|
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 {} '{}' in {}",
|
|
kind,
|
|
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, TICKET, 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_entry_file(¤t_path, TICKET, &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 dir = worklane_dir.join(status);
|
|
save_entry(worklane_dir, &dir, TICKET, uuid, title, new_title, content)
|
|
}
|
|
|
|
/// The same for a campaign, whose directory is `campaigns/` and which sits in no status.
|
|
///
|
|
/// A named wrapper rather than a `save_entry` at the call site, so the campaign handler
|
|
/// reads the way the ticket handlers do and neither has to know which directory the other
|
|
/// writes to.
|
|
fn save_campaign(
|
|
worklane_dir: &Path,
|
|
uuid: &str,
|
|
title: &str,
|
|
new_title: Option<&String>,
|
|
content: &str,
|
|
) -> Result<()> {
|
|
let dir = campaigns_dir(worklane_dir);
|
|
save_entry(worklane_dir, &dir, CAMPAIGN, uuid, title, new_title, content)
|
|
}
|
|
|
|
/// Write a file back where it was, renaming it when the title changed.
|
|
///
|
|
/// One body for tickets and campaigns. Both are `<uuid>_<slug>.md` in a directory, both are
|
|
/// written through `write_then_replace` so a failure leaves no half file, and both rename
|
|
/// only after the write has landed: renaming first and writing second is what leaves a file
|
|
/// under a name that does not match what is in it.
|
|
fn save_entry(
|
|
worklane_dir: &Path,
|
|
dir: &Path,
|
|
kind: &str,
|
|
uuid: &str,
|
|
title: &str,
|
|
new_title: Option<&String>,
|
|
content: &str,
|
|
) -> Result<()> {
|
|
let filename = find_entry_file(dir, kind, uuid, title)?;
|
|
let path = dir.join(&filename);
|
|
|
|
write_then_replace(worklane_dir, &path, &filename, content, kind, title)?;
|
|
|
|
// The uuid is kept, so the new name cannot collide with another entry, 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 = dir.join(&renamed);
|
|
fs::rename(&path, &destination).map_err(|e| {
|
|
anyhow!(
|
|
"Could not rename {} '{}' to {} after updating it: {}",
|
|
kind,
|
|
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,
|
|
codename,
|
|
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,
|
|
codename.as_deref(),
|
|
&id,
|
|
owner.as_deref(),
|
|
&Local::now().format(TIMESTAMP_FORMAT).to_string(),
|
|
);
|
|
|
|
write_then_replace(&worklane_dir, &path, &filename, &body, CAMPAIGN, 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, ids: bool) -> Result<()> {
|
|
let index = CampaignIndex::load(worklane_dir)?;
|
|
|
|
// Ahead of the empty check, which prints prose: a completion must offer nothing
|
|
// rather than offer a sentence, the same bargain `list_ids` takes with a missing
|
|
// status directory.
|
|
if ids {
|
|
for campaign in index.iter() {
|
|
println!("{}\t{}", short_id(&campaign.uuid), campaign.title);
|
|
}
|
|
return Ok(());
|
|
}
|
|
|
|
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(),
|
|
};
|
|
|
|
// The codename between the id and the title, in the colour the board draws it in
|
|
// and with the same mark: the answer to "which campaign is this" is one word, and
|
|
// it should be the same word wherever it is read. A campaign filed without one
|
|
// spends nothing on it, the way an untagged card spends no row.
|
|
let codename = match campaign.codename.is_some() {
|
|
true => {
|
|
let label = campaign_label(&campaign.uuid, campaign.codename.as_deref());
|
|
format!("{} ", paint_cells(&[label], colored))
|
|
}
|
|
false => String::new(),
|
|
};
|
|
|
|
println!(
|
|
" ({}) {}{} | {}{}",
|
|
paint(short_id(&campaign.uuid), Color::Red, colored),
|
|
codename,
|
|
campaign.title,
|
|
standing.label(),
|
|
state,
|
|
);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Every tag on the board, with how many tickets carry it.
|
|
///
|
|
/// The vocabulary itself, which nothing else could answer: `ls --tag` filters by a tag
|
|
/// already known, and the decorated listing does not print tags at all. A grooming sweep
|
|
/// starts by asking what the vocabulary *is*, and `assets/PLAN.md` used to have to say
|
|
/// that the question could only be answered by reading the tickets.
|
|
///
|
|
/// **Alphabetical, and case sensitive.** `--tag` matches a whole value case sensitively,
|
|
/// so `bug` and `Bug` are two tags and listing them as one would hide the reason a filter
|
|
/// came back short. Sorting puts them next to each other, which is where a near-duplicate
|
|
/// is spotted.
|
|
///
|
|
/// Machine-readable, the second output in the tree that is: the tag, a tab, the count.
|
|
/// Fish reads what follows the tab as a description, a script takes `cut -f1`, and neither
|
|
/// wants an escape sequence. Every status, done included, for the reason `ls --ids`
|
|
/// includes it: a tag retired months ago is still part of the answer to what the
|
|
/// vocabulary has been.
|
|
pub fn cmd_tags(worklane_dir: &Path) -> Result<()> {
|
|
// BTreeMap rather than a sort afterwards: the order is the point, and the counting
|
|
// wants a map anyway.
|
|
let mut counts: BTreeMap<String, usize> = BTreeMap::new();
|
|
|
|
for status in status_dirs() {
|
|
let status_path = worklane_dir.join(status);
|
|
// Skipped rather than refused, as in `list_ids`, and for the same reason.
|
|
if !status_path.exists() {
|
|
continue;
|
|
}
|
|
for item in collect_ticket_items(&status_path)? {
|
|
for tag in item.tags {
|
|
*counts.entry(tag).or_default() += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
for (tag, count) in counts {
|
|
println!("{}\t{}", tag, count);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Replace fields on a campaign that is already filed.
|
|
///
|
|
/// `cmd_set` for a campaign, and built out of the same parts: `set_title` for the heading,
|
|
/// `set_metadata_field` for the field, `apply` for whether an edit changed anything, and
|
|
/// `report` for what it says afterwards. Nothing about writing a field lives twice, which is
|
|
/// the shape `cmd_chown` already took.
|
|
///
|
|
/// The **codename is inserted when the campaign has no such line**, rather than refused.
|
|
/// `set_metadata_field` refuses a field that is not there, which is right for the fields
|
|
/// `add` writes; every campaign filed before the field existed has none, and those are
|
|
/// exactly the campaigns this command is for. So it goes through
|
|
/// `set_or_insert_metadata_field`, the upsert `assign` already uses for the Campaign field
|
|
/// on a ticket, for the same reason.
|
|
///
|
|
/// **Replacing a codename the campaign already has needs `--force`.** Once a campaign has
|
|
/// one it is referred to by it: it is on every card in the campaign, it is what resolves the
|
|
/// campaign at the command line, and changing it out from under that is the same mistake
|
|
/// overwriting an edited skill document would be. So it is refused, and the refusal names
|
|
/// both words and the flag, the way `install-skill` names `--force` rather than leaving it
|
|
/// to be found.
|
|
///
|
|
/// Checked before any edit is applied, like `SetArgs::contested`, so a call that also
|
|
/// carries `--title` writes neither field rather than half of what was asked for.
|
|
///
|
|
/// No-op detection compares the whole file, the way `set` and `chown` do, so setting a
|
|
/// codename a campaign already carries writes nothing. That is a no-op and not a refusal:
|
|
/// `--force` is about overwriting a *different* word, and there is nothing to overwrite.
|
|
pub fn cmd_campaign_set(args: &CampaignSetArgs, start: &Path) -> Result<()> {
|
|
let worklane_dir = find_worklane_dir(start)?;
|
|
let campaign = resolve_campaign(&args.campaign, &worklane_dir)?;
|
|
let title = campaign.title.clone();
|
|
|
|
let overwrite = match (&args.codename, &campaign.codename) {
|
|
(Some(wanted), Some(held)) if wanted != held => Some((held, wanted)),
|
|
_ => None,
|
|
};
|
|
if let Some((held, wanted)) = overwrite.filter(|_| !args.force) {
|
|
return Err(anyhow!(
|
|
"Campaign '{}' is already codenamed '{}', so nothing was written. \
|
|
Pass --force to replace it with '{}'",
|
|
title,
|
|
held,
|
|
wanted
|
|
));
|
|
}
|
|
|
|
let mut content = campaign.content.clone();
|
|
let mut changed: 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);
|
|
}
|
|
|
|
if let Some(codename) = &args.codename {
|
|
let next = set_or_insert_metadata_field(&content, CODENAME_FIELD, codename, &title)?;
|
|
apply(&mut content, &mut changed, "codename", next);
|
|
}
|
|
|
|
if changed.is_empty() {
|
|
report(&[], &title, "Updated");
|
|
return Ok(());
|
|
}
|
|
|
|
let renamed = changed.contains(&"title").then_some(()).and(args.title.as_ref());
|
|
save_campaign(&worklane_dir, &campaign.uuid, &title, renamed, &content)?;
|
|
|
|
report(&changed, args.title.as_ref().unwrap_or(&title), "Updated");
|
|
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 written = install_each(&chosen, &root, force, |asset| {
|
|
format!("worklane install-skill {} --print", 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(())
|
|
}
|
|
|
|
/// Write each asset under `root` and report what happened to it.
|
|
///
|
|
/// Shared by both install commands, which differ in what they install and in what they
|
|
/// say afterwards, never in how an outcome is reported. `compare` is the invocation the
|
|
/// refusal points at, which is the one line that has to name the command it came from.
|
|
///
|
|
/// Returns whether anything was written, because that is what decides the closing line:
|
|
/// each command has its own thing to say about what picks the asset up, and neither
|
|
/// should say it once per asset.
|
|
fn install_each(
|
|
chosen: &[&install::Asset],
|
|
root: &Path,
|
|
force: bool,
|
|
compare: impl Fn(&install::Asset) -> String,
|
|
) -> Result<bool> {
|
|
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 `{}`, or overwrite with --force", compare(asset));
|
|
}
|
|
}
|
|
}
|
|
|
|
Ok(written)
|
|
}
|
|
|
|
/// Install the opencode tool definitions.
|
|
///
|
|
/// No name argument, where `install-skill` has an optional one: there is a single tool
|
|
/// file, so a name could only be right or wrong, and `--print` needs no help deciding
|
|
/// what to print.
|
|
pub fn cmd_install_tool(force: bool, print: bool) -> Result<()> {
|
|
if print {
|
|
print!("{}", install::TOOL.content);
|
|
return Ok(());
|
|
}
|
|
|
|
let chosen: Vec<&install::Asset> = install::TOOLS.iter().collect();
|
|
let root = install::tools_root()?;
|
|
let written =
|
|
install_each(&chosen, &root, force, |_| "worklane install-tool --print".to_string())?;
|
|
|
|
// Not "on its next session", which is what the skills say: opencode reads its config
|
|
// once at startup and does not reload it, so a running one keeps the tools it began
|
|
// with. The second line is there because the file is executable and looks like it
|
|
// needs a toolchain: it does not, it runs inside opencode.
|
|
if written {
|
|
println!(
|
|
"opencode loads it in every project. Restart it: the config is read at startup and never reloaded"
|
|
);
|
|
println!(
|
|
"Nothing else to install. It runs in opencode's own runtime, so neither Bun nor @opencode-ai/plugin is needed on this machine"
|
|
);
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|