(07ac4e1) Filter campaign ls by state, and lay its listing out as a table, and bump to 0.33.6

campaign ls printed every campaign and offered no way to narrow it, and the
row was assembled by hand, so a long title pushed the standing out of line
with the row above it and the created date the file already carries was not
shown at all.

--state takes open, done or empty and matches against Standing::state(),
so the derived value keeps one definition: a campaign reads [open] in the
listing if and only if --state open lists it. --state rather than --status,
which names one of the five ticket statuses everywhere else and would
invite --state backlog here. empty is the third value because an empty
campaign derives None deliberately, and a filter that could not reach those
would leave what has been filed and forgotten answerable only by reading
the whole listing. A filter that matches nothing names the value back,
since a silent listing reads as the other empty case.

The filter reaches --ids as well, the way ls --ids keeps its own, and is
the only thing that makes that path count members: an unfiltered completion
is as cheap as it was.

The columns are measured on the raw values and padded before anything is
painted, the rule metadata_cells follows. The codename is measured with the
title rather than given a column of its own: a campaign filed without one
spends nothing on it, so a column for it would be one most rows pad into
and some leave empty, and what a reader lines up is where a name ends and
its progress begins.

A flag's possible values now come off the command that holds the flag, so
campaign ls --state reaches ls's own arguments rather than campaign's. The
prompt offered nothing there while fish offered the three values, which
made a liar of the rule that a ValueEnum added anywhere is typeable on the
board the day it is added.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ansho Rei
2026-09-15 16:42:21 +02:00
co-authored by Claude Opus 5
parent 3e732535f8
commit 634a1f44c4
14 changed files with 448 additions and 30 deletions
+55 -1
View File
@@ -238,6 +238,13 @@ pub fn members(worklane_dir: &Path, uuid: &str) -> Result<Vec<(&'static str, Vec
Ok(grouped)
}
/// A campaign with work outstanding, beside [`DONE`] for one with none left.
///
/// Not a [`Status`]: no ticket is ever in it and no directory is named for it. It is the
/// campaign's own two-word vocabulary, and it is a const because the listing prints it,
/// [`Standing::state`] derives it and [`CampaignState`] filters on it.
pub const OPEN: &str = "open";
/// How far a campaign has got: members done against members held.
///
/// `Copy` because the board carries one on every `CampaignRow`, settled at reload: two
@@ -282,7 +289,54 @@ impl Standing {
match (self.total, self.done == self.total) {
(0, _) => None,
(_, true) => Some(DONE),
(_, false) => Some("open"),
(_, false) => Some(OPEN),
}
}
}
/// The state a campaign is in, as `campaign ls --state` accepts it.
///
/// A `ValueEnum` for the reason [`Status`] is one: an unknown value is clap's to refuse
/// at parse time with the three listed, no handler has to check, and every shell that
/// completes possible values gets them for free.
///
/// `--state` and not `--status`, which names one of the five ticket statuses everywhere
/// else in the tool. A campaign sits in no status directory, and borrowing the word for
/// a different vocabulary is how a reader comes to type `--status backlog` here.
///
/// `Empty` is the third value because [`Standing::state`] answers `None` for a campaign
/// nothing has been filed against, deliberately, and a filter that could not reach those
/// would leave the one question a grooming sweep asks — what has been filed and forgotten
/// — answerable only by reading the whole listing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum CampaignState {
/// Holds members, and at least one of them is not finished
Open,
/// Holds members, and every one of them is done or discarded
Done,
/// Holds no members at all, so it is neither open nor done
Empty,
}
impl CampaignState {
/// The value as it is typed, which is what a message naming the filter repeats back.
pub fn as_str(self) -> &'static str {
match self {
Self::Open => OPEN,
Self::Done => DONE,
Self::Empty => "empty",
}
}
/// Whether a campaign in this standing is the one the filter asked for.
///
/// Matched against [`Standing::state`] rather than against the counters, so the
/// derived value has one definition: a campaign reads `[open]` in the listing if and
/// only if `--state open` lists it.
pub fn holds(self, standing: &Standing) -> bool {
match self {
Self::Empty => standing.state().is_none(),
wanted => standing.state() == Some(wanted.as_str()),
}
}
}
+12
View File
@@ -4,6 +4,7 @@ use std::sync::LazyLock;
use chrono::NaiveDate;
use crate::campaign::CampaignState;
use crate::util::{Clearable, PRIORITY_RANGE, RelationKind, Status, priority_legend};
/// clap wants a `&str` with a long enough lifetime, and the legend is built from
@@ -430,6 +431,17 @@ pub enum CampaignCommand {
/// candidate list on a keypress
#[arg(long)]
ids: bool,
/// Only campaigns in this state: open, done, or empty for one nothing has been
/// filed against
///
/// A campaign's state is derived from its members, so this is a match against the
/// value the listing already computes and shows in brackets. `--state` rather than
/// `--status`, which names one of the five ticket statuses everywhere else; a
/// campaign sits in no status directory. It applies to `--ids` as well, where the
/// member counts it needs are read only because a filter was given
#[arg(long, value_name = "STATE")]
state: Option<CampaignState>,
},
/// Show a campaign and its members grouped by status
+22 -1
View File
@@ -167,6 +167,16 @@ pub fn argument_at(args: &[String], index: usize) -> Option<Argument> {
let verb = args.first().map(String::as_str)?;
let group = cli.find_subcommand(verb);
// The command a flag belongs to, which is the *nested* one where a group's child
// carries it: `--state` is `campaign ls`'s and clap holds it on `ls`, not on
// `campaign`. Falls back to the group itself, which is where every other flag is, and
// to nothing for a line whose second word names no subcommand — `mv 1b78a24 --status`
// reaches `mv`'s own arguments as it always did.
let holder = args
.get(1)
.and_then(|child| group.and_then(|group| group.find_subcommand(child)))
.or(group);
// A flag's value is the argument after it, which is where the flag sits whether the
// value is half typed or has not been started.
if let Some(flag) = args.get(index - 1).and_then(|arg| arg.strip_prefix("--")) {
@@ -187,7 +197,9 @@ pub fn argument_at(args: &[String], index: usize) -> Option<Argument> {
// And everything else the flag could take, which is whatever clap knows: `--status`
// and `set --clear` are both `ValueEnum`s, so their values are already written down
// once, in the enum.
let arg = group?.get_arguments().find(|arg| arg.get_long() == Some(flag))?;
let arg = holder?
.get_arguments()
.find(|arg| arg.get_long() == Some(flag))?;
return fixed(arg);
}
@@ -762,6 +774,15 @@ mod tests {
assert!(shells.contains(&"fish".to_string()), "{shells:?}");
}
/// The flag on a nested command is answered the same way, from the enum: nothing here
/// knows what a campaign's states are, and the values reach the prompt and fish alike
/// the day a fourth one is added to `CampaignState`.
#[test]
fn campaign_ls_state_is_offered_the_enums_own_values() {
let states = values("campaign ls --state ").expect("--state takes a state");
assert_eq!(states, vec!["open", "done", "empty"], "{states:?}");
}
/// `relate --clear` takes the kind and then the target, which is the one argument clap
/// cannot answer for: possible values on the flag would refuse every target.
#[test]
+183 -18
View File
@@ -1486,21 +1486,43 @@ pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path, sink: &mut Sink) -
Ok(())
}
/// List the campaigns with how far each has got.
/// List the campaigns with how far each has got, as a table.
///
/// The counts come from one pass over the status directories per campaign. That is a
/// scan per row rather than one scan reused, and it is deliberate: the alternative is a
/// map from campaign uuid to counts built in a single walk, which is worth writing when
/// a board has enough campaigns to notice and is premature now.
pub fn cmd_campaign_ls(worklane_dir: &Path, ids: bool, sink: &mut Sink) -> Result<()> {
///
/// **The columns are measured on the raw values and padded before anything is styled**,
/// the rule `metadata_cells` follows: a padded coloured value counts its escape
/// sequences towards its width, which tilts a table when colour is on and not when it is
/// off.
///
/// The codename is measured with the title rather than given a column of its own. A
/// campaign filed without one spends nothing on it, so a column for it would be a column
/// most rows pad into and some rows leave empty; what a reader is lining up is where one
/// campaign's name ends and its progress begins.
pub fn cmd_campaign_ls(
worklane_dir: &Path,
ids: bool,
state: Option<CampaignState>,
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.
//
// The filter reaches here too, the way `ls --ids` keeps its own filters. The counts
// it needs are what `--ids` exists to avoid reading, so they are read only when a
// filter was given: an unfiltered completion is as cheap as it was.
if ids {
for campaign in index.iter() {
if !kept(worklane_dir, &campaign.uuid, state)? {
continue;
}
sink.writeln(&format!("{}\t{}", short_id(&campaign.uuid), campaign.title))?;
}
return Ok(());
@@ -1511,33 +1533,85 @@ pub fn cmd_campaign_ls(worklane_dir: &Path, ids: bool, sink: &mut Sink) -> Resul
return Ok(());
}
sink.writeln("Campaigns:\n")?;
// Built whole before anything is written, because no column can be sized until every
// row has been seen. `CampaignRow` holds the raw values, so the widths are measured
// on what a reader sees rather than on what an escape sequence costs.
let mut rows: Vec<CampaignRow> = Vec::new();
for campaign in index.iter() {
let standing = Standing::of(&members(worklane_dir, &campaign.uuid)?);
let state = match standing.state() {
Some(state) => format!(" [{}]", paint(state, Color::Orange, colored)),
None => String::new(),
};
if state.is_some_and(|wanted| !wanted.holds(&standing)) {
continue;
}
// The codename between the id and the title, in the colour the board draws it in
// and with the same mark: the answer to "which campaign is this" is one word, and
// it should be the same word wherever it is read. A campaign filed without one
// spends nothing on it, the way an untagged card spends no row.
let codename = match campaign.codename.is_some() {
true => {
let label = campaign_label(&campaign.uuid, campaign.codename.as_deref());
format!("{} ", paint_cells(&[label], colored))
}
let name = match campaign.codename.is_some() {
true => vec![
campaign_label(&campaign.uuid, campaign.codename.as_deref()),
Cell::plain(format!(" {}", campaign.title)),
],
false => vec![Cell::plain(&campaign.title)],
};
rows.push(CampaignRow {
created: format_created_at(&parse_ticket_field(&campaign.content, "Created At")),
id: short_id(&campaign.uuid).to_string(),
width: name.iter().map(|cell| cell.text.chars().count()).sum(),
name,
label: standing.label(),
state: standing.state(),
});
}
// A filter that matches nothing says so, naming what was asked for: a listing that
// went silent reads as a board with no campaigns on it, which is the other message.
if rows.is_empty() {
let wanted = state.map(CampaignState::as_str).unwrap_or_default();
sink.writeln(&format!("No campaigns matching `--state {wanted}`."))?;
return Ok(());
}
sink.writeln("Campaigns:\n")?;
let name_width = rows.iter().map(|row| row.width).max().unwrap_or(0);
let label_width = rows
.iter()
.map(|row| row.label.chars().count())
.max()
.unwrap_or(0);
// Every stamp is the same width, so the column is either there or it is not: a
// campaign whose Created At cannot be parsed drops it, the way a ticket's does.
let dated = rows.iter().any(|row| !row.created.is_empty());
let created_width = rows
.iter()
.map(|row| row.created.chars().count())
.max()
.unwrap_or(0);
for row in &rows {
let created = match dated {
true => format!(
"{}{} ",
paint(&row.created, Color::Cyan, colored),
" ".repeat(created_width - row.created.chars().count()),
),
false => String::new(),
};
let state = match row.state {
Some(state) => format!(" [{}]", paint(state, Color::Orange, colored)),
None => String::new(),
};
sink.writeln(&format!(
" ({}) {}{} | {}{}",
paint(short_id(&campaign.uuid), Color::Red, colored),
codename,
campaign.title,
standing.label(),
" {}({}) {}{} | {}{}{}",
created,
paint(&row.id, Color::Red, colored),
paint_cells(&row.name, colored),
" ".repeat(name_width - row.width),
row.label,
" ".repeat(label_width - row.label.chars().count()),
state,
))?;
}
@@ -1545,6 +1619,35 @@ pub fn cmd_campaign_ls(worklane_dir: &Path, ids: bool, sink: &mut Sink) -> Resul
Ok(())
}
/// One row of the `campaign ls` table, as its raw values.
///
/// The widths are measured off these and the painting happens after, which is the whole
/// reason the row is held rather than written as it is built: a column sized on a
/// coloured string counts its escape sequences towards its width.
struct CampaignRow {
created: String,
id: String,
/// The codename and the title, as the cells they are drawn in.
name: Vec<Cell>,
/// The width of `name` in characters, which is what the column is sized on.
width: usize,
label: String,
state: Option<&'static str>,
}
/// Whether one campaign survives the `--state` filter, reading its members only when
/// there is a filter to answer.
///
/// The counts cost a pass over the status directories, and `--ids` is called on a
/// keypress by a shell filling in a candidate list.
fn kept(worklane_dir: &Path, uuid: &str, state: Option<CampaignState>) -> Result<bool> {
let Some(wanted) = state else {
return Ok(true);
};
Ok(wanted.holds(&Standing::of(&members(worklane_dir, uuid)?)))
}
/// Every tag on the board: the ones the tickets carry, the ones the file declares, and
/// what each declared one means.
///
@@ -2296,6 +2399,68 @@ mod sink_tests {
root
}
/// A campaign file as `campaign add` writes one, for a listing test that needs two
/// of them with titles of different lengths.
fn campaign(dir: &Path, title: &str, codename: Option<&str>, uuid: &str) {
let id = uuid::Uuid::parse_str(uuid).unwrap();
let body = campaign_body(title, &[], codename, &id, None, "2026-08-21 02:10:17");
fs::write(dir.join("campaigns").join(format!("{uuid}_{}.md", slug(title))), body).unwrap();
}
/// The table is laid out on the raw values, so the columns stand in the same place
/// whether the row is coloured or not.
///
/// Rendered both ways in one process and compared with the escapes taken back off,
/// which is what `metadata_cells` is pinned by: a column measured on a painted value
/// counts its escape sequences towards its width, and the listing then tilts when
/// colour is on and stands straight when it is off, which is the one combination a
/// piped test can never see.
#[test]
fn the_campaign_table_stands_in_the_same_columns_coloured_or_not() {
let dir = temp_worklane();
ticket(&dir, "backlog", "11111111-1111-4111-8111-111111111111");
campaign(
&dir,
"A campaign nothing was filed against",
None,
"aa11bb22-0000-4000-8000-000000000000",
);
campaign(&dir, "Short", Some("v1"), "bb22cc33-0000-4000-8000-000000000000");
let mut plain = Vec::new();
{
let mut sink = Sink::new(Box::new(&mut plain), false);
cmd_campaign_ls(&dir, false, None, &mut sink).unwrap();
}
let mut painted = Vec::new();
{
let mut sink = Sink::new(Box::new(&mut painted), true);
cmd_campaign_ls(&dir, false, None, &mut sink).unwrap();
}
let plain = String::from_utf8(plain).unwrap();
let painted = String::from_utf8(painted).unwrap();
assert!(painted.contains('\u{1b}'), "the coloured sink wrote no colour");
assert_eq!(
without_escapes(&painted),
plain,
"the columns moved when the values were painted"
);
// And they are columns: the gutter before the member count sits at one offset on
// every row, whatever the title before it was.
let gutters: Vec<Option<usize>> = plain
.lines()
.filter(|line| line.contains(" | "))
.map(|line| line.find(" | "))
.collect();
assert_eq!(gutters.len(), 2, "both campaigns should be listed:\n{plain}");
assert!(
gutters.iter().all(|at| *at == gutters[0]),
"the gutter is ragged:\n{plain}"
);
}
/// 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]
+2 -2
View File
@@ -121,9 +121,9 @@ pub fn dispatch(command: &Command, start: &Path, by: Attribution, sink: &mut Sin
} => cmd_comment(ticket, body, actor, *actor_from_git, start, by, sink),
Command::Campaign { command } => match command {
CampaignCommand::Add(args) => cmd_campaign_add(args, start, sink),
CampaignCommand::Ls { ids } => {
CampaignCommand::Ls { ids, state } => {
let worklane_dir = find_worklane_dir(start)?;
cmd_campaign_ls(&worklane_dir, *ids, sink)
cmd_campaign_ls(&worklane_dir, *ids, *state, sink)
}
CampaignCommand::Set(args) => cmd_campaign_set(args, start, sink),
CampaignCommand::Append(args) => cmd_campaign_append(args, start, sink),