Compare commits

...
2 Commits
7 changed files with 501 additions and 176 deletions
+1
View File
@@ -312,6 +312,7 @@ and this file is for what someone changing worklane's own code needs.
- **A query turns the truncation off**, which is the point of having one: the campaign a reader is searching for is exactly the one the truncation hid - **A query turns the truncation off**, which is the point of having one: the campaign a reader is searching for is exactly the one the truncation hid
- **The query is a layer, and `esc` takes it off before it takes the picker off**, the order `dismiss` closes the board's own layers in. So the list is whole again after that press, not still filtered with nothing on screen saying why. Movement and `enter` stay live under an open query, because a filtered list nothing can move in is a list nothing can be chosen from; every *printable* key goes into the buffer, so `q` types and so does `j` - **The query is a layer, and `esc` takes it off before it takes the picker off**, the order `dismiss` closes the board's own layers in. So the list is whole again after that press, not still filtered with nothing on screen saying why. Movement and `enter` stay live under an open query, because a filtered list nothing can move in is a list nothing can be chosen from; every *printable* key goes into the buffer, so `q` types and so does `j`
- **The highlight follows its row, not its row number.** `place_picker` takes a key — whichever answer `PickerRow::key` hands back, the same shape `Tab::filter` holds for any of them: typing, clearing the query and a tick that finishes a campaign all reshape the list, and a number kept across that names whichever campaign now sits at it. One the list no longer holds drops the highlight to the first row that does, which is where an incremental filter puts it. `reload` reads the highlighted key before the lists are rebuilt and puts it back after - **The highlight follows its row, not its row number.** `place_picker` takes a key — whichever answer `PickerRow::key` hands back, the same shape `Tab::filter` holds for any of them: typing, clearing the query and a tick that finishes a campaign all reshape the list, and a number kept across that names whichever campaign now sits at it. One the list no longer holds drops the highlight to the first row that does, which is where an incremental filter puts it. `reload` reads the highlighted key before the lists are rebuilt and puts it back after
- **Both ends bring the highlight into the window.** Opening aligns against the screen the dispatch hands `open_picker`, and the draw follows the highlight again through `aligned_offset` on the geometry it is actually drawing — a resize between that keypress and the frame, or a tick that put the highlight back without touching the scroll, cannot leave it below the fold until some later keypress fixes it. The stored offset is left alone, the way a column's is: what is drawn is corrected immediately and the next navigation writes the correction back
- **A miss is a row in the box, `no match` in brightred**, where the search prompt puts its own, and `enter` on it leaves the picker and the query exactly as they are so the query can be corrected in place. An empty box says nothing about why it is empty - **A miss is a row in the box, `no match` in brightred**, where the search prompt puts its own, and `enter` on it leaves the picker and the query exactly as they are so the query can be corrected in place. An empty box says nothing about why it is empty
- **The picker's footer becomes its query**, the trade `draw_search` makes: with every printable key going into a buffer, a list of keys describes nothing that works. `/ search` is named only on the closed query, and the open one names what `esc` does to *it* rather than what it does to the picker - **The picker's footer becomes its query**, the trade `draw_search` makes: with every printable key going into a buffer, a list of keys describes nothing that works. `/ search` is named only on the closed query, and the open one names what `esc` does to *it* rather than what it does to the picker
- **The title says both counts while a query is open**, `campaigns (2 of 6)`. The bare total is what the box is, but over a list a query has cut down it is a lie about what is on screen - **The title says both counts while a query is open**, `campaigns (2 of 6)`. The bare total is what the box is, but over a list a query has cut down it is a lie about what is on screen
Generated
+1 -1
View File
@@ -1503,7 +1503,7 @@ dependencies = [
[[package]] [[package]]
name = "worklane" name = "worklane"
version = "0.32.11" version = "0.32.13"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"assert_cmd", "assert_cmd",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "worklane" name = "worklane"
version = "0.32.11" version = "0.32.13"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
+283 -125
View File
@@ -2,7 +2,7 @@ use anyhow::{Result, anyhow};
use chrono::Local; use chrono::Local;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::fs; use std::fs;
use std::io::{BufRead, IsTerminal, Write}; use std::io::{BufRead, IsTerminal};
use std::path::Path; use std::path::Path;
use crate::campaign::*; use crate::campaign::*;
@@ -15,12 +15,12 @@ use crate::install;
use crate::tag::{TAGS_FILE, TagIndex, tags_path}; use crate::tag::{TAGS_FILE, TagIndex, tags_path};
use crate::util::*; 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 dir = start.canonicalize().unwrap_or_else(|_| start.to_path_buf());
let worklane_dir = dir.join(".worklane"); let worklane_dir = dir.join(".worklane");
if worklane_dir.exists() { if worklane_dir.exists() {
println!("worklane already initialized in: {}", worklane_dir.display()); sink.writeln(&format!("worklane already initialized in: {}", worklane_dir.display()))?;
return Ok(()); 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. // directory was made three lines ago, so there is nothing here to truncate.
fs::write(tags_path(&worklane_dir), TagIndex::default().render())?; 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(()) 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 // 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 // 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 // `--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 uuid = campaign.as_ref().map(|campaign| campaign.uuid.as_str());
let tag = args.tag.as_deref(); let tag = args.tag.as_deref();
let priority_filter = args.priority; let priority_filter = args.priority;
let colored = sink.use_color;
if args.ids { 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 { if let Some(campaign) = &campaign {
println!( sink.writeln(&format!(
"Members of campaign ({}) {}\n", "Members of campaign ({}) {}\n",
color_text(short_id(&campaign.uuid), Color::Red), paint(short_id(&campaign.uuid), Color::Red, colored),
color_text(&campaign.title, Color::Green), paint(&campaign.title, Color::Green, colored),
); ))?;
} }
if let Some(status) = args.status { 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)); items.sort_by(|a, b| by_status_order(status, a, b));
if items.is_empty() { if items.is_empty() {
println!("No tickets in '{}' status.", name); sink.writeln(&format!("No tickets in '{}' status.", name))?;
return Ok(()); return Ok(());
} }
println!("Tickets in '{}' status:\n", name); sink.writeln(&format!("Tickets in '{}' status:\n", name))?;
display_ticket_items(&items); display_ticket_items(sink, &items)?;
} else { } else {
// List all statuses with their ticket counts // List all statuses with their ticket counts
let statuses = status_dirs(); let statuses = status_dirs();
println!("Tickets by status:\n"); sink.writeln("Tickets by status:\n")?;
for status in &statuses { for status in &statuses {
let status_path = worklane_dir.join(status); let status_path = worklane_dir.join(status);
if !status_path.exists() { 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 items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid, tag);
let count = items.len(); let count = items.len();
let label = if count == 1 { "ticket" } else { "tickets" }; 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 // 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; continue;
} }
let status_header = let status_header =
color_text(&format!("[{}]", status.as_str().to_uppercase()), Color::Orange); paint(&format!("[{}]", status.as_str().to_uppercase()), Color::Orange, colored);
println!("\n{}", status_header); sink.writeln(&format!("\n{}", status_header))?;
display_ticket_items(&items); 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 /// 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. /// list, and an error printed over the prompt is worse there than no candidates.
fn list_ids( fn list_ids(
sink: &mut Sink,
status: Option<Status>, status: Option<Status>,
level: Option<u8>, level: Option<u8>,
campaign: Option<&str>, campaign: Option<&str>,
@@ -181,7 +183,7 @@ fn list_ids(
let mut items = filtered(collect_ticket_items(&status_path)?, level, campaign, tag); let mut items = filtered(collect_ticket_items(&status_path)?, level, campaign, tag);
items.sort_by(|a, b| by_status_order(status, a, b)); items.sort_by(|a, b| by_status_order(status, a, b));
for item in items { 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 { let AddArgs {
title, title,
description, 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. // 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)?; write_then_replace(&worklane_dir, &filepath, &filename, &body, TICKET, title)?;
println!("Created ticket: {}", filename); sink.writeln(&format!("Created ticket: {}", filename))?;
Ok(()) 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 (_status, title, content) = resolve_ticket(search, worklane_dir)?;
let ticket_uuid = parse_ticket_field(&content, "ID"); let ticket_uuid = parse_ticket_field(&content, "ID");
// Read before anything is printed, so a board that cannot be read fails instead of // Read before anything is printed, so a board that cannot be read fails instead of recover.
// half printing a ticket.
let resolved = resolved_for(&content, worklane_dir)?; 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 // 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. // measured in characters so a non-ASCII title is not over-drawn.
println!("{}", color_text(&title, Color::Green)); sink.writeln(&paint(&title, Color::Green, colored))?;
println!("{}", "─".repeat(title.chars().count())); sink.writeln(&"─".repeat(title.chars().count()))?;
println!("\n{}", content_trim_colored(&content, &resolved)); sink.writeln(&format!("\n{}", content_trim(&content, colored, &resolved)))?;
if ticket_uuid != "_Not set_" { if ticket_uuid != "_Not set_" {
let entries = read_history(worklane_dir, &ticket_uuid)?; let entries = read_history(worklane_dir, &ticket_uuid)?;
let formatted = format_history(&entries); let formatted = format_history(&entries);
println!("{}", formatted); sink.writeln(&formatted)?;
} }
Ok(()) 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 /// 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 /// and nothing here has to check. What is left is the order of the flow, which is
/// `Status::ALL`. /// `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 { let MvArgs {
ticket: ticket_id, ticket: ticket_id,
status: target, status: target,
@@ -657,10 +659,10 @@ pub fn cmd_mv(args: &MvArgs, start: &Path) -> Result<()> {
let recorded = parse_ticket_field(&resolved, "Status"); let recorded = parse_ticket_field(&resolved, "Status");
if recorded == target_status { if recorded == target_status {
println!( sink.writeln(&format!(
"Ticket is already in '{}' status.", "Ticket is already in '{}' status.",
color_text(target_status, Color::Orange) paint(target_status, Color::Orange, sink.use_color)
); ))?;
return Ok(()); return Ok(());
} }
@@ -679,12 +681,12 @@ pub fn cmd_mv(args: &MvArgs, start: &Path) -> Result<()> {
&corrected, &corrected,
)?; )?;
println!( sink.writeln(&format!(
"Corrected Status field on '{}': said {}, but the file sits in {}.", "Corrected Status field on '{}': said {}, but the file sits in {}.",
color_text(&title, Color::Green), paint(&title, Color::Green, sink.use_color),
color_text(&recorded, Color::Orange), paint(&recorded, Color::Orange, sink.use_color),
color_text(target_status, Color::Orange) paint(target_status, Color::Orange, sink.use_color)
); ))?;
return Ok(()); return Ok(());
} }
@@ -747,12 +749,12 @@ pub fn cmd_mv(args: &MvArgs, start: &Path) -> Result<()> {
&reason, &reason,
)?; )?;
println!( sink.writeln(&format!(
"Moved ticket '{}' from {} to {}", "Moved ticket '{}' from {} to {}",
color_text(&title, Color::Green), paint(&title, Color::Green, sink.use_color),
color_text(&current_status, Color::Orange), paint(&current_status, Color::Orange, sink.use_color),
color_text(target_status, Color::Orange), paint(target_status, Color::Orange, sink.use_color),
); ))?;
Ok(()) Ok(())
} }
@@ -763,6 +765,7 @@ pub fn cmd_comment(
actor: &Option<String>, actor: &Option<String>,
actor_from_git: bool, actor_from_git: bool,
start: &Path, start: &Path,
sink: &mut Sink,
) -> Result<()> { ) -> Result<()> {
if body.is_empty() { if body.is_empty() {
return Err(anyhow!("Comment body is required.")); 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(()) 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) { fn report(sink: &mut Sink, fields: &[&str], title: &str, verb: &str) -> Result<()> {
report_in(fields, title, Color::Green, verb) report_in(sink, fields, title, Color::Green, verb)
} }
/// The same, for a subject that is not a title. /// 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 /// 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 /// `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. /// 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() { if fields.is_empty() {
println!("No changes to '{}'", color_text(title, color)); sink.writeln(&format!("No changes to '{}'", sink.color(title, color)))?;
return; 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() { if let Some(field) = args.contested() {
let name = field.name(); let name = field.name();
return Err(anyhow!( return Err(anyhow!(
@@ -1010,7 +1025,7 @@ pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
} }
if changed.is_empty() && cleared.is_empty() { if changed.is_empty() && cleared.is_empty() {
report(&[], &title, "Updated"); report(sink, &[], &title, "Updated")?;
return Ok(()); return Ok(());
} }
@@ -1037,10 +1052,10 @@ pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
let shown = args.title.clone().unwrap_or(title); let shown = args.title.clone().unwrap_or(title);
if !changed.is_empty() { if !changed.is_empty() {
report(&changed, &shown, "Updated"); report(sink, &changed, &shown, "Updated")?;
} }
if !cleared.is_empty() { if !cleared.is_empty() {
report(&cleared, &shown, "Cleared"); report(sink, &cleared, &shown, "Cleared")?;
} }
Ok(()) 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 /// 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 /// says nobody owns this, and putting the person running the command there instead would
/// hand them a ticket they were giving up. /// 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(|| { let (ticket_id, user) = args.target().ok_or_else(|| {
anyhow!("chown takes a user and a ticket, or --clear with the ticket alone") 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)?; let content = set_metadata_field(&original, "Owner", user.unwrap_or(NOT_SET), &title)?;
if content == original { if content == original {
report(&[], &title, "Updated"); report(sink, &[], &title, "Updated")?;
return Ok(()); return Ok(());
} }
@@ -1097,11 +1112,11 @@ pub fn cmd_chown(args: &ChownArgs, start: &Path) -> Result<()> {
Some(_) => "Updated", Some(_) => "Updated",
None => "Cleared", None => "Cleared",
}; };
report(&["owner"], &title, verb); report(sink, &["owner"], &title, verb)?;
Ok(()) 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 worklane_dir = find_worklane_dir(start)?;
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?; let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
let uuid = parse_ticket_field(&original, "ID"); 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)?; save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
report(&changed, &title, "Appended to"); report(sink, &changed, &title, "Appended to")?;
Ok(()) 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 worklane_dir = find_worklane_dir(start)?;
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?; let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
let uuid = parse_ticket_field(&original, "ID"); 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() { if items.is_empty() && dropped.is_empty() {
report(&[], &title, "Recorded"); report(sink, &[], &title, "Recorded")?;
return Ok(()); return Ok(());
} }
@@ -1336,10 +1351,10 @@ pub fn cmd_relate(args: &RelateArgs, start: &Path) -> Result<()> {
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?; save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
if !changed.is_empty() { if !changed.is_empty() {
report(&changed, &title, "Recorded"); report(sink, &changed, &title, "Recorded")?;
} }
if !cleared.is_empty() { if !cleared.is_empty() {
report(&cleared, &title, "Cleared"); report(sink, &cleared, &title, "Cleared")?;
} }
Ok(()) 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 /// 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 /// 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. /// 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 { let CampaignAddArgs {
title, title,
description, 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)?; write_then_replace(&worklane_dir, &path, &filename, &body, CAMPAIGN, title)?;
println!("Created campaign: {}", filename); sink.writeln(&format!("Created campaign: {}", filename))?;
Ok(()) 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 /// 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 /// 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. /// 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 index = CampaignIndex::load(worklane_dir)?;
let colored = sink.use_color;
// Ahead of the empty check, which prints prose: a completion must offer nothing // 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 // rather than offer a sentence, the same bargain `list_ids` takes with a missing
// status directory. // status directory.
if ids { if ids {
for campaign in index.iter() { 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(()); return Ok(());
} }
if index.is_empty() { 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(()); return Ok(());
} }
let colored = should_use_colors(); sink.writeln("Campaigns:\n")?;
println!("Campaigns:\n");
for campaign in index.iter() { for campaign in index.iter() {
let standing = Standing::of(&members(worklane_dir, &campaign.uuid)?); 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(), false => String::new(),
}; };
println!( sink.writeln(&format!(
" ({}) {}{} | {}{}", " ({}) {}{} | {}{}",
paint(short_id(&campaign.uuid), Color::Red, colored), paint(short_id(&campaign.uuid), Color::Red, colored),
codename, codename,
campaign.title, campaign.title,
standing.label(), standing.label(),
state, state,
); ))?;
} }
Ok(()) 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 /// 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. /// 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 // 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 // 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 // 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 { for (tag, count) in counts {
match index.summary(&tag) { match index.summary(&tag) {
Some(summary) => println!("{tag}\t{count}\t{summary}"), Some(summary) => sink.writeln(&format!("{tag}\t{count}\t{summary}"))?,
None => println!("{tag}\t{count}"), 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 /// 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 /// 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. /// 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 worklane_dir = find_worklane_dir(start)?;
let mut index = TagIndex::load(&worklane_dir)?; 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 // 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. // 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(()) 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` /// 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 /// 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. /// 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 worklane_dir = find_worklane_dir(start)?;
let mut index = TagIndex::load(&worklane_dir)?; 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(()) 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: /// 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 /// that is the opposite of the Relations case, where `add` writes nothing and the insertion
/// is the only path there is. /// 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 worklane_dir = find_worklane_dir(start)?;
let campaign = resolve_campaign(&args.campaign, &worklane_dir)?; let campaign = resolve_campaign(&args.campaign, &worklane_dir)?;
let title = campaign.title.clone(); let title = campaign.title.clone();
@@ -1693,14 +1711,14 @@ pub fn cmd_campaign_set(args: &CampaignSetArgs, start: &Path) -> Result<()> {
} }
if changed.is_empty() { if changed.is_empty() {
report(&[], &title, "Updated"); report(sink, &[], &title, "Updated")?;
return Ok(()); return Ok(());
} }
let renamed = changed.contains(&"title").then_some(()).and(args.title.as_ref()); let renamed = changed.contains(&"title").then_some(()).and(args.title.as_ref());
save_campaign(&worklane_dir, &campaign.uuid, &title, renamed, &content)?; 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(()) 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 /// One section, so there is no loop and no list to report: what changed is the description
/// or the call failed. /// 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 worklane_dir = find_worklane_dir(start)?;
let campaign = resolve_campaign(&args.campaign, &worklane_dir)?; 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)?; 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(()) 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 /// 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 /// listing. A campaign's whole point is what is finished against what is left, so
/// hiding the finished half would hide the answer. /// 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)?; let campaign = resolve_campaign(search, worklane_dir)?;
println!("{}", color_text(&campaign.title, Color::Green)); sink.writeln(&paint(&campaign.title, Color::Green, colored))?;
println!("{}", "─".repeat(campaign.title.chars().count())); sink.writeln(&"─".repeat(campaign.title.chars().count()))?;
// No relations and no campaign of its own: a campaign is not a ticket, and neither // No relations and no campaign of its own: a campaign is not a ticket, and neither
// belongs to one. // 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 grouped = members(worklane_dir, &campaign.uuid)?;
let standing = Standing::of(&grouped); let standing = Standing::of(&grouped);
println!("{}", color_text("Members", Color::Orange)); sink.writeln(&paint("Members", Color::Orange, colored))?;
println!("{}", "─".repeat("Members".chars().count())); sink.writeln(&"─".repeat("Members".chars().count()))?;
println!("\n{}", standing.label()); sink.writeln(&format!("\n{}", standing.label()))?;
for (status, items) in &grouped { for (status, items) in &grouped {
if items.is_empty() { if items.is_empty() {
continue; continue;
} }
println!("\n{}", color_text(&format!("[{}]", status.to_uppercase()), Color::Orange)); sink.writeln(&format!(
display_ticket_items(items); "\n{}",
paint(&format!("[{}]", status.to_uppercase()), Color::Orange, colored)
))?;
display_ticket_items(sink, items)?;
} }
Ok(()) Ok(())
@@ -1776,6 +1801,7 @@ pub fn cmd_assign(
actor: &Option<String>, actor: &Option<String>,
actor_from_git: bool, actor_from_git: bool,
start: &Path, start: &Path,
sink: &mut Sink,
) -> Result<()> { ) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?; let worklane_dir = find_worklane_dir(start)?;
let campaign = resolve_campaign(campaign_search, &worklane_dir)?; 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)?; set_or_insert_metadata_field(&original, CAMPAIGN_FIELD, &campaign.uuid, TICKET, &title)?;
if content == original { if content == original {
println!( sink.writeln(&format!(
"Ticket '{}' is already in campaign '{}'", "Ticket '{}' is already in campaign '{}'",
color_text(&title, Color::Green), paint(&title, Color::Green, sink.use_color),
campaign.title, campaign.title,
); ))?;
return Ok(()); return Ok(());
} }
@@ -1817,11 +1843,11 @@ pub fn cmd_assign(
"", "",
)?; )?;
println!( sink.writeln(&format!(
"Assigned '{}' to campaign '{}'", "Assigned '{}' to campaign '{}'",
color_text(&title, Color::Green), paint(&title, Color::Green, sink.use_color),
campaign.title, campaign.title,
); ))?;
Ok(()) Ok(())
} }
@@ -1832,7 +1858,7 @@ pub fn cmd_assign(
/// reason: the opencode wrapper throws on the exit code and keeps stderr, so a list /// 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 /// printed to stdout would be discarded and an agent would learn nothing. Prompting
/// regardless would leave it blocked on a stdin that never closes. /// 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); let listing = criteria_list(criteria);
if !std::io::stdin().is_terminal() { 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)); sink.writeln(&format!(
println!("{}", listing); "Acceptance criteria of '{}':",
paint(title, Color::Green, sink.use_color)
))?;
sink.writeln(&listing)?;
// Either form, since find_criteria takes both. // Either form, since find_criteria takes both.
print!("Number or text: "); sink.write("Number or text: ")?;
std::io::stdout().flush()?; sink.flush()?;
let mut answer = String::new(); let mut answer = String::new();
std::io::stdin().lock().read_line(&mut answer)?; std::io::stdin().lock().read_line(&mut answer)?;
@@ -1933,7 +1962,7 @@ fn resolve_criteria(criteria: &[Criterion], terms: &[String], title: &str) -> Re
Ok(chosen) 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 worklane_dir = find_worklane_dir(start)?;
let (status, title, content) = resolve_ticket(&args.ticket, &worklane_dir)?; 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() { 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)?, terms => resolve_criteria(&criteria, terms, &title)?,
}; };
@@ -1975,7 +2004,12 @@ pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path) -> Result<()> {
past.to_string() 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(()) 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 /// 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 /// exception rather than the rule, so that a document added in a later version reaches
/// anyone who already knows the command. /// 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 { if print {
// Printing every document would run them together into something that is not // 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. // 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() install::skill_names()
) )
})?; })?;
print!("{}", install::skill_named(name)?.content); sink.write(install::skill_named(name)?.content)?;
return Ok(()); 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 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) format!("worklane install-skill {} --print", asset.name)
})?; })?;
// Once, and only when something arrived: repeating it per document would make the // 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. // instruction look like part of each outcome rather than the one thing to do next.
if written { 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(()) 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 /// each command has its own thing to say about what picks the asset up, and neither
/// should say it once per asset. /// should say it once per asset.
fn install_each( fn install_each(
sink: &mut Sink,
chosen: &[&install::Asset], chosen: &[&install::Asset],
root: &Path, root: &Path,
force: bool, force: bool,
@@ -2043,15 +2083,26 @@ fn install_each(
for asset in chosen { for asset in chosen {
match asset.install(root, force)? { match asset.install(root, force)? {
install::Outcome::Written(path) => { 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; written = true;
} }
install::Outcome::Unchanged(path) => { install::Outcome::Unchanged(path) => {
println!("Already up to date: {}", path.display()); sink.writeln(&format!("Already up to date: {}", path.display()))?;
} }
install::Outcome::Refused(path) => { install::Outcome::Refused(path) => {
println!("Differs from the version in this binary: {}", path.display()); sink.writeln(&format!(
println!("Compare with `{}`, or overwrite with --force", compare(asset)); "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 /// 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 /// file, so a name could only be right or wrong, and `--print` needs no help deciding
/// what to print. /// 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 { if print {
print!("{}", install::TOOL.content); sink.write(install::TOOL.content)?;
return Ok(()); return Ok(());
} }
let chosen: Vec<&install::Asset> = install::TOOLS.iter().collect(); let chosen: Vec<&install::Asset> = install::TOOLS.iter().collect();
let root = install::tools_root()?; let root = install::tools_root()?;
let written = let written = install_each(sink, &chosen, &root, force, |_| {
install_each(&chosen, &root, force, |_| "worklane install-tool --print".to_string())?; "worklane install-tool --print".to_string()
})?;
// Not "on its next session", which is what the skills say: opencode reads its config // 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 // 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 // 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. // needs a toolchain: it does not, it runs inside opencode.
if written { if written {
println!( sink.writeln(
"opencode loads it in every project. Restart it: the config is read at startup and never reloaded" "opencode loads it in every project. Restart it: the config is read at startup and never reloaded",
); )?;
println!( 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" "Nothing else to install. It runs in opencode's own runtime, so neither Bun nor @opencode-ai/plugin is needed on this machine",
); )?;
} }
Ok(()) 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();
}
}
+33 -26
View File
@@ -42,45 +42,47 @@ fn main() -> Result<()> {
let start = std::env::current_dir()?; let start = std::env::current_dir()?;
match cli.command { let mut sink = Sink::std();
let result = match cli.command {
// No subcommand opens the board, the way a bare `frig` does, and with no path // No subcommand opens the board, the way a bare `frig` does, and with no path
// it opens the board above the working directory. // it opens the board above the working directory.
None => run_tui(&[], &start), None => run_tui(&[], &start),
Some(Command::Tui { paths }) => run_tui(&paths, &start), Some(Command::Tui { paths }) => run_tui(&paths, &start),
Some(Command::Init) => cmd_init(&start), Some(Command::Init) => cmd_init(&start, &mut sink),
Some(Command::Add(args)) => cmd_add(&args, &start), Some(Command::Add(args)) => cmd_add(&args, &start, &mut sink),
Some(Command::Ls(args)) => { Some(Command::Ls(args)) => {
let worklane_dir = find_worklane_dir(&start)?; let worklane_dir = find_worklane_dir(&start)?;
cmd_ls(&args, &worklane_dir) cmd_ls(&args, &worklane_dir, &mut sink)
} }
Some(Command::Show { id }) => { Some(Command::Show { id }) => {
let worklane_dir = find_worklane_dir(&start)?; let worklane_dir = find_worklane_dir(&start)?;
cmd_show(&id, &worklane_dir) cmd_show(&id, &worklane_dir, &mut sink)
} }
Some(Command::Mv(args)) => cmd_mv(&args, &start), Some(Command::Mv(args)) => cmd_mv(&args, &start, &mut sink),
Some(Command::Set(args)) => cmd_set(&args, &start), Some(Command::Set(args)) => cmd_set(&args, &start, &mut sink),
Some(Command::Append(args)) => cmd_append(&args, &start), Some(Command::Append(args)) => cmd_append(&args, &start, &mut sink),
Some(Command::Relate(args)) => cmd_relate(&args, &start), Some(Command::Relate(args)) => cmd_relate(&args, &start, &mut sink),
Some(Command::Chown(args)) => cmd_chown(&args, &start), Some(Command::Chown(args)) => cmd_chown(&args, &start, &mut sink),
Some(Command::Check(args)) => cmd_check(&args, true, &start), Some(Command::Check(args)) => cmd_check(&args, true, &start, &mut sink),
Some(Command::Uncheck(args)) => cmd_check(&args, false, &start), Some(Command::Uncheck(args)) => cmd_check(&args, false, &start, &mut sink),
Some(Command::Comment { Some(Command::Comment {
ticket, ticket,
body, body,
actor, actor,
actor_from_git, actor_from_git,
}) => cmd_comment(&ticket, &body, &actor, actor_from_git, &start), }) => cmd_comment(&ticket, &body, &actor, actor_from_git, &start, &mut sink),
Some(Command::Campaign { command }) => match command { Some(Command::Campaign { command }) => match command {
CampaignCommand::Add(args) => cmd_campaign_add(&args, &start), CampaignCommand::Add(args) => cmd_campaign_add(&args, &start, &mut sink),
CampaignCommand::Ls { ids } => { CampaignCommand::Ls { ids } => {
let worklane_dir = find_worklane_dir(&start)?; let worklane_dir = find_worklane_dir(&start)?;
cmd_campaign_ls(&worklane_dir, ids) cmd_campaign_ls(&worklane_dir, ids, &mut sink)
} }
CampaignCommand::Set(args) => cmd_campaign_set(&args, &start), CampaignCommand::Set(args) => cmd_campaign_set(&args, &start, &mut sink),
CampaignCommand::Append(args) => cmd_campaign_append(&args, &start), CampaignCommand::Append(args) => cmd_campaign_append(&args, &start, &mut sink),
CampaignCommand::Show { campaign } => { CampaignCommand::Show { campaign } => {
let worklane_dir = find_worklane_dir(&start)?; let worklane_dir = find_worklane_dir(&start)?;
cmd_campaign_show(&campaign, &worklane_dir) cmd_campaign_show(&campaign, &worklane_dir, &mut sink)
} }
}, },
Some(Command::Assign { Some(Command::Assign {
@@ -88,32 +90,37 @@ fn main() -> Result<()> {
ticket, ticket,
actor, actor,
actor_from_git, actor_from_git,
}) => cmd_assign(&campaign, &ticket, &actor, actor_from_git, &start), }) => cmd_assign(&campaign, &ticket, &actor, actor_from_git, &start, &mut sink),
// The bare form and `ls` are one arm: `worklane tags` was the listing before the // The bare form and `ls` are one arm: `worklane tags` was the listing before the
// group existed and the fish completion still calls it that way, so the two // group existed and the fish completion still calls it that way, so the two
// spellings cannot be allowed to drift into two behaviours. // spellings cannot be allowed to drift into two behaviours.
Some(Command::Tags { command }) => match command { Some(Command::Tags { command }) => match command {
None | Some(TagCommand::Ls) => { None | Some(TagCommand::Ls) => {
let worklane_dir = find_worklane_dir(&start)?; let worklane_dir = find_worklane_dir(&start)?;
cmd_tags(&worklane_dir) cmd_tags(&worklane_dir, &mut sink)
} }
Some(TagCommand::Add(args)) => cmd_tag_add(&args, &start), Some(TagCommand::Add(args)) => cmd_tag_add(&args, &start, &mut sink),
Some(TagCommand::Set(args)) => cmd_tag_set(&args, &start), Some(TagCommand::Set(args)) => cmd_tag_set(&args, &start, &mut sink),
}, },
// No board either, for the reason `install-skill` has none: a completion script // No board either, for the reason `install-skill` has none: a completion script
// is generated from the clap definition and is the same wherever it is run. // is generated from the clap definition and is the same wherever it is run.
Some(Command::Completions { shell }) => { Some(Command::Completions { shell }) => {
completions::generate(shell, &mut std::io::stdout()).map_err(Into::into) completions::generate(shell, sink.as_write()).map_err(Into::into)
} }
// No board is looked for: the point of the skill is to teach an agent worklane // No board is looked for: the point of the skill is to teach an agent worklane
// before there is a `.worklane` anywhere. // before there is a `.worklane` anywhere.
Some(Command::InstallSkill { skill, force, print }) => { Some(Command::InstallSkill { skill, force, print }) => {
cmd_install_skill(skill.as_deref(), force, print) cmd_install_skill(skill.as_deref(), force, print, &mut sink)
} }
// No board either, and one agent rather than both: opencode loads the tool file, // No board either, and one agent rather than both: opencode loads the tool file,
// Claude Code has no path for one. // Claude Code has no path for one.
Some(Command::InstallTool { force, print }) => cmd_install_tool(force, print), Some(Command::InstallTool { force, print }) => cmd_install_tool(force, print, &mut sink),
} };
// The board (and every handler) own their own writing, so flush what the last one
// handed the sink before returning; an error path printed nothing to flush.
sink.flush()?;
result
} }
// ---------------------------------------------------------------------- tui -- // ---------------------------------------------------------------------- tui --
+93 -8
View File
@@ -4026,16 +4026,30 @@ fn draw_picker(frame: &mut Frame, tab: &Tab, picker: &Picker, area: Rect) {
Style::default().fg(Color::Orange.into()), Style::default().fg(Color::Orange.into()),
)); ));
// Capped against blank space past the last row, the way an unfocused column is. // Followed on the geometry this frame is drawing, not the one the keypress
let last = (lines.len() as u16).saturating_sub(text.height); // measured. Opening aligns against the screen the dispatch hands it, but a resize
// between that keypress and here shrinks the window under an offset sized to the
// old one, and a tick puts the highlight back by key without touching the scroll at
// all. The stored value is left alone, the way a column's is: what is drawn is
// corrected immediately and the next navigation writes the correction back. The cap
// against blank space past the last row falls out of the same call.
// Followed on the geometry this frame is drawing, not the one the keypress
// measured. Opening aligns against the screen the dispatch hands it, but a resize
// between that keypress and here shrinks the window under an offset sized to the
// old one, and a tick puts the highlight back by key without touching the scroll at
// all. The stored value is left alone, the way a column's is: what is drawn is
// corrected immediately and the next navigation writes the correction back. The cap
// against blank space past the last row falls out of the same call.
let offset = aligned_offset(
picker.offset,
picker.row as u16,
picker.row as u16 + 1,
text.height,
lines.len() as u16,
);
frame.render_widget(Clear, overlay); frame.render_widget(Clear, overlay);
frame.render_widget( frame.render_widget(Paragraph::new(lines).block(block).scroll((offset, 0)), overlay);
Paragraph::new(lines)
.block(block)
.scroll((picker.offset.min(last), 0)),
overlay,
);
} }
/// The picker's own title: how many campaigns the board has, and how many a query left. /// The picker's own title: how many campaigns the board has, and how many a query left.
@@ -11144,6 +11158,77 @@ approach";
); );
} }
/// A board whose picker list is taller than a short window draws, with the campaign
/// filtered onto sitting at its foot: the shape where reaching the highlight takes
/// scrolling, and `c` on the filtered board looks like `c` on any other until the
/// highlight is actually inside the box.
///
/// Fourteen numbered campaigns sort above it, so the deep one is the last open row;
/// with no members anywhere nothing completes, so there is no completed section
/// either and the arithmetic stays fixed.
fn deep_picker_board(dir: &Path) -> Board {
for n in 1..=14 {
write_campaign(
dir,
&format!("{n:02}aaaaaa-0000-4000-8000-000000000000"),
&format!("Campaign {n:02}"),
&format!("c{n:02}"),
"Filler.",
);
}
write_campaign(
dir,
"ffff9999-0000-4000-8000-000000000000",
"Zeppelin survey",
"zeppelin",
"The one far down.",
);
let mut board = one_board(dir);
board
.select_filter(Filter::Campaign("ffff9999-0000-4000-8000-000000000000".into()), SCREEN);
board
}
/// The picker opens with the highlight inside the drawn window, whatever row the
/// selected campaign sits on.
#[test]
fn the_picker_opens_with_the_highlight_inside_the_window() {
let dir = board_dir();
let mut board = deep_picker_board(&dir);
board.open_picker(PickerKind::Campaign, SCREEN);
let rows = picker_rows(&board, 100, 20);
let deep = short_id("ffff9999-0000-4000-8000-000000000000");
assert!(
rows.iter().any(|row| row.contains(deep)),
"the highlighted campaign opened below the fold: {rows:?}"
);
}
/// The draw brings the highlight into the window on its own geometry, so a terminal
/// resized between the keypress that aligned and this frame cannot hide it. Opening
/// against a tall screen leaves an offset sized to the old window; the draw corrects
/// it without a keypress, the way the draw follows the selected card in a column.
#[test]
fn a_resize_between_open_and_frame_cannot_hide_the_highlight() {
let dir = board_dir();
let mut board = deep_picker_board(&dir);
let tall = Size { width: 100, height: 60 };
board.open_picker(PickerKind::Campaign, tall);
// Everything fits the tall window, so nothing but the resize stands between the
// offset and the top of the list.
assert_eq!(board.picker.as_ref().unwrap().offset, 0);
let rows = picker_rows(&board, 100, 20);
let deep = short_id("ffff9999-0000-4000-8000-000000000000");
assert!(
rows.iter().any(|row| row.contains(deep)),
"the draw drew the old window around the highlight: {rows:?}"
);
}
/// The key is named where a reader has to find it, and left out where the frame's own /// The key is named where a reader has to find it, and left out where the frame's own
/// border says how to put a campaign away. /// border says how to put a campaign away.
#[test] #[test]
+89 -15
View File
@@ -1,7 +1,7 @@
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use std::fs; use std::fs;
use std::io::IsTerminal; use std::io::{IsTerminal, Write};
use std::path::Path; use std::path::Path;
use std::sync::OnceLock; use std::sync::OnceLock;
@@ -303,6 +303,80 @@ pub fn color_text(text: &str, color: Color) -> String {
paint(text, color, should_use_colors()) paint(text, color, should_use_colors())
} }
/// A destination for a command's output, chosen by the caller.
///
/// `main` hands a handler its own stdout and nothing about the CLI changes; the
/// board (or a test) hands it an in-memory buffer and reads back what the command
/// said. Threading the writer and the colour decision together means every print
/// site reaches both, and a handler never asks the process about its own stdout.
///
/// `use_color` is the sink's answer, not a read of [`should_use_colors`]: a process
/// whose stdout is a pipe still wants colour when the sink is a buffer a renderer
/// will colour itself, and the board wants plain text however the terminal answers.
pub struct Sink<'a> {
writer: Box<dyn Write + 'a>,
/// Whether the bytes this sink writes carry colour escapes.
pub use_color: bool,
}
impl<'a> Sink<'a> {
/// The process's stdout, coloured by what the terminal wants.
///
/// What `main` passes, so the CLI's output is byte identical to before: every
/// command wrote to stdout through `println!`, and this sink writes to the same
/// stdout through the same [`paint`].
pub fn std() -> Sink<'static> {
// Through `new` so the process's stdout is just another writer the sink wraps.
Sink::new(Box::new(std::io::stdout()), should_use_colors())
}
/// An in-memory buffer, plain, for a test or a caller that colours the text
/// itself.
#[allow(dead_code)]
pub fn buffer(target: &'a mut Vec<u8>) -> Sink<'a> {
Sink {
writer: Box::new(target),
use_color: false,
}
}
/// Any writer, with the colour decision given.
pub fn new(writer: Box<dyn Write + 'a>, use_color: bool) -> Sink<'a> {
Sink { writer, use_color }
}
/// The writer, for a caller that already knows how to fill it (the completions
/// generator).
pub fn as_write(&mut self) -> &mut dyn Write {
&mut *self.writer
}
/// Write `text` followed by a newline, the way `println!` did.
pub fn writeln(&mut self, text: &str) -> Result<()> {
self.writer.write_all(text.as_bytes())?;
self.writer.write_all(b"\n")?;
Ok(())
}
/// Write `text` with no terminator, the way `print!` did. The caller flushes
/// when it then waits on input.
pub fn write(&mut self, text: &str) -> Result<()> {
self.writer.write_all(text.as_bytes())?;
Ok(())
}
/// Flush the writer, so a prompt reaches the terminal before a read.
pub fn flush(&mut self) -> Result<()> {
self.writer.flush()?;
Ok(())
}
/// `text` wrapped in `color`'s escape when this sink is coloured.
pub fn color(&self, text: &str, color: Color) -> String {
paint(text, color, self.use_color)
}
}
/// What sits at a candidate `.worklane` path. /// What sits at a candidate `.worklane` path.
/// ///
/// The distinction the walk turns on is between nothing there and something /// The distinction the walk turns on is between nothing there and something
@@ -738,10 +812,6 @@ pub struct Resolved {
pub campaign: Vec<Cell>, pub campaign: Vec<Cell>,
} }
pub fn content_trim_colored(content: &str, resolved: &Resolved) -> String {
content_trim(content, should_use_colors(), resolved)
}
/// A section heading, its rule, and the blank line the body opens under. /// A section heading, its rule, and the blank line the body opens under.
/// ///
/// The rule is measured on the name as displayed, in characters. It used to span the /// The rule is measured on the name as displayed, in characters. It used to span the
@@ -3314,8 +3384,8 @@ fn show_priority(priority: Priority, colored: bool) -> String {
paint(glyph, colour, colored) paint(glyph, colour, colored)
} }
pub fn display_ticket_items(items: &[TicketItem]) { pub fn display_ticket_items(sink: &mut Sink, items: &[TicketItem]) -> Result<()> {
let colored = should_use_colors(); let colored = sink.use_color;
for item in items { for item in items {
let id = paint(&item.id, Color::Red, colored); let id = paint(&item.id, Color::Red, colored);
@@ -3324,15 +3394,19 @@ pub fn display_ticket_items(items: &[TicketItem]) {
let priority = show_priority(item.priority, colored); let priority = show_priority(item.priority, colored);
if item.created.is_empty() { if item.created.is_empty() {
println!(" {} ({}) {} | Owner: {} | Due: {}", priority, id, item.title, owner, due); sink.writeln(&format!(
" {} ({}) {} | Owner: {} | Due: {}",
priority, id, item.title, owner, due
))?;
} else { } else {
let created = paint(&item.created, Color::Cyan, colored); let created = paint(&item.created, Color::Cyan, colored);
println!( sink.writeln(&format!(
" {} {} ({}) {} | Owner: {} | Due: {}", " {} {} ({}) {} | Owner: {} | Due: {}",
priority, created, id, item.title, owner, due priority, created, id, item.title, owner, due
); ))?;
} }
} }
Ok(())
} }
pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketItem>> { pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketItem>> {
@@ -4714,7 +4788,7 @@ mod tests {
#[test] #[test]
fn a_section_rule_matches_the_width_of_its_name() { fn a_section_rule_matches_the_width_of_its_name() {
let rendered = content_trim_colored("# T\n\n## Description\nbody\n", &Resolved::default()); let rendered = content_trim("# T\n\n## Description\nbody\n", false, &Resolved::default());
// Eleven characters, not fourteen: the rule used to span "## Description" // Eleven characters, not fourteen: the rule used to span "## Description"
assert!(rendered.starts_with("Description\n───────────\n"), "{rendered:?}"); assert!(rendered.starts_with("Description\n───────────\n"), "{rendered:?}");
@@ -4722,7 +4796,7 @@ mod tests {
#[test] #[test]
fn a_non_ascii_section_name_is_not_over_drawn() { fn a_non_ascii_section_name_is_not_over_drawn() {
let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n", &Resolved::default()); let rendered = content_trim("# T\n\n## Résumé\nbody\n", false, &Resolved::default());
assert!(rendered.starts_with("Résumé\n──────\n"), "{rendered:?}"); assert!(rendered.starts_with("Résumé\n──────\n"), "{rendered:?}");
} }
@@ -4730,7 +4804,7 @@ mod tests {
#[test] #[test]
fn the_body_leaves_the_title_to_cmd_show() { fn the_body_leaves_the_title_to_cmd_show() {
let rendered = let rendered =
content_trim_colored("# Only Once\n\n## Description\nbody\n", &Resolved::default()); content_trim("# Only Once\n\n## Description\nbody\n", false, &Resolved::default());
assert!(!rendered.contains("Only Once"), "{rendered:?}"); assert!(!rendered.contains("Only Once"), "{rendered:?}");
// And no gap where it was // And no gap where it was
@@ -4740,7 +4814,7 @@ mod tests {
#[test] #[test]
fn the_metadata_section_renders_as_a_table_inside_the_body() { fn the_metadata_section_renders_as_a_table_inside_the_body() {
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n- **Owner**: alice\n"; let content = "# T\n\n## Metadata\n\n- **ID**: abc\n- **Owner**: alice\n";
let rendered = content_trim_colored(content, &Resolved::default()); let rendered = content_trim(content, false, &Resolved::default());
assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n"); assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n");
} }
@@ -4853,7 +4927,7 @@ Plain line with **bold** and a [link](http://x.test/a).
#[test] #[test]
fn a_section_after_metadata_still_renders() { fn a_section_after_metadata_still_renders() {
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n\n## Notes\n\nafter\n"; let content = "# T\n\n## Metadata\n\n- **ID**: abc\n\n## Notes\n\nafter\n";
let rendered = content_trim_colored(content, &Resolved::default()); let rendered = content_trim(content, false, &Resolved::default());
assert!(rendered.contains("ID abc"), "{rendered:?}"); assert!(rendered.contains("ID abc"), "{rendered:?}");
assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}"); assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}");