(fa5662a) Write handler output through a caller-supplied sink, and bump to 0.32.13

This commit is contained in:
Ansho Rei
2026-08-27 08:13:32 +02:00
parent 8675f22209
commit 69bc2feef5
5 changed files with 407 additions and 168 deletions
+283 -125
View File
@@ -2,7 +2,7 @@ use anyhow::{Result, anyhow};
use chrono::Local;
use std::collections::BTreeMap;
use std::fs;
use std::io::{BufRead, IsTerminal, Write};
use std::io::{BufRead, IsTerminal};
use std::path::Path;
use crate::campaign::*;
@@ -15,12 +15,12 @@ use crate::install;
use crate::tag::{TAGS_FILE, TagIndex, tags_path};
use crate::util::*;
pub fn cmd_init(start: &Path) -> Result<()> {
pub fn cmd_init(start: &Path, sink: &mut Sink) -> 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());
sink.writeln(&format!("worklane already initialized in: {}", worklane_dir.display()))?;
return Ok(());
}
@@ -42,11 +42,11 @@ pub fn cmd_init(start: &Path) -> Result<()> {
// directory was made three lines ago, so there is nothing here to truncate.
fs::write(tags_path(&worklane_dir), TagIndex::default().render())?;
println!("Initialized worklane in: {}", worklane_dir.display());
sink.writeln(&format!("Initialized worklane in: {}", worklane_dir.display()))?;
Ok(())
}
pub fn cmd_ls(args: &LsArgs, worklane_dir: &Path) -> Result<()> {
pub fn cmd_ls(args: &LsArgs, worklane_dir: &Path, sink: &mut Sink) -> 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
@@ -58,17 +58,18 @@ pub fn cmd_ls(args: &LsArgs, worklane_dir: &Path) -> Result<()> {
let uuid = campaign.as_ref().map(|campaign| campaign.uuid.as_str());
let tag = args.tag.as_deref();
let priority_filter = args.priority;
let colored = sink.use_color;
if args.ids {
return list_ids(args.status, priority_filter, uuid, tag, worklane_dir);
return list_ids(sink, args.status, priority_filter, uuid, tag, worklane_dir);
}
if let Some(campaign) = &campaign {
println!(
sink.writeln(&format!(
"Members of campaign ({}) {}\n",
color_text(short_id(&campaign.uuid), Color::Red),
color_text(&campaign.title, Color::Green),
);
paint(short_id(&campaign.uuid), Color::Red, colored),
paint(&campaign.title, Color::Green, colored),
))?;
}
if let Some(status) = args.status {
@@ -92,16 +93,16 @@ pub fn cmd_ls(args: &LsArgs, worklane_dir: &Path) -> Result<()> {
items.sort_by(|a, b| by_status_order(status, a, b));
if items.is_empty() {
println!("No tickets in '{}' status.", name);
sink.writeln(&format!("No tickets in '{}' status.", name))?;
return Ok(());
}
println!("Tickets in '{}' status:\n", name);
display_ticket_items(&items);
sink.writeln(&format!("Tickets in '{}' status:\n", name))?;
display_ticket_items(sink, &items)?;
} else {
// List all statuses with their ticket counts
let statuses = status_dirs();
println!("Tickets by status:\n");
sink.writeln("Tickets by status:\n")?;
for status in &statuses {
let status_path = worklane_dir.join(status);
if !status_path.exists() {
@@ -110,7 +111,7 @@ pub fn cmd_ls(args: &LsArgs, worklane_dir: &Path) -> Result<()> {
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);
sink.writeln(&format!(" [{}] {} {}", status.to_uppercase(), count, label))?;
}
// Show all tickets except the two terminal statuses, grouped by status. Over
@@ -134,9 +135,9 @@ pub fn cmd_ls(args: &LsArgs, worklane_dir: &Path) -> Result<()> {
continue;
}
let status_header =
color_text(&format!("[{}]", status.as_str().to_uppercase()), Color::Orange);
println!("\n{}", status_header);
display_ticket_items(&items);
paint(&format!("[{}]", status.as_str().to_uppercase()), Color::Orange, colored);
sink.writeln(&format!("\n{}", status_header))?;
display_ticket_items(sink, &items)?;
}
}
@@ -160,6 +161,7 @@ pub fn cmd_ls(args: &LsArgs, worklane_dir: &Path) -> Result<()> {
/// 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(
sink: &mut Sink,
status: Option<Status>,
level: Option<u8>,
campaign: Option<&str>,
@@ -181,7 +183,7 @@ fn list_ids(
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);
sink.writeln(&format!("{}\t{}", item.id, item.title))?;
}
}
@@ -243,7 +245,7 @@ fn filter_by_priority(items: Vec<TicketItem>, level: Option<u8>) -> Vec<TicketIt
}
}
pub fn cmd_add(args: &AddArgs, start: &Path) -> Result<()> {
pub fn cmd_add(args: &AddArgs, start: &Path, sink: &mut Sink) -> Result<()> {
let AddArgs {
title,
description,
@@ -349,28 +351,28 @@ pub fn cmd_add(args: &AddArgs, start: &Path) -> Result<()> {
// the same writer as every edit is the one that makes the new file appear whole.
write_then_replace(&worklane_dir, &filepath, &filename, &body, TICKET, title)?;
println!("Created ticket: {}", filename);
sink.writeln(&format!("Created ticket: {}", filename))?;
Ok(())
}
pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
pub fn cmd_show(search: &str, worklane_dir: &Path, sink: &mut Sink) -> Result<()> {
let colored = sink.use_color;
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.
// Read before anything is printed, so a board that cannot be read fails instead of recover.
let resolved = resolved_for(&content, worklane_dir)?;
// The only title in the output: content_trim_colored used to print it a second
// The only title in the output: content_trim 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));
sink.writeln(&paint(&title, Color::Green, colored))?;
sink.writeln(&"─".repeat(title.chars().count()))?;
sink.writeln(&format!("\n{}", content_trim(&content, colored, &resolved)))?;
if ticket_uuid != "_Not set_" {
let entries = read_history(worklane_dir, &ticket_uuid)?;
let formatted = format_history(&entries);
println!("{}", formatted);
sink.writeln(&formatted)?;
}
Ok(())
@@ -598,7 +600,7 @@ fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str) -> Result<()>
/// 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(args: &MvArgs, start: &Path) -> Result<()> {
pub fn cmd_mv(args: &MvArgs, start: &Path, sink: &mut Sink) -> Result<()> {
let MvArgs {
ticket: ticket_id,
status: target,
@@ -657,10 +659,10 @@ pub fn cmd_mv(args: &MvArgs, start: &Path) -> Result<()> {
let recorded = parse_ticket_field(&resolved, "Status");
if recorded == target_status {
println!(
sink.writeln(&format!(
"Ticket is already in '{}' status.",
color_text(target_status, Color::Orange)
);
paint(target_status, Color::Orange, sink.use_color)
))?;
return Ok(());
}
@@ -679,12 +681,12 @@ pub fn cmd_mv(args: &MvArgs, start: &Path) -> Result<()> {
&corrected,
)?;
println!(
sink.writeln(&format!(
"Corrected Status field on '{}': said {}, but the file sits in {}.",
color_text(&title, Color::Green),
color_text(&recorded, Color::Orange),
color_text(target_status, Color::Orange)
);
paint(&title, Color::Green, sink.use_color),
paint(&recorded, Color::Orange, sink.use_color),
paint(target_status, Color::Orange, sink.use_color)
))?;
return Ok(());
}
@@ -747,12 +749,12 @@ pub fn cmd_mv(args: &MvArgs, start: &Path) -> Result<()> {
&reason,
)?;
println!(
sink.writeln(&format!(
"Moved ticket '{}' from {} to {}",
color_text(&title, Color::Green),
color_text(&current_status, Color::Orange),
color_text(target_status, Color::Orange),
);
paint(&title, Color::Green, sink.use_color),
paint(&current_status, Color::Orange, sink.use_color),
paint(target_status, Color::Orange, sink.use_color),
))?;
Ok(())
}
@@ -763,6 +765,7 @@ pub fn cmd_comment(
actor: &Option<String>,
actor_from_git: bool,
start: &Path,
sink: &mut Sink,
) -> Result<()> {
if body.is_empty() {
return Err(anyhow!("Comment body is required."));
@@ -785,7 +788,7 @@ pub fn cmd_comment(
"",
)?;
println!("Comment added to '{}' ({})", title, filename);
sink.writeln(&format!("Comment added to '{}' ({})", title, filename))?;
Ok(())
}
@@ -928,8 +931,8 @@ fn apply(content: &mut String, changed: &mut Vec<&'static str>, field: &'static
}
}
fn report(fields: &[&str], title: &str, verb: &str) {
report_in(fields, title, Color::Green, verb)
fn report(sink: &mut Sink, fields: &[&str], title: &str, verb: &str) -> Result<()> {
report_in(sink, fields, title, Color::Green, verb)
}
/// The same, for a subject that is not a title.
@@ -939,16 +942,28 @@ fn report(fields: &[&str], title: &str, verb: &str) {
/// not one of them. The colour is passed in rather than decided here, which is the trade
/// `paint` makes with `color_text`, and it keeps the wording in one place so a tag reports
/// a no-op in the same words a ticket does.
fn report_in(fields: &[&str], title: &str, color: Color, verb: &str) {
fn report_in(
sink: &mut Sink,
fields: &[&str],
title: &str,
color: Color,
verb: &str,
) -> Result<()> {
if fields.is_empty() {
println!("No changes to '{}'", color_text(title, color));
return;
sink.writeln(&format!("No changes to '{}'", sink.color(title, color)))?;
return Ok(());
}
println!("{} {} on '{}'", verb, fields.join(", "), color_text(title, color));
sink.writeln(&format!(
"{} {} on '{}'",
verb,
fields.join(", "),
sink.color(title, color)
))?;
Ok(())
}
pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
pub fn cmd_set(args: &SetArgs, start: &Path, sink: &mut Sink) -> Result<()> {
if let Some(field) = args.contested() {
let name = field.name();
return Err(anyhow!(
@@ -1010,7 +1025,7 @@ pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
}
if changed.is_empty() && cleared.is_empty() {
report(&[], &title, "Updated");
report(sink, &[], &title, "Updated")?;
return Ok(());
}
@@ -1037,10 +1052,10 @@ pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
let shown = args.title.clone().unwrap_or(title);
if !changed.is_empty() {
report(&changed, &shown, "Updated");
report(sink, &changed, &shown, "Updated")?;
}
if !cleared.is_empty() {
report(&cleared, &shown, "Cleared");
report(sink, &cleared, &shown, "Cleared")?;
}
Ok(())
}
@@ -1061,7 +1076,7 @@ pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
/// 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<()> {
pub fn cmd_chown(args: &ChownArgs, start: &Path, sink: &mut Sink) -> Result<()> {
let (ticket_id, user) = args.target().ok_or_else(|| {
anyhow!("chown takes a user and a ticket, or --clear with the ticket alone")
})?;
@@ -1073,7 +1088,7 @@ pub fn cmd_chown(args: &ChownArgs, start: &Path) -> Result<()> {
let content = set_metadata_field(&original, "Owner", user.unwrap_or(NOT_SET), &title)?;
if content == original {
report(&[], &title, "Updated");
report(sink, &[], &title, "Updated")?;
return Ok(());
}
@@ -1097,11 +1112,11 @@ pub fn cmd_chown(args: &ChownArgs, start: &Path) -> Result<()> {
Some(_) => "Updated",
None => "Cleared",
};
report(&["owner"], &title, verb);
report(sink, &["owner"], &title, verb)?;
Ok(())
}
pub fn cmd_append(args: &AppendArgs, start: &Path) -> Result<()> {
pub fn cmd_append(args: &AppendArgs, start: &Path, sink: &mut Sink) -> 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");
@@ -1122,7 +1137,7 @@ pub fn cmd_append(args: &AppendArgs, start: &Path) -> Result<()> {
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
report(&changed, &title, "Appended to");
report(sink, &changed, &title, "Appended to")?;
Ok(())
}
@@ -1210,7 +1225,7 @@ fn find_relation(
}
}
pub fn cmd_relate(args: &RelateArgs, start: &Path) -> Result<()> {
pub fn cmd_relate(args: &RelateArgs, start: &Path, sink: &mut Sink) -> 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");
@@ -1303,7 +1318,7 @@ pub fn cmd_relate(args: &RelateArgs, start: &Path) -> Result<()> {
}
if items.is_empty() && dropped.is_empty() {
report(&[], &title, "Recorded");
report(sink, &[], &title, "Recorded")?;
return Ok(());
}
@@ -1336,10 +1351,10 @@ pub fn cmd_relate(args: &RelateArgs, start: &Path) -> Result<()> {
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
if !changed.is_empty() {
report(&changed, &title, "Recorded");
report(sink, &changed, &title, "Recorded")?;
}
if !cleared.is_empty() {
report(&cleared, &title, "Cleared");
report(sink, &cleared, &title, "Cleared")?;
}
Ok(())
}
@@ -1351,7 +1366,7 @@ pub fn cmd_relate(args: &RelateArgs, start: &Path) -> Result<()> {
/// 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<()> {
pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path, sink: &mut Sink) -> Result<()> {
let CampaignAddArgs {
title,
description,
@@ -1382,7 +1397,7 @@ pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path) -> Result<()> {
write_then_replace(&worklane_dir, &path, &filename, &body, CAMPAIGN, title)?;
println!("Created campaign: {}", filename);
sink.writeln(&format!("Created campaign: {}", filename))?;
Ok(())
}
@@ -1392,26 +1407,26 @@ pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path) -> Result<()> {
/// 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<()> {
pub fn cmd_campaign_ls(worklane_dir: &Path, ids: bool, sink: &mut Sink) -> Result<()> {
let index = CampaignIndex::load(worklane_dir)?;
let colored = sink.use_color;
// 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);
sink.writeln(&format!("{}\t{}", short_id(&campaign.uuid), campaign.title))?;
}
return Ok(());
}
if index.is_empty() {
println!("No campaigns yet. `worklane campaign add --title` files one.");
sink.writeln("No campaigns yet. `worklane campaign add --title` files one.")?;
return Ok(());
}
let colored = should_use_colors();
println!("Campaigns:\n");
sink.writeln("Campaigns:\n")?;
for campaign in index.iter() {
let standing = Standing::of(&members(worklane_dir, &campaign.uuid)?);
@@ -1432,14 +1447,14 @@ pub fn cmd_campaign_ls(worklane_dir: &Path, ids: bool) -> Result<()> {
false => String::new(),
};
println!(
sink.writeln(&format!(
" ({}) {}{} | {}{}",
paint(short_id(&campaign.uuid), Color::Red, colored),
codename,
campaign.title,
standing.label(),
state,
);
))?;
}
Ok(())
@@ -1479,7 +1494,7 @@ pub fn cmd_campaign_ls(worklane_dir: &Path, ids: bool) -> Result<()> {
///
/// 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<()> {
pub fn cmd_tags(worklane_dir: &Path, sink: &mut Sink) -> Result<()> {
// Through the same `load` `tags add` uses, so a file that is there and cannot be read
// is an error here too. The listing is the one tag command that could go on without the
// file, and reporting a vocabulary while silently treating a broken file as no file is
@@ -1507,8 +1522,8 @@ pub fn cmd_tags(worklane_dir: &Path) -> Result<()> {
for (tag, count) in counts {
match index.summary(&tag) {
Some(summary) => println!("{tag}\t{count}\t{summary}"),
None => println!("{tag}\t{count}"),
Some(summary) => sink.writeln(&format!("{tag}\t{count}\t{summary}"))?,
None => sink.writeln(&format!("{tag}\t{count}"))?,
}
}
@@ -1531,7 +1546,7 @@ pub fn cmd_tags(worklane_dir: &Path) -> Result<()> {
/// The whole file is re-rendered from the parsed vocabulary, so declaring a tag also
/// re-sorts the file and rewrites its preamble. That is why an unreadable file is an error
/// in `TagIndex::load` rather than an empty vocabulary: here, empty would mean erased.
pub fn cmd_tag_add(args: &TagAddArgs, start: &Path) -> Result<()> {
pub fn cmd_tag_add(args: &TagAddArgs, start: &Path, sink: &mut Sink) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let mut index = TagIndex::load(&worklane_dir)?;
@@ -1559,7 +1574,10 @@ pub fn cmd_tag_add(args: &TagAddArgs, start: &Path) -> Result<()> {
// The tag in its own colour, which is the colour it is drawn in on every card and in
// every listing: `tag_color` is a pure function of the word.
println!("Declared tag: {}", color_text(&args.tag, tag_color(&args.tag)));
sink.writeln(&format!(
"Declared tag: {}",
paint(&args.tag, tag_color(&args.tag), sink.use_color)
))?;
Ok(())
}
@@ -1577,7 +1595,7 @@ pub fn cmd_tag_add(args: &TagAddArgs, start: &Path) -> Result<()> {
/// The no-op compares the rendered file rather than the annotation, which is what `apply`
/// does for a ticket: the file is the thing that would be written, so it is the thing worth
/// asking whether the write would change.
pub fn cmd_tag_set(args: &TagSetArgs, start: &Path) -> Result<()> {
pub fn cmd_tag_set(args: &TagSetArgs, start: &Path, sink: &mut Sink) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let mut index = TagIndex::load(&worklane_dir)?;
@@ -1606,7 +1624,7 @@ pub fn cmd_tag_set(args: &TagSetArgs, start: &Path) -> Result<()> {
)?;
}
report_in(&changed, &args.tag, tag_color(&args.tag), "Updated");
report_in(sink, &changed, &args.tag, tag_color(&args.tag), "Updated")?;
Ok(())
}
@@ -1649,7 +1667,7 @@ pub fn cmd_tag_set(args: &TagSetArgs, start: &Path) -> Result<()> {
/// the heading, so an insertion path here would be reachable only from a hand-edited file:
/// that is the opposite of the Relations case, where `add` writes nothing and the insertion
/// is the only path there is.
pub fn cmd_campaign_set(args: &CampaignSetArgs, start: &Path) -> Result<()> {
pub fn cmd_campaign_set(args: &CampaignSetArgs, start: &Path, sink: &mut Sink) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let campaign = resolve_campaign(&args.campaign, &worklane_dir)?;
let title = campaign.title.clone();
@@ -1693,14 +1711,14 @@ pub fn cmd_campaign_set(args: &CampaignSetArgs, start: &Path) -> Result<()> {
}
if changed.is_empty() {
report(&[], &title, "Updated");
report(sink, &[], &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");
report(sink, &changed, args.title.as_ref().unwrap_or(&title), "Updated")?;
Ok(())
}
@@ -1717,7 +1735,7 @@ pub fn cmd_campaign_set(args: &CampaignSetArgs, start: &Path) -> Result<()> {
///
/// One section, so there is no loop and no list to report: what changed is the description
/// or the call failed.
pub fn cmd_campaign_append(args: &CampaignAppendArgs, start: &Path) -> Result<()> {
pub fn cmd_campaign_append(args: &CampaignAppendArgs, start: &Path, sink: &mut Sink) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let campaign = resolve_campaign(&args.campaign, &worklane_dir)?;
@@ -1726,7 +1744,7 @@ pub fn cmd_campaign_append(args: &CampaignAppendArgs, start: &Path) -> Result<()
save_campaign(&worklane_dir, &campaign.uuid, &campaign.title, None, &content)?;
report(&[DESCRIPTION.label], &campaign.title, "Appended to");
report(sink, &[DESCRIPTION.label], &campaign.title, "Appended to")?;
Ok(())
}
@@ -1735,28 +1753,35 @@ pub fn cmd_campaign_append(args: &CampaignAppendArgs, start: &Path) -> Result<()
/// 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<()> {
pub fn cmd_campaign_show(search: &str, worklane_dir: &Path, sink: &mut Sink) -> Result<()> {
let colored = sink.use_color;
let campaign = resolve_campaign(search, worklane_dir)?;
println!("{}", color_text(&campaign.title, Color::Green));
println!("{}", "─".repeat(campaign.title.chars().count()));
sink.writeln(&paint(&campaign.title, Color::Green, colored))?;
sink.writeln(&"─".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()));
sink.writeln(&format!(
"\n{}",
content_trim(&campaign.content, colored, &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());
sink.writeln(&paint("Members", Color::Orange, colored))?;
sink.writeln(&"─".repeat("Members".chars().count()))?;
sink.writeln(&format!("\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);
sink.writeln(&format!(
"\n{}",
paint(&format!("[{}]", status.to_uppercase()), Color::Orange, colored)
))?;
display_ticket_items(sink, items)?;
}
Ok(())
@@ -1776,6 +1801,7 @@ pub fn cmd_assign(
actor: &Option<String>,
actor_from_git: bool,
start: &Path,
sink: &mut Sink,
) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let campaign = resolve_campaign(campaign_search, &worklane_dir)?;
@@ -1786,11 +1812,11 @@ pub fn cmd_assign(
set_or_insert_metadata_field(&original, CAMPAIGN_FIELD, &campaign.uuid, TICKET, &title)?;
if content == original {
println!(
sink.writeln(&format!(
"Ticket '{}' is already in campaign '{}'",
color_text(&title, Color::Green),
paint(&title, Color::Green, sink.use_color),
campaign.title,
);
))?;
return Ok(());
}
@@ -1817,11 +1843,11 @@ pub fn cmd_assign(
"",
)?;
println!(
sink.writeln(&format!(
"Assigned '{}' to campaign '{}'",
color_text(&title, Color::Green),
paint(&title, Color::Green, sink.use_color),
campaign.title,
);
))?;
Ok(())
}
@@ -1832,7 +1858,7 @@ pub fn cmd_assign(
/// 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> {
fn ask_which_criterion(sink: &mut Sink, criteria: &[Criterion], title: &str) -> Result<usize> {
let listing = criteria_list(criteria);
if !std::io::stdin().is_terminal() {
@@ -1843,11 +1869,14 @@ fn ask_which_criterion(criteria: &[Criterion], title: &str) -> Result<usize> {
));
}
println!("Acceptance criteria of '{}':", color_text(title, Color::Green));
println!("{}", listing);
sink.writeln(&format!(
"Acceptance criteria of '{}':",
paint(title, Color::Green, sink.use_color)
))?;
sink.writeln(&listing)?;
// Either form, since find_criteria takes both.
print!("Number or text: ");
std::io::stdout().flush()?;
sink.write("Number or text: ")?;
sink.flush()?;
let mut answer = String::new();
std::io::stdin().lock().read_line(&mut answer)?;
@@ -1933,7 +1962,7 @@ fn resolve_criteria(criteria: &[Criterion], terms: &[String], title: &str) -> Re
Ok(chosen)
}
pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path) -> Result<()> {
pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path, sink: &mut Sink) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let (status, title, content) = resolve_ticket(&args.ticket, &worklane_dir)?;
@@ -1943,7 +1972,7 @@ pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path) -> Result<()> {
}
let chosen = match args.criteria.as_slice() {
[] => vec![ask_which_criterion(&criteria, &title)?],
[] => vec![ask_which_criterion(sink, &criteria, &title)?],
terms => resolve_criteria(&criteria, terms, &title)?,
};
@@ -1975,7 +2004,12 @@ pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path) -> Result<()> {
past.to_string()
};
println!("{} {}: {}", state, offset + 1, color_text(&criterion.text, Color::Green));
sink.writeln(&format!(
"{} {}: {}",
state,
offset + 1,
paint(&criterion.text, Color::Green, sink.use_color)
))?;
}
Ok(())
@@ -1990,7 +2024,12 @@ pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path) -> Result<()> {
/// 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<()> {
pub fn cmd_install_skill(
skill: Option<&str>,
force: bool,
print: bool,
sink: &mut Sink,
) -> 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.
@@ -2000,7 +2039,7 @@ pub fn cmd_install_skill(skill: Option<&str>, force: bool, print: bool) -> Resul
install::skill_names()
)
})?;
print!("{}", install::skill_named(name)?.content);
sink.write(install::skill_named(name)?.content)?;
return Ok(());
}
@@ -2010,14 +2049,14 @@ pub fn cmd_install_skill(skill: Option<&str>, force: bool, print: bool) -> Resul
};
let root = install::skills_root()?;
let written = install_each(&chosen, &root, force, |asset| {
let written = install_each(sink, &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");
sink.writeln("Claude Code and opencode pick it up on their next session")?;
}
Ok(())
@@ -2033,6 +2072,7 @@ pub fn cmd_install_skill(skill: Option<&str>, force: bool, print: bool) -> Resul
/// 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(
sink: &mut Sink,
chosen: &[&install::Asset],
root: &Path,
force: bool,
@@ -2043,15 +2083,26 @@ fn install_each(
for asset in chosen {
match asset.install(root, force)? {
install::Outcome::Written(path) => {
println!("Installed the {} {} to: {}", asset.name, asset.what, path.display());
sink.writeln(&format!(
"Installed the {} {} to: {}",
asset.name,
asset.what,
path.display()
))?;
written = true;
}
install::Outcome::Unchanged(path) => {
println!("Already up to date: {}", path.display());
sink.writeln(&format!("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));
sink.writeln(&format!(
"Differs from the version in this binary: {}",
path.display()
))?;
sink.writeln(&format!(
"Compare with `{}`, or overwrite with --force",
compare(asset)
))?;
}
}
}
@@ -2064,29 +2115,136 @@ fn install_each(
/// 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<()> {
pub fn cmd_install_tool(force: bool, print: bool, sink: &mut Sink) -> Result<()> {
if print {
print!("{}", install::TOOL.content);
sink.write(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())?;
let written = install_each(sink, &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"
);
sink.writeln(
"opencode loads it in every project. Restart it: the config is read at startup and never reloaded",
)?;
sink.writeln(
"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 sink_tests {
use super::*;
use crate::util::Sink;
use std::fs;
/// A throwaway board, so a test can point a handler at a sink without touching the
/// real one. Cleaned up at the end; a leftover here is an aborted test, not a
/// fixture the suite has to keep alive.
fn temp_worklane() -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("wl-sink-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&dir).unwrap();
for status in ["backlog", "committed", "reviewing", "done", "discarded"] {
fs::create_dir_all(dir.join(status)).unwrap();
}
fs::create_dir_all(dir.join("campaigns")).unwrap();
fs::write(dir.join("tags.md"), crate::tag::TagIndex::default().render()).unwrap();
dir
}
fn ticket(dir: &Path, status: &str, uuid: &str) {
fs::write(
dir.join(status).join(format!("{}_ticket.md", uuid)),
format!(
"# {u} title\n\
\n\
## Description\n\
body\n\
\n\
## Metadata\n\
\n\
- **ID**: {u}\n\
- **Priority**: 3\n\
- **Tags**: _None_\n\
- **Owner**: alice\n\
- **Created At**: 2026-08-21 02:10:17\n\
- **Status**: {status}\n",
u = uuid,
status = status,
),
)
.unwrap();
}
/// A handler writes through the sink it is handed, and a caller can read the bytes
/// back without a terminal or a real stdout.
#[test]
fn handler_writes_to_a_buffer() {
let dir = temp_worklane();
ticket(&dir, "backlog", "abc1234-def5678");
let args = LsArgs {
status: None,
priority: None,
tag: None,
campaign: None,
ids: false,
};
let mut buf = Vec::new();
{
let mut sink = Sink::buffer(&mut buf);
cmd_ls(&args, &dir, &mut sink).unwrap();
}
let out = String::from_utf8(buf).unwrap();
// The short id, not swallowed by a terminal, and no colour escapes without a
// colour sink.
assert!(out.contains("abc1234"), "ticket id missing from:\n{out}");
assert!(!out.contains('\u{1b}'), "unexpected colour in:\n{out}");
fs::remove_dir_all(&dir).ok();
}
/// The same handler behind a coloured sink paints the id red, so the colour decision
/// is the sink's and not the process's.
#[test]
fn handler_colours_when_the_sink_says_so() {
let dir = temp_worklane();
ticket(&dir, "backlog", "abc1234-def5678");
let args = LsArgs {
status: None,
priority: None,
tag: None,
campaign: None,
ids: false,
};
let mut buf = Vec::new();
{
let mut sink = Sink::new(Box::new(&mut buf), true);
// The sink is the source of the colour decision: the same word it wraps
// here is what the handler paints through `paint(.., sink.use_color)`.
assert!(sink.color("abc1234", Color::Red).contains('\u{1b}'));
cmd_ls(&args, &dir, &mut sink).unwrap();
}
let out = String::from_utf8(buf).unwrap();
assert!(out.contains("abc1234"), "ticket id missing from:\n{out}");
assert!(out.contains('\u{1b}'), "expected colour in:\n{out}");
fs::remove_dir_all(&dir).ok();
}
}