Compare commits

..
5 Commits
Author SHA1 Message Date
Ansho ReiandClaude Opus 5 634a1f44c4 (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>
2026-09-15 16:42:21 +02:00
Ansho ReiandClaude Opus 5 3e732535f8 (bc86c85) Attribute a command typed at the board to the person, not the variable, and bump to 0.33.5
WORKLANE_ACTOR is set once in the environment an agent runs in, which is
right for an agent and wrong for the board: a person who exports it where
their own shell picks it up, the obvious way to configure it for the agents
on that machine, then moved a ticket with ':' and the board recorded the
move as the agent's.

Nothing but the reader can type that line, so the prompt asks for
--actor-from-git's precedence without the flag. An explicit --actor still
wins, which is how the reader puts somebody else's name on their own
keystrokes, and a machine with no git user configured reads unknown rather
than falling back to the variable, for the reason the flag does.

The attribution is a parameter of dispatch rather than a field the prompt
writes into what clap parsed: rewriting the arguments would need an arm per
entry-writing command, and the command added after it would be attributed
to the agent until somebody noticed. no_handler_decides_its_own_attribution
reads src for a handler naming an Attribution of its own, which the
compiler cannot catch because it compiles.

The same command typed in a shell is unchanged, which is what keeps a board
several agents write to saying which of them wrote what.

Also closes a code fence in the skill that e26e589 left open, duplicating
the mv --actor example under it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 16:23:24 +02:00
Ansho ReiandClaude Opus 5 a885f81da5 (952a9f8) Complete the verb, the statuses, the tags and the campaigns in the prompt, and bump to 0.33.4
With the ticket suggested, the rest of the line was still typed blind. The
prompt now completes everything fish does: the verb and the verbs of a
group, the five statuses, the tags the board carries, the campaigns a
codename resolves against, and relate --clear's three kinds.

`ticket_argument` becomes `argument_at`, which answers what a position
names rather than whether it is a ticket. The tables say Ticket, Campaign
or Tag; clap says the rest, so the verbs, the statuses, `set --clear`'s
fields and the `completions` shells are never written down twice. Only
`relate --clear` needed a table of its own: the flag takes a kind and then
a target, so possible values on it would refuse every target.

The row draws the longest opening every candidate agrees on, which is
exactly what the next tab takes. One rule for one candidate and for many: a
ticket position has only the selected card, so the rest of its id is drawn
as before; the five statuses agree on nothing, so nothing is drawn and tab
steps through them one press at a time.

The walk holds the line as it stood before the first press, not the list
and not the candidate the last press chose, so every press re-derives the
candidates and stepping cannot narrow them to what it just typed. Every
edit ends it, beside `refused` and for the same reason.

193f9be is not inherited: `tags set` is offered only the tags the
vocabulary declares, and `tags add` and both `--tags` that take the whole
list are offered nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 15:18:59 +02:00
Ansho ReiandClaude Opus 5 c714c73a75 (00a14e7) Suggest the selected ticket where a ticket argument goes, and accept it with tab, and bump to 0.33.3
The reader has the ticket selected, which is the whole reason to type a
command on the board rather than in a shell, so where the line is naming a
ticket the selected card's short id is drawn after the cursor in grey and
tab takes it into the line.

Where a ticket goes is completions.rs's answer, through a new
`ticket_argument` over the three tables the fish half is generated from. A
copy of the positions on the board would go wrong the next time a command
grew a ticket argument, and silently, since the tests guarding the first
copy would not read the second.

TICKET_FLAGS holds (command, flag) pairs now, the shape TAG_FLAGS already
had, and the `chown --clear` rule the fish block wrote out by hand is
generated from it. Only chown's --clear names a ticket: relate's takes a
kind and set's a field, and the flag alone cannot tell the three apart.

The suggestion is derived on every call rather than held on the Prompt, so
what the row draws and what tab takes are one answer, and it is offered
only with the cursor at the end of the line, while a card is selected, and
while the id still starts with what is typed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 15:01:15 +02:00
Ansho ReiandClaude Opus 5 a017f9002e (c680e24) Write a warning through a second stream on the sink, and bump to 0.33.2
check_blockers reported a blocker the board does not hold with eprintln!,
the one print site fa5662a left behind: a helper had no sink to reach, and
what it wrote was stderr rather than stdout. Harmless while main was the
only caller, and since 53ffb94 the command prompt runs the same handlers,
where stderr is the alternate screen with the columns on it. ratatui does
not repaint a cell it believes is unchanged, so the fragment stayed until
something else redrew them.

Sink carries two writers instead of one, because the CLI's two streams are
two: Sink::std hands the answer to stdout and an aside to stderr, so a
shell reads the same line on the same stream, and the integration test now
asserts that stderr whole rather than searching it. Sink::buffer holds its
warnings instead, and Board::run reads them back with Sink::warnings and
puts them above the answer on both outcomes -- a mv that warns about a
dangling blocker and is then refused by a real one wrote the aside first,
and it says why the refusal names one blocker and the ticket records two.

check_blockers and check_dependents both take the sink now, so their
refusals take the colour from it as well, rather than asking the process
about a stdout the board is not writing to.

no_handler_or_helper_reaches_a_print_macro walks src for the next print
site, each file cut at its own test module, since the rule is about every
future site rather than the one that broke.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 11:53:10 +02:00
20 changed files with 2170 additions and 148 deletions
Generated
+1 -1
View File
@@ -1563,7 +1563,7 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.33.1"
version = "0.33.6"
dependencies = [
"anyhow",
"assert_cmd",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "worklane"
version = "0.33.1"
version = "0.33.6"
edition = "2024"
[dependencies]
+2 -2
View File
@@ -21,7 +21,7 @@ Worklane is a local Kanban flow for agentic software development.
| `worklane campaign add` | Files a campaign in `.worklane/campaigns/` with `--title`, `--description`, `--codename` and `--owner`. A campaign has no status: its state is derived, open until every member is done. `--codename` is one word to call it by, `v1` or `beaver`, which is what the board draws on every card in it and what every command that takes a campaign will also resolve it by |
| `worklane campaign set <campaign>` | Replaces `--title`, which renames the file keeping the uuid, `--description` and `--codename`. At least one required. The way a campaign filed before codenames existed gets one, and the way a description filed with a typo in it gets fixed. Replacing a codename the campaign already has needs `--force`, since that is the word it is referred to by everywhere; setting the one it already has is a no-op either way. A description needs no `--force`: it is prose written to be revised. No `--clear` and no `--owner` |
| `worklane campaign append <campaign>` | Adds a paragraph to a campaign's description with `--description`, which is required. The other half of `campaign set --description`, so adding a line to a description does not mean retyping the rest of it. Repeat the flag for more lines within the one paragraph. Its own subcommand rather than the top-level `append`, which resolves a ticket |
| `worklane campaign ls` | Lists the campaigns as their short id, their codename, their title, how many members are done, and the state that count derives: `[open]` until every member is done and `[done]` after. A campaign nothing has been filed against reads `no members` and carries no state, being neither. `--ids` prints one per line as the id, a tab and the title, unstyled and without the counts, which read every ticket on the board, for a script or a completion |
| `worklane campaign ls` | Lists the campaigns as a table: when each was created, its short id, its codename, its title, how many members are done, and the state that count derives: `[open]` until every member is done and `[done]` after. A campaign nothing has been filed against reads `no members` and carries no state, being neither. The columns are padded to the widest value in each, so the rows line up whatever the titles are, and the codename is measured with the title rather than given a column of its own, since a campaign filed without one spends nothing on it. `--state` lists only the campaigns in one state, `open`, `done` or `empty` for one nothing has been filed against, and says so by name when nothing matches. `--ids` prints one per line as the id, a tab and the title, unstyled and without the counts, which read every ticket on the board, for a script or a completion; `--state` applies there too, and is the only thing that makes that path count members |
| `worklane campaign show <campaign>` | Shows a campaign and its members grouped by status, done included, since what is finished against what is left is the question a campaign asks |
| `worklane assign <campaign> <ticket>` | Puts a ticket in a campaign, the only command that writes the Campaign field. Campaign first and ticket second, after `chown`. A ticket is in at most one, so assigning one that already belongs somewhere moves it |
| `worklane tags` | Lists the tags the board carries as the tag, a tab and how many tickets carry it, one per line, unstyled and alphabetical. Case sensitive like `ls --tag`, so `bug` and `Bug` list separately and land next to each other. Every status, done included. The one command that answers what tags exist rather than what carries a tag already known |
@@ -33,7 +33,7 @@ Worklane is a local Kanban flow for agentic software development.
| Variable | Effect |
|----------|--------|
| `WORKLANE_ACTOR` | Who every entry the CLI writes is attributed to: a comment, and the `status`, `owner` and `tags` entries `mv`, `chown` and `set --tags` record. Set it once, in the environment an agent runs in, and every call it makes is attributed to it instead of to the git user of whoever's machine it is on. `--actor` overrides it per call and `--actor-from-git` lifts the git user over it per call (the two flags are refused together), an empty value counts as unset, and with neither supplied the author is the git user and then `unknown`. Free text, checked against nothing |
| `WORKLANE_ACTOR` | Who every entry the CLI writes is attributed to: a comment, and the `status`, `owner` and `tags` entries `mv`, `chown` and `set --tags` record. Set it once, in the environment an agent runs in, and every call it makes is attributed to it instead of to the git user of whoever's machine it is on. `--actor` overrides it per call and `--actor-from-git` lifts the git user over it per call (the two flags are refused together), an empty value counts as unset, and with neither supplied the author is the git user and then `unknown`. A command typed at the board's `:` prompt is attributed to the person instead, the git user and then `unknown`, never this variable: nothing but whoever is sitting at the board can type one. Free text, checked against nothing |
| `NO_COLOR` | Set and non-empty turns colour off, whatever the value, per no-color.org. Colour is also off when output is not a terminal, and when `TERM` is `dumb` or empty |
| `XDG_CONFIG_HOME` | Where `install-tool` looks for opencode's config root, `$XDG_CONFIG_HOME/opencode`, defaulting to `~/.config`. `install-skill` does not follow it: `~/.claude` is not an XDG path |
+7
View File
@@ -168,6 +168,7 @@ fields; a goal is a campaign.
```
worklane campaign ls
worklane campaign ls --state empty # filed against nothing, which is the one to ask about
worklane campaign show v1
worklane campaign add --title "..." --codename v1 --description "..."
worklane campaign set v1 --title "..." # or --description or --codename, on one already filed
@@ -183,6 +184,12 @@ tui is usable on a narrow terminal" is a campaign. "The tui tickets" is a tag.
them in a container says nothing that the tag did not already say.
- **Check what exists first.** `campaign ls` before proposing a new one, or you will
propose a second container for a goal that already has one.
- **`--state empty` finds the containers nothing was ever filed against.** A campaign with
no members is neither open nor done, so it is invisible to `--state open` and reads as
just another row in the full listing. Either the tickets for that goal exist and were
never assigned to it, which is an `assign` away, or the goal is one nobody is working,
which is worth saying out loud. A campaign cannot be discarded, so an empty one stays on
the board until it has members.
- **A ticket is in at most one campaign**, and `assign` moves it rather than adding a
second. So two proposed campaigns that overlap are really one proposal to take members
out of the other, and it has to say so.
+7 -2
View File
@@ -302,6 +302,7 @@ there is no such thing as a done campaign holding an open ticket.
worklane campaign add --title "First public release" --codename v1 \
--description "Everything that has to ship before the tag."
worklane campaign ls # every campaign, its codename, how far it has got
worklane campaign ls --state open # only the ones with work left: open, done, empty
worklane campaign ls --ids # id and title, tab separated, like ls --ids
worklane campaign show v1 # its body, then its members by status
worklane campaign set v1 --title "..." # replace the title, description or codename
@@ -417,8 +418,6 @@ is never needed. It cannot be combined with `--actor`, and a machine with no git
configured has nobody to name: the entry reads `unknown` rather than falling back to your
variable.
```
worklane mv 1b78a24 --status done --actor "Ansho Rei"
```
worklane mv 1b78a24 --status done --actor "Ansho Rei"
```
@@ -431,6 +430,12 @@ recognise.
On `chown`, `--actor` is not the user argument: `worklane chown alice 1b78a24` makes alice
the ticket's owner, and `--actor` says who made that change.
**An entry made from the board is the person's, not yours.** A command typed at the
board's `:` prompt is attributed to the git user of that machine whatever `WORKLANE_ACTOR`
is set to, because nothing but the person sitting at the board can type one. So an entry
can appear under a name no agent is configured with, and reading it as somebody else's
agent is reading it wrong: that is the person whose board it is, acting for themselves.
## Shell completions
```
+8 -1
View File
@@ -726,8 +726,14 @@ export const campaign_append = tool({
export const campaign_ls = tool({
description:
"List campaigns with how far each has got: id, codename or title, owner, and done members against total. Open until every member is done or discarded.",
"List campaigns with how far each has got: created, id, codename or title, and done members against total. Open until every member is done or discarded.",
args: {
state: tool.schema
.enum(["open", "done", "empty"])
.describe(
"Only campaigns in this state. A campaign with no members is neither open nor done, which is what 'empty' reaches.",
)
.optional(),
ids: tool.schema
.boolean()
.describe("Print only id and title, tab separated, one per line, for parsing.")
@@ -735,6 +741,7 @@ export const campaign_ls = tool({
},
async execute(args: Record<string, any>, context: ToolContext) {
const cmd = ["campaign", "ls"];
if (args.state) cmd.push("--state", String(args.state));
if (args.ids) cmd.push("--ids");
try {
return await run(cmd, context);
+5
View File
@@ -14,6 +14,11 @@ The container that groups tickets across the flow, and why its state is derived.
- **`Resolved` carries what `content_trim` cannot render from the file.** The relations block and the campaign cell both come from elsewhere on the board. A struct rather than two more parameters, so the next such field is one entry here instead of an edit at every call site
- `campaign show` lists **done** members, unlike `ls`, which leaves the done column out of its listing. What is finished against what is left is the whole question a campaign asks, so hiding half the answer is not an option. `ls --campaign` is the other way round: it is the ordinary board filtered, and keeps every rule `ls` already has
- `campaign ls` scans the status directories **once per campaign** to count members. That is a scan per row rather than one walk reused, and it is deliberate: the map-from-uuid version is worth writing when a board has enough campaigns to notice
- **`campaign ls --state` filters on `Standing::state()`, never on the counters.** The derived value has one definition, so a campaign reads `[open]` in the listing if and only if `--state open` lists it. `--state` and not `--status`: the word names one of the five ticket statuses everywhere else in the tool, and a campaign sits in no status directory. The third value is `empty`, matching the `None` an empty campaign derives, because 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 says so and repeats the value back, since a silent listing reads as the other empty case, a board with no campaigns on it
- **The filter reaches `--ids` as well, and is the only thing that makes that path count members.** `ls --ids` keeps its own filters, so this one keeps its. An unfiltered completion is as cheap as it was: `kept` returns true without reading a ticket when there is no filter to answer
- **The listing is a table, measured on the raw values and padded before anything is painted**, the rule `metadata_cells` follows. A column sized on a painted value counts its escape sequences towards its width, which is what tilts a table when colour is on and leaves it straight when it is off — the one combination an integration test running through a pipe can never see, which is why `the_campaign_table_stands_in_the_same_columns_coloured_or_not` renders both ways in one process and compares them with the escapes taken back 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 lines up is where one campaign's name ends and its progress begins, which is one field: the name is the codename and the title together
- **The created stamp is `format_created_at`'s, the same form `ls` prints**, rather than a second spelling of a date. An unparseable one is empty there and the column goes, exactly as it does for a ticket
- **The TUI got a card label and a frame, not a campaign tab.** 61879a4 decided it. A tab would have had to answer what its columns are, and a campaign groups *across* the flow rather than within one status, so the honest answer is the four statuses filtered — which is a filter on the board it already has rather than a fifth tab. So: a label on the card, a frame above the columns while one is selected, and `c` for the picker. The cost the earlier decision balked at, a campaigns read per reload, is paid once per project in `columns_of` and is what names the label; see [The Board View](tui-board.md)
- **A campaign is named by its codename on the board, and by its short id when it has none.** The uuid does not fit on a card and the title is a sentence, which is the gap `Codename` fills. `campaign_label` builds it in one place, as a `Cell`, so the CLI paints it and the board makes a span of it; the mark is `CAMPAIGN_MARK`, `~`, beside `#` for a tag
- **`campaign set` and `campaign append` are the only writers of a filed campaign's fields.** d637288 decided the command: a `set` rather than a flag on something narrower, because the file has more than one editable thing and the moment somebody wants to fix a typo in a title there would be a second command to design. `set` carries `--title`, which renames the file the way `set --title` does, `--description` and `--codename`; `append` carries `--description` alone. `campaign add` writing a field at creation is not a second writer, exactly as `add --title` and `set --title` coexist
+6 -1
View File
@@ -10,10 +10,15 @@ The generated half, the fish half, and what keeps the two honest.
- **The strongest completion check loads the script into fish and asks it for candidates.** `fish_offers_the_commands_the_statuses_and_the_values` in `tests/cmd_completions.rs` sources the generated script into a throwaway shell standing in a real board, with this build's directory on the front of PATH, and compares `complete -C` against the ticket and the tag it put there. Every other test in the file reads the script as text, which cannot tell a rule that fires from one whose condition stopped matching, and that is how a completion actually breaks. **Assert the values, not the flag names**: clap emits every option's name on its own, so `--tags` and `--blocked-by` are offered with every hand-written rule deleted; what the dynamic half adds is what comes *after* the flag. Two traps, both paid for once: the shell must have `fish_complete_path` emptied, or `complete -C` autoloads `~/.config/fish/completions/worklane.fish` and answers from whatever version wrote that, which is a guard that cannot fail; and the script is written beside the board rather than in it, since a rule that fires nothing falls back to listing the directory
- **`fish --no-execute` is the floor under that, not an oracle.** It catches a script that does not parse, quotes still open at the end of the file or an unclosed block. Measured, not assumed: an apostrophe interpolated into a `-d` description partway down re-balances against the next quote and parses, corrupting every rule in between while the check passes; the same apostrophe in the last rule reaches the end unbalanced and is caught. Only fish gets this, because only fish gets a hand-written half
- **The rule counts in the completion tests are hardcoded on purpose.** The walkers go clap → list and never see an entry naming something that does not exist, so a bogus pair in `TAG_FLAGS` is caught by `every_tag_rule_takes_the_annotation_as_its_description` counting one rule too many. Deriving that number from the lists it checks would grow with the bogus entry and pass. The `seen` totals in the walkers are hardcoded for the mirror reason, and both carry the note
- **The five completion lists are kept honest by tests** that walk the clap definition and fail on an argument left out of them. `TICKET_COMMANDS` and `TICKET_SECOND_COMMANDS` by position, `TICKET_FLAGS`, `CAMPAIGN_COMMANDS`, `CAMPAIGN_NESTED_COMMANDS`, `CAMPAIGN_FLAGS` and `TAG_FLAGS` likewise, the last against the test-local `TAG_LIST_FLAGS` and `TAG_NEW_COMMANDS` for the tag arguments that deliberately get no rule. The walk is one function, `every_argument`, since the tests differ only in the id they look for. Each also asserts *how many* it found, so a walker that stopped finding arguments fails rather than passing every assertion by never running them
- **The completion lists are kept honest by tests** that walk the clap definition and fail on an argument left out of them. `TICKET_COMMANDS` and `TICKET_SECOND_COMMANDS` by position, `TICKET_FLAGS`, `CAMPAIGN_COMMANDS`, `CAMPAIGN_NESTED_COMMANDS`, `CAMPAIGN_FLAGS` and `TAG_FLAGS` likewise, the last against the test-local `TAG_LIST_FLAGS` and `TAG_NEW_COMMANDS` for the tag arguments that deliberately get no rule. The walk is one function, `every_argument`, since the tests differ only in the id they look for. Each also asserts *how many* it found, so a walker that stopped finding arguments fails rather than passing every assertion by never running them
- **A campaign is named in three shapes and a tag in one**, which is why the lists are not one list: a campaign is `assign`'s first positional, the first argument of `campaign show` and `campaign set`, and `ls --campaign`'s value, and each needs a different fish rule. A tag is only ever an option value, and its values come from a different command
- **`TICKET_FLAGS` holds pairs, the command and the flag, and every ticket rule in the fish half is generated from it.** Three commands carry a `--clear` and each takes something different: `chown`'s names the ticket, since with no user to give there is no positional for it; `relate`'s takes the kind and then the target; `set`'s takes a field name clap already offers. So the command is half of the fact, and a list of bare flag names could only be scoped by hand, which is what the `chown --clear` rule used to be. `every_ticket_flag_is_a_real_option` walks each pair against the command it names, which a flat list could not do
- **The lists answer the board as well as the shell.** `argument_at` reads every one of them to say what the argument at a given index of a typed line names — a ticket, a campaign, a tag, or a fixed list it takes off clap — which is what the command prompt completes against, see [tui-prompts.md](tui-prompts.md). Position is counted there exactly as it is counted here, so the two cannot come to disagree about `mv --status done <ticket>`; a second table on the board would be a copy the tests above never read. The values are the one half that is not shared: fish runs `worklane ls --ids` and the board reads the rows the tab already holds
- **`TAG_FLAGS` holds pairs where the others hold names**, because the two options that take one tag are spelled differently: `ls --tag` filters on one and `append --tags` adds them, so a single rule naming both would tell fish that each command accepts the other's flag. One rule per pair, generated in `fish_dynamic`. `add --tags` and `set --tags` are in the test's `TAG_LIST_FLAGS` instead and get no rule: they take the *whole* list, so the token at the cursor is `bug,tui` and fish replaces a token entire, which would throw away what is already typed. The test walks both `tag` and `tags`, so the next one has to say which of the two it is
- **A `ValueEnum` is never listed twice, and `argument_at` is why the fish half's two hand-written value lists are the only ones.** clap emits the possible values of an *option*, so `mv --status` and `set --clear` need nothing here and the board reads them off the same definition with `Arg::get_possible_values`. The `ls` status and the `completions` shell are positionals, which the fish generator emits nothing for, so those two are written into the block from the enums — and the board reaches them through `get_positionals`, which needs no `Command::build` the way `get_index` would
- **`RELATION_KIND_FLAGS` is the one position clap cannot answer for.** `relate --clear` takes a kind and then a target, two values of different kinds under one flag, so possible values on it would refuse every target. Both renderers therefore say so themselves: the fish rule lists `RelationKind::ALL` and the table names the pair
- **`ls --ids` is the machine-readable listing**, and one of the three outputs in the tree meant to be parsed: the short id, a tab, the title, unstyled. Two fields because fish reads what follows a tab as the description and a script reads `cut -f1`. It includes done, which the decorated listing leaves out, because a completion has to be able to name a finished ticket, and it skips a missing status directory rather than refusing, because an error printed over a shell prompt is worse than no candidates. The filters still apply, and an unknown `--campaign` is still refused
- **A flag's possible values are read off the command that *holds* the flag, nested or not.** `argument_at` resolves the group's child when the second word names one, so `campaign ls --state` reaches `ls`'s own arguments rather than `campaign`'s, which carry no such flag. Without that the prompt offered nothing where fish offered the three values, and the promise that a `ValueEnum` added anywhere is typeable on the board the day it is added held only for a top-level command
- **`campaign ls --ids` is the same flag and the same two fields for the other object**, and it deliberately skips the member counting the decorated listing does: `members()` reads every ticket on the board, and the caller here is a shell filling in candidates on a keypress. It also prints nothing on an empty board, where the decorated listing prints a sentence, because a sentence offered as a candidate is worse than no candidates
- **`worklane tags` is the third, and it is a command rather than a mode on `ls`.** Two reasons: `ls --tag <tag>` answers what carries a tag and cannot answer what tags exist, which is the question a grooming sweep starts from, and a `--tags` beside a `--tag` is one letter from a filter that means something else. Alphabetical and case sensitive, matching the filter, so `bug` and `Bug` list separately and land next to each other, which is where a near-duplicate is spotted. Every status, done included: a tag that has fallen out of use is still part of what the vocabulary has been. `assets/PLAN.md` used to tell the agent to count tags with a `show` per ticket, and now points here
+2
View File
@@ -5,6 +5,8 @@ Who an entry is attributed to, and what the log does and does not record.
## Who Wrote an Entry
- **Identity is supplied, not detected.** Every option that needs no cooperation fails: a harness variable such as `CLAUDECODE` names the tool rather than the instance and breaks across versions, walking the parent process is platform specific and also only names the harness, and a terminal check separates interactive from not, which a human piping output is too. So the actor is `WORKLANE_ACTOR`, set once per session, with `--actor` as the per-call override
- **Precedence: flag, then `WORKLANE_ACTOR`, then `get_git_user()`, then `unknown`.** With `--actor-from-git` and no explicit value the git user is lifted *above* the variable rather than added beneath it — the flag says attribute this to the human, and a machine with no git user configured reads `unknown` instead of quietly attributing back to the agent. An explicit `--actor` wins outright either way. `resolve_actor` is the only caller of `get_git_user` for an entry's author, and every entry the CLI writes goes through it. The halves are separate pure functions, `session_actor` (the variable alone now) and `entry_actor`, tested without touching the process environment for the reason `colors_wanted` is split that way
- **A command typed at the board is the person's, not the session's.** `dispatch` takes an `Attribution`, `Session` from `main` and `Person` from the command prompt, and `Person` asks for `--actor-from-git`'s lift without the flag: nothing but the reader can type that line, and a person who exported `WORKLANE_ACTOR` where their own shell picks it up — the obvious way to configure it for the agents on that machine — would otherwise watch their own `mv` recorded as the agent's. An explicit `--actor` still wins there, which is how the reader puts somebody else's name on their own keystrokes, and with no git user configured the entry reads `unknown` rather than falling back to the variable, for the reason the flag does. `entry_actor` takes it beside `from_git` and the two are one branch, since `--actor-from-git` typed at the prompt asks for what the prompt does anyway
- **The attribution is a parameter of `dispatch`, not a field the prompt writes into the parsed arguments.** Rewriting what clap produced would need an arm per entry-writing command, and the command added after it would be attributed to the agent until somebody noticed. A parameter is one edit for both callers, and `no_handler_decides_its_own_attribution` reads `src` for a handler naming an `Attribution` of its own, which the compiler cannot catch because it compiles
- **The variable half is cached in a `OnceLock` and the git user in another**, the way `should_use_colors` is: neither input can change mid-run, and the git user costs a subprocess. Two caches rather than one is the whole point: baking the git user into the session's answer would make `--actor-from-git` read whatever the run's *first* call produced, since with the variable set that call never fetched git at all. `entry_actor` takes the git user as a closure so the subprocess is not run when something ahead of it already answered
- **The two flags are refused together at parse time**, clap `conflicts_with`: both answer who the entry is attributed to, and last-wins would be a silent answer to a contradictory call. `every_actor_command_takes_actor_from_git` walks the clap definition so the pair travels together onto any command that grows an `--actor`
- An **empty `WORKLANE_ACTOR` counts as unset**, the convention `colors_wanted` follows for `NO_COLOR`, so a wrapper script can clear an inherited one. Whitespace counts the same, since a shell quoting a missing value writes one
+1 -1
View File
@@ -26,7 +26,7 @@ Recording an edge between two tickets, and drawing the block that reports them.
- **A dependent may stand level with its blocker but never ahead of it.** `blocks_move` is the rule: the move is refused exactly when the status moved into is further down `Status::ALL` than the blocker's own, so a blocker in reviewing lets the dependent be committed and reviewed and gates only done. The first shape of this refused every move while a blocker was not done, which read as one rule rather than a table of transitions but stopped the work it was meant to order: a pair is usually built and reviewed together, and waiting for the blocker to land cost a `-f` on every move and left the rule enforcing nothing
- **A finished blocker is answered by `is_open`, and a discard target by name.** Done landed and discarded never will, so neither holds anything up, and that is the one place the board decides what finished means. Discarded is last in `Status::ALL` for the stamp rule's sake, so a comparison of positions alone would read a discard as the furthest move of all: `blocks_move` returns false for it outright, since abandoning a ticket is not carrying it along the flow and owes nothing to what it waits on. A status that is not one of the five holds up every move, the direction `is_open` already takes with such a value: a fault surfaces rather than quietly letting a dependent past
- **The blocker check runs on every move**, after the already-in-that-status return and behind `force`, with the target status passed in as what decides the answer. A move to the status the ticket is already in is not a move, so it is not refused. A backward move never is either, being at or behind everything, and it needs `-f` for its own reason anyway. `-f` bypasses three rules, which is the right home for it: each one is a deliberate override of something the board would otherwise keep true
- **A blocker that is not on the board warns and allows the move.** Refusing would wedge the ticket with no way out but `-f`, and a uuid nothing carries is a bookkeeping fault rather than a dependency. The refusal names **every** blocker still behind the move and the status it was for, since advancing the one that happened to be printed would leave the ticket held up, and a ticket refused the next stage after moving once is otherwise told nothing about what changed. A blocker further along than the move is left out of the list entirely: a dependent told to wait for work already ahead of it has nothing to act on
- **A blocker that is not on the board warns and allows the move.** Refusing would wedge the ticket with no way out but `-f`, and a uuid nothing carries is a bookkeeping fault rather than a dependency. The warning goes through the sink `check_blockers` is handed, which is why a guard that says nothing on the happy path takes one at all: the same helper runs from the board's command prompt, where the process's stderr is the alternate screen. See [The Command Prompt](tui-prompts.md). The refusal names **every** blocker still behind the move and the status it was for, since advancing the one that happened to be printed would leave the ticket held up, and a ticket refused the next stage after moving once is otherwise told nothing about what changed. A blocker further along than the move is left out of the list entirely: a dependent told to wait for work already ahead of it has nothing to act on
- Left out on purpose: removing a relation, which 4179958 assigns to 74904dc. The blocked marker on the card landed in b8ce18c, and it cost no scan of the board: the blockers ride along on the read that already builds the cards. It asks `blocks_move` about the status one stage ahead of the column the card is in, so the mark means the card cannot advance and not that a dependency was ever recorded. See [The Board View](tui-board.md)
## The Relations Block
+25 -1
View File
@@ -19,13 +19,15 @@ The three input modes on the board and the key that copies an id off it.
## The Command Prompt
- **`prompt: Option<Prompt>` is the whole mode**, the shape `search` and `detail` use: open and content cannot disagree, and closing it leaves nothing to reset. `Prompt` carries the line, the cursor as a byte offset into it, and `refused`, which is `Search::missed` with something to say
- **`Board::prompt_key` is third in the pre-dispatch**, beside `search_key` and `picker_key` and on the same contract: while a command is being typed `q` is a letter, `d` leaves the columns alone and `tab` stays out of the project tabs, and `ctrl-c` is the one key declined. It takes a `Size` for enter's sake: running a command reloads the board and then has to bring the ticket it moved back into view, which is the measurement `follow_selection` takes. Only one of the two prompts can be open at once: `:` is reachable from the action arms alone, and while either has the keyboard the other's key is a character in a line
- **`esc` and `enter` are the mode's own keys and are answered in `prompt_key`; everything else belongs to the line and goes to `Prompt::key`.** That is also what keeps the borrow straight, since closing the prompt takes the whole board and editing takes only the prompt. Left, right, home, end, backspace and `ctrl-w` behave as they do in a shell, and `ctrl-w` eats the separators behind the cursor before the word behind those, so one press at the end of `mv 1b78a24 ` takes the id. There is deliberately no `tab`: suggesting the selected ticket is 00a14e7, and until then it is a key that must not reach the tabs
- **`esc` and `enter` are the mode's own keys and are answered in `prompt_key`; everything else belongs to the line and goes to `Prompt::key`.** That is also what keeps the borrow straight, since closing the prompt takes the whole board and editing takes only the prompt. Left, right, home, end, backspace and `ctrl-w` behave as they do in a shell, and `ctrl-w` eats the separators behind the cursor before the word behind those, so one press at the end of `mv 1b78a24 ` takes the id. `tab` is the mode's too, for the reason the recall walk is: what it takes is made of the selected card and the line is only where it lands
- **The grammar is clap's, with nothing restated.** The line is tokenised by `split_line`, the binary's own name goes in front, and the arguments go to the same `Cli` definition the shell reaches, so a flag added to a command is typeable here the day it is added. Through `Cli::command().try_get_matches_from_mut` rather than `try_parse_from`, for what the matches give back: `command_name` walks the subcommands to name what resolved (`campaign show`, not `campaign`) instead of a `match` over every variant, which would be a second list of every verb the CLI has and one that goes stale silently
- **`refused` is cleared by an edit and not by a movement.** The message is about the line, and moving the cursor does not change the line. `Prompt::key` clears it in the three arms that write to the line
- **A line that ends inside a quote never reaches clap.** That is what `Unclosed` is for: a grammar complaint about a sentence nobody finished describes the wrong thing. Enter on an empty line, or one of nothing but separators, closes the prompt with nothing said, the way `esc` does — the bare form of the CLI opens a board and there is one on the screen
- **Enter runs it, through `main.rs`'s `dispatch` and never through a handler this file names.** That match is the one mapping from a parsed command to the function that performs it: `main` calls it with its own stdout and the working directory, `Board::run` calls it with a buffer and the selected tab's root. A second copy inside `tui.rs` would drift the first time a command was added, and it would drift *silently*, since both halves go on compiling. The match is exhaustive so a new verb cannot fall into an `_` arm and do nothing, and `main_and_the_prompt_run_one_dispatch_table` reads both files as text to pin it. Only `tui` is matched outside the table, in `main`, because the board is that table's caller rather than an entry in it; reached from the prompt it is refused in those words
- **What it writes is attributed to the person at the board**, through the same `dispatch` parameter, because a line nothing but the reader can type is the reader's action. The rule and its precedence are in [history.md](history.md), which owns attribution; what belongs here is that the board is the one caller that asks for it
- **`from_arg_matches` on the same matches gives `run` the typed values.** One parse, two readings: `command_name` walks the subcommands to name what resolved and `from_arg_matches` reconstructs the `Cli`. A `match` over every `Command` variant to get one or the other would be a second list of every verb the CLI has
- **The handler's own words are what the board reports, word for word.** Those messages are written for a person already, and a second set kept here would go stale the first time one of them changed. The sink is a buffer, so the words come back as text and the board styles them; it is plain for the same reason `Detail` holds spans, since a ratatui paragraph prints an escape rather than obeying it. An error never goes through a sink at all — `color_text` asks the *process* about its stdout, which under the board answers yes about a terminal the message is not going to — so `error_lines` runs `without_escapes` over it and puts each cause on a line of its own
- **A warning goes through the sink's second stream, and never through `eprintln!`.** `Sink` carries two writers because the CLI's two streams are two: `Sink::std` hands the answer to stdout and an aside to stderr, and a shell has to go on reading the same line on the same stream. Under the board neither is a stream at all — stderr is the alternate screen with the columns on it — so `Sink::buffer` *holds* its warnings and `Board::run` reads them back with `Sink::warnings` and puts them above the answer, on both outcomes: a `mv` that warns about a dangling blocker and is then refused by a real one wrote the aside first, and it is the half that says why the refusal names one blocker and the ticket records two. That is c680e24: one `eprintln!` in `check_blockers` outlived fa5662a because a helper had no sink to reach, and ratatui does not repaint a cell it believes is unchanged, so the fragment stayed on the columns until something else redrew them. `no_handler_or_helper_reaches_a_print_macro` walks `src` for the next one, each file cut at its test module, so a print site in a module added tomorrow is caught the day it is added
- **A handler that errors leaves the prompt open with the line intact.** The usual cause is an ambiguous id, and the fix is two more characters rather than the whole line retyped from `:`. Ambiguity is an `Err` carrying the candidates, not a print and an `exit`, which is what makes it safe to reach from here at all
- **The reload after a command is unconditional, and runs whether it failed or not.** `tick` reloads on the digest, which is right for a change made in another pane and needless latency for one the board just made: the reader would watch their own `mv` take up to a poll interval to appear. Either way, because a handler that failed part way through has still written
- **The selection is restored by uuid across that reload, never by index.** `mv` puts the card in another column, `set --title` renames its file, and a filter can drop it out of view entirely, so the slot is not the ticket. `Board::reselect` has three answers: the card is in a drawn column and the selection goes to it; it is on the board but in a column the rotation is hiding, which is where `--status done` lands by default, so the notice says where it went and which key shows it; or the filter no longer holds it, which is said too, since a card vanishing from under the highlight reads as a bug in the board
@@ -45,6 +47,28 @@ The three input modes on the board and the key that copies an id off it.
- **A failed write is silent, and an unreadable file is an empty recall.** The line is in memory either way, so the walk works for the run on a board whose folder cannot be written, and a board with no history yet is the ordinary case rather than something to say. A notice about a history file would be about the one thing the reader did not ask for
- **`.wlhistory` is not in `digest`.** Appending to it must not read as the tree moving, or every command typed would provoke a reload of every board on top of the one `run` already does
## The Prompt's Completion
- **The reader has the ticket selected, which is the whole reason to type a command on the board rather than in a shell.** So where the line is naming a ticket, the selected card's short id is drawn after the cursor and `tab` takes it into the line. Retyping seven characters off the card in front of you is the friction the prompt exists to remove
- **Where a ticket goes is `completions.rs`'s answer, not a table written here.** `argument_at` reads `TICKET_COMMANDS`, `TICKET_SECOND_COMMANDS` and `TICKET_FLAGS`, which `no_ticket_taking_subcommand_is_missing` and `every_ticket_flag_is_a_real_option` keep honest against clap's own definition, and the campaign and tag lists beside them. A second copy of the positions on the board would go wrong the next time a command grew a ticket argument, and it would go wrong *silently*, since the test guarding the first copy would not read the second
- **The ticket is not always the first argument, which is what a naive version gets wrong.** `chown alice <ticket>` and `assign v1 <ticket>` put it second on purpose, `relate x --blocked-by <ticket>` puts it in a flag, and `chown --clear <ticket>` does too, since with no user to give there is no positional for it. Nothing is offered where the argument is something else: `relate --clear` wants a kind, `set --clear` wants a field name, and `chown`'s first argument is a user
- **Position is counted, exactly as the fish half counts it**, so `mv --status done <ticket>` is not recognised: the ticket is `mv`'s first positional and the third argument on the line. That is the fish rules' limit as well, and one table answering both is worth more than two tables disagreeing about the corner
- **`TICKET_FLAGS` holds pairs, command and flag, where it used to hold bare flag names.** Three commands carry a `--clear` and only `chown`'s names a ticket, so the command is half of the fact. It also took the last hand-written ticket rule out of the fish block: every one of them is generated from the table now, and `every_ticket_flag_is_a_real_option` walks each pair against the command it names
- **It is derived on every call and held nowhere.** `Board::completion` is asked once by the draw and once by `tab`, so what is on the row and what the key takes cannot disagree, and there is no list to go stale when the line is edited or the board reloads under it. That is also what "any other key drops it" means: nothing is dropped, because nothing was kept
- **Only with the cursor at the end of the line.** The suggestion is drawn after the cursor and `tab` inserts it there, so with a command continuing past the cursor both would land in the middle of something already typed. A shell's own suggestion keeps the same rule
- **Only while a candidate still starts with what is typed**, and what is drawn is the rest of it rather than the whole. An offer that no longer matches the argument under it describes nothing, and once the whole of it is typed there is nothing left to add
- **Nothing with no card under the selection.** On the frame the selection is on a campaign or a tag, and neither is a ticket: `y` copies what the frame names there, and this deliberately does not
- **Everything else worklane can name is completed the same way**, which is what makes it one mechanism rather than a ticket suggestion with four more bolted on. `Argument` says what a position takes — a ticket, a campaign, a tag, or a fixed list — and `Board::candidates` says what the board currently holds of it. The verbs and the enum values are clap's own, so a command, a status, a shell or a clearable field added anywhere is typeable here the day it is added, and the campaigns and the tags are the tab's own rows, rebuilt at every reload beside the columns and drawn by the `c` and `t` pickers. **Nothing here reads the tree**: a keypress that went to disk would be a second source for what is already in memory
- **A campaign is offered by codename, and by its short id where it has none.** The codename is what the board draws on every card in the campaign and the shortest thing that addresses it; a campaign without one is labelled by its short id in both renderers, and leaving it out would hide it from the only place a reader can reach it by typing
- **`tags set` is offered only the declared tags.** It changes what a declared tag means and refuses one the vocabulary file does not declare, so the carried-but-undeclared ones are exactly the values it rejects. That is 193f9be in the fish half, which reads one listing for both, and the prompt does not inherit it. `tags add` gets nothing for the mirror reason, and neither `--tags` that takes the whole list does, since one tag offered into `bug,tui` is not what the field asked for
- **The clap definition is rebuilt on every call**, at 32µs in release against a board that redraws four times a second. A definition cached beside the board would be a second copy of what `Cli::command()` already answers; the fish half spends 2.5ms per keypress running worklane itself for the same values
- **What is drawn is the longest opening every candidate agrees on, which is exactly what the next `tab` takes.** One rule for one candidate and for many: a ticket position has only the selected card, so the rest of its id is drawn; the five statuses agree on nothing, so nothing is drawn and `tab` steps through them instead. The row never shows something a press would not do
- **`tab` again steps through the candidates in place, and wraps.** A shell does the same and it needs no list drawn over the columns, which is the trade — the board behind the prompt is what the reader is reading. Wrapping loses nothing typed, unlike the recall's walk, because every candidate still starts with the stem the walk was built from, which is why there is no `pending` here
- **Each press rebuilds the row from the line as it stood before the first**, so the candidates are read fresh every press and the only thing `Completing` holds is that line and how many presses have landed. Holding the list would be a copy going stale between two presses; holding the candidate the last press chose would narrow the list to it, and the walk would step once and stand still
- **Every edit ends the walk**, beside `refused` and for the same reason: the walk is about one argument and a line that has changed is a different argument. What the last press put on the row stays there, which is what makes `tab` then a letter the ordinary way to take a candidate
- **Nothing is drawn while a walk is on the row.** What is there is a whole candidate already, and a second offer drawn against it would read as part of the same word
- **Grey, which is what the palette already spends on a value that is not one.** It is not in the line until `tab` puts it there, and the reader has to tell the two apart at a glance. It takes what the line leaves of the field rather than a field of its own, so a long command loses the offer instead of pushing `esc` and `enter` off the row. The terminal cursor sits on its first cell, which is where the cursor already was
- **The row does not name `tab`.** The prompt names its two mode keys and no more — `ctrl-w`, the arrows and home and end are unnamed there as well — and the suggestion under the cursor is its own affordance
## Splitting a Typed Line
- **`split_line` is the whole module, and it knows nothing about `Board`.** The command prompt reads one string and clap reads an argv, so `comment 1b78a24 the offset was never passed` has to be tokenised before anything can parse it: split on whitespace it is five arguments and `comment` takes two. A pure function over the line and the cursor is what makes every rule reachable from a unit test, and it is in a file of its own rather than in `tui.rs`, which is eleven thousand lines already
- **The rules are the shell's, because that is what the prompt promises**: the line is spelled there exactly as it is spelled in the shell. Runs of whitespace separate arguments, single and double quotes group one, a backslash escapes the next character *except* inside single quotes where it is a backslash, and an explicitly empty `''` is an argument that exists and is empty — which is what `--title ""` being a usage error rather than a silent clear depends on. A leading hyphen is not special here: whether `--foo` is a flag or the text of a criterion is clap's question, and `PROSE` already answers it
+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
+383 -33
View File
@@ -39,8 +39,19 @@ pub const TICKET_COMMANDS: [&str; 8] = [
/// campaign, and neither is completed.
pub const TICKET_SECOND_COMMANDS: [&str; 2] = ["chown", "assign"];
/// Options whose value is a ticket, as `relate` takes three of.
pub const TICKET_FLAGS: [&str; 3] = ["blocked-by", "regression-of", "relates-to"];
/// Options whose value is a ticket, as the command that takes it and the flag's long name.
///
/// Pairs rather than the flat list this was, for the reason [`TAG_FLAGS`] holds pairs: the
/// commands spell their flags differently and one of the spellings is shared. `relate`'s
/// three take a ticket, `chown --clear` takes one because there is no user to give it, and
/// `set --clear` takes a field name and `relate --clear` a relation kind — so a list of
/// bare flag names would offer tickets to those two as well.
pub const TICKET_FLAGS: [(&str, &str); 4] = [
("relate", "blocked-by"),
("relate", "regression-of"),
("relate", "relates-to"),
("chown", "clear"),
];
/// Subcommands whose first positional is a campaign.
///
@@ -90,6 +101,166 @@ pub const TAG_FLAGS: [(&str, &str); 2] = [("ls", "tag"), ("append", "tags")];
/// `no_tag_taking_option_is_missing` makes somebody decide.
pub const TAG_NESTED_COMMANDS: [(&str, &str); 1] = [("tags", "set")];
/// Options whose first value is a relation kind.
///
/// `relate --clear` alone, and it is a list rather than a line in [`argument_at`] for the
/// reason every other position is: what an argument names belongs beside the tables that
/// answer the same question about the rest of them. It cannot come off clap the way a
/// status does, which is why it is here at all — the flag takes a kind and then a target,
/// two values of different kinds under one name, so possible values on it would refuse
/// every target.
pub const RELATION_KIND_FLAGS: [(&str, &str); 1] = [("relate", "clear")];
/// What an argument of a typed line names, where worklane can answer what goes there.
///
/// The board's command prompt completes against this: the tables above say *what* the
/// position takes and the prompt says what the board currently holds of it. A ticket and a
/// campaign and a tag are all "a word off the board" to clap and three different questions
/// to the reader, which is why this is an enum rather than a candidate list — the values
/// live where the board is and the positions live here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Argument {
/// A ticket on the board. One candidate, the card the reader has selected.
Ticket,
/// A campaign, which is named by its codename and drawn by it on every card it holds.
Campaign,
/// A tag. `declared` is `tags set`'s: it changes what a declared tag means and refuses
/// one the vocabulary file does not declare, so offering a carried-but-undeclared tag
/// there would offer exactly the values the command rejects. That is 193f9be in the
/// fish half, and this is the prompt not inheriting it.
Tag { declared: bool },
/// Values the tool itself holds: the subcommand names at a verb position, the possible
/// values of an argument clap built from a `ValueEnum`, and the relation kinds.
///
/// Read off the clap definition rather than written out, so a command, a status or a
/// clearable field added anywhere is typeable on the board the day it is added.
Fixed(Vec<String>),
}
/// What the argument at `index` of a typed line names, `index` counting from the verb at 0,
/// or nothing where worklane has nothing to offer.
///
/// The tables above are what answer it, reached rather than restated: a second copy of the
/// positions on the board would go wrong the next time a command grew a ticket argument, and
/// it would go wrong silently, since the tests that keep these honest against clap would
/// not read the copy.
///
/// Position is counted rather than inferred, exactly as the fish half counts it, so
/// `mv --status done <ticket>` is not recognised: the ticket is `mv`'s first *positional*
/// and the third argument on the line. That is the fish rules' limit too, and one answer
/// for both is worth more than two that disagree about the corner.
///
/// The clap definition is rebuilt on every call, at 32µs in release, and the caller is a
/// board that redraws four times a second: a definition cached beside the board would be a
/// second copy of what `Cli::command()` already answers, for a cost nothing can measure.
/// The fish half spends 2.5ms per keypress running worklane itself for the same answers.
pub fn argument_at(args: &[String], index: usize) -> Option<Argument> {
let cli = crate::command::Cli::command();
// The verb itself, which is every subcommand the tool has. Hidden ones are left out:
// they are not in the help either, and a candidate nobody can read about is one a
// reader has to go and look up.
if index == 0 {
return Some(Argument::Fixed(subcommand_names(&cli)));
}
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("--")) {
if TICKET_FLAGS.contains(&(verb, flag)) {
return Some(Argument::Ticket);
}
if CAMPAIGN_FLAGS.contains(&flag) {
return Some(Argument::Campaign);
}
if TAG_FLAGS.contains(&(verb, flag)) {
return Some(Argument::Tag { declared: false });
}
if RELATION_KIND_FLAGS.contains(&(verb, flag)) {
let kinds = RelationKind::ALL.iter().map(|kind| kind.flag().to_string());
return Some(Argument::Fixed(kinds.collect()));
}
// 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 = holder?
.get_arguments()
.find(|arg| arg.get_long() == Some(flag))?;
return fixed(arg);
}
// The positionals, at the index each table records.
match index {
1 if TICKET_COMMANDS.contains(&verb) => return Some(Argument::Ticket),
1 if CAMPAIGN_COMMANDS.contains(&verb) => return Some(Argument::Campaign),
2 if TICKET_SECOND_COMMANDS.contains(&verb) => return Some(Argument::Ticket),
_ => {}
}
let group = group?;
// The verb of a group, `campaign show` and `tags set`, which is a subcommand name
// exactly as the top-level verb is.
if index == 1 && group.has_subcommands() {
return Some(Argument::Fixed(subcommand_names(group)));
}
// And the first argument of one, which is where a campaign and a declared tag are named.
if index == 2
&& let Some(child) = args.get(1).map(String::as_str)
{
if CAMPAIGN_NESTED_COMMANDS.contains(&(verb, child)) {
return Some(Argument::Campaign);
}
if TAG_NESTED_COMMANDS.contains(&(verb, child)) {
return Some(Argument::Tag { declared: true });
}
}
// And whatever else the positional itself knows, which is the `ls` status and the
// `completions` shell: both are `ValueEnum`s that the fish generator has to list by
// hand, because it emits possible values for an option and none for a positional.
fixed(group.get_positionals().nth(index - 1)?)
}
/// The names a command answers to, hidden ones left out.
fn subcommand_names(command: &clap::Command) -> Vec<String> {
command
.get_subcommands()
.filter(|sub| !sub.is_hide_set())
.map(|sub| sub.get_name().to_string())
.collect()
}
/// The possible values of one argument, or nothing for an argument that takes free text.
///
/// `get_positionals` and `get_long` both read what the derive wrote, so nothing here needs
/// the command built the way `get_index` would.
fn fixed(arg: &clap::Arg) -> Option<Argument> {
let values: Vec<String> = arg
.get_possible_values()
.iter()
.filter(|value| !value.is_hide_set())
.map(|value| value.get_name().to_string())
.collect();
(!values.is_empty()).then_some(Argument::Fixed(values))
}
pub fn generate(shell: Shell, out: &mut dyn io::Write) -> io::Result<()> {
let mut command = crate::command::Cli::command();
clap_complete::generate(shell, &mut command, "worklane", out);
@@ -107,7 +278,16 @@ pub fn generate(shell: Shell, out: &mut dyn io::Write) -> io::Result<()> {
fn fish_dynamic() -> String {
let ticket_commands = TICKET_COMMANDS.join(" ");
let ticket_second_commands = TICKET_SECOND_COMMANDS.join(" ");
let ticket_flags = flag_list(&TICKET_FLAGS);
let ticket_flags = TICKET_FLAGS
.iter()
.map(|(command, flag)| {
format!(
"complete -c worklane -n '__worklane_command_is {command}' -l {flag} \\\n \
-x -a '(worklane ls --ids)'"
)
})
.collect::<Vec<_>>()
.join("\n");
let relation_kinds = RelationKind::ALL
.iter()
.map(|kind| kind.flag())
@@ -207,17 +387,19 @@ complete -c worklane \
-n '__worklane_first_arg_of {ticket_commands}; or __worklane_second_arg_of {ticket_second_commands}' \
-a '(worklane ls --ids)'
# `relate` takes its targets as option values, so they are completed by flag rather
# than by position.
complete -c worklane -n '__worklane_command_is relate' {ticket_flags} \
-x -a '(worklane ls --ids)'
# The options whose value is a ticket, one rule per command so that a flag is offered
# only under the command that has it. `relate` takes its three targets this way rather
# than by position, and `chown --clear` names the ticket in the flag because with no user
# to give there is no second positional to put it in. Its `--clear` is scoped like every
# other: `set` has one that takes a field name, which clap already offers.
{ticket_flags}
# `--clear` is the one flag here whose first value is not a ticket, so it is not in
# `TICKET_FLAGS`: it takes the kind and then the target, and offering a board listing where
# the kind goes would be offering values it refuses. The kinds come from `RelationKind`
# rather than being spelled again. The target gets no rule at all, deliberately: fish
# completes the value after the flag, and the case this flag exists for is a target whose
# ticket is gone, which no listing of the board can offer.
# `relate --clear` is the one `--clear` whose first value is not a ticket, which is why
# that pair is not in `TICKET_FLAGS`: it takes the kind and then the target, and offering a
# board listing where the kind goes would be offering values it refuses. The kinds come
# from `RelationKind` rather than being spelled again. The target gets no rule at all,
# deliberately: fish completes the value after the flag, and the case this flag exists for
# is a target whose ticket is gone, which no listing of the board can offer.
complete -c worklane -n '__worklane_command_is relate' -l clear -x -a '{relation_kinds}'
# Campaigns, from `campaign ls --ids`, in the three places one is named: `assign`'s first
@@ -247,11 +429,6 @@ complete -c worklane -n '__worklane_command_is ls' {campaign_flags} \
# here are the values it refuses.
complete -c worklane -n '{tag_nested}' -a '(worklane tags | cut -f1,3)'
# `chown --clear` names the ticket in the flag too, since with no user to give there is
# no second positional to put it in. Scoped to `chown`, unlike the rule above: `set`
# has a `--clear` of its own that takes a field name, and clap already offers those.
complete -c worklane -n '__worklane_command_is chown' -l clear -x -a '(worklane ls --ids)'
# clap emits the statuses for `mv --status`, which is an option, but the fish generator
# emits nothing for the possible values of a positional. So the one place a status is
# positional needs them listed, and the same goes for the shell below.
@@ -489,6 +666,160 @@ mod tests {
);
}
/// One line, split the way the prompt splits it, and what the cursor's argument names.
///
/// The splitter is the prompt's own, so a row below states a line as a reader types it
/// rather than as a hand-written argument vector, and the two cannot come apart.
fn at_cursor(line: &str) -> Option<Argument> {
let split = crate::split::split_line(line, line.len());
argument_at(&split.args, split.cursor_arg)
}
/// The fixed values offered at the cursor, or nothing where what goes there is not a
/// fixed list.
fn values(line: &str) -> Option<Vec<String>> {
match at_cursor(line) {
Some(Argument::Fixed(values)) => Some(values),
_ => None,
}
}
/// Every position a ticket is taken in, as the line that reaches it.
#[test]
fn a_ticket_is_recognised_in_every_position_a_command_takes_one() {
for line in [
// The first positional, begun and half typed.
"show ",
"mv 1b7",
"comment ",
"check ",
// The second, where the first argument is a user or a campaign.
"chown alice ",
"assign v1 1b7",
// The three of `relate`'s flags, and `chown --clear`, which names the ticket
// in the flag because there is no user to give.
"relate 1b78a24 --blocked-by ",
"relate 1b78a24 --regression-of 417",
"relate 1b78a24 --relates-to ",
"chown --clear ",
] {
assert_eq!(
at_cursor(line),
Some(Argument::Ticket),
"`{line}` takes a ticket at the cursor and was not offered one"
);
}
}
/// The three places a campaign is named, and the two a tag is, which are why the lists
/// are not one list.
#[test]
fn a_campaign_and_a_tag_are_recognised_where_each_is_named() {
for line in [
"assign ",
"campaign show ",
"campaign set v1",
"ls --campaign ",
] {
assert_eq!(at_cursor(line), Some(Argument::Campaign), "`{line}`");
}
for line in ["ls --tag ", "append 1b78a24 --tags bu"] {
assert_eq!(at_cursor(line), Some(Argument::Tag { declared: false }), "`{line}`");
}
// `tags set` changes what a declared tag means and refuses one the file does not
// declare, so only the declared ones may be offered there. That is the fish half's
// 193f9be, which this deliberately does not inherit.
assert_eq!(at_cursor("tags set "), Some(Argument::Tag { declared: true }));
}
/// The verbs, which are clap's own subcommands at the top level and inside a group.
#[test]
fn the_verb_position_is_offered_the_subcommands() {
let top = values("").expect("the empty line names a verb");
for command in ["add", "ls", "mv", "relate", "campaign", "tags"] {
assert!(top.contains(&command.to_string()), "`{command}` is not offered: {top:?}");
}
// A group's own verb sits where a top-level command's first argument does, which is
// why `campaign show` needs a rule of its own in the fish half as well. In the
// order the definition spells them, since that is the order tab steps through.
let nested = values("campaign ").expect("a group names a verb");
assert_eq!(nested, ["add", "set", "append", "ls", "show"], "{nested:?}");
// `help` is clap's own and is added when the command is built, which nothing here
// does. That suits the board: what `help` prints is a page, and the prompt has a
// row.
assert!(!top.contains(&"help".to_string()), "{top:?}");
}
/// The values clap itself holds, which is every `ValueEnum` in the tool: nothing here
/// writes a status or a clearable field down a second time.
#[test]
fn an_enum_valued_argument_is_offered_the_enums_own_values() {
let statuses = values("mv 1b78a24 --status ").expect("--status takes a status");
let listed: Vec<String> = Status::ALL.iter().map(|s| s.as_str().to_string()).collect();
assert_eq!(statuses, listed, "the five statuses are not what `--status` offers");
// The one place a status is positional, which clap emits nothing for and the fish
// half lists by hand.
assert_eq!(values("ls "), Some(listed));
// And the other two enums a reader types: the fields `set --clear` empties and the
// shells `completions` writes for.
let fields = values("set 1b78a24 --clear ").expect("--clear takes a field");
assert!(fields.contains(&"acceptance".to_string()), "{fields:?}");
let shells = values("completions ").expect("completions takes a shell");
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]
fn relate_clear_is_offered_the_relation_kinds_and_no_ticket() {
let kinds = values("relate 1b78a24 --clear ").expect("--clear takes a kind");
let listed: Vec<String> = RelationKind::ALL
.iter()
.map(|kind| kind.flag().to_string())
.collect();
assert_eq!(kinds, listed, "{kinds:?}");
// And the second value is a target the board may no longer hold, which is what the
// flag exists for, so nothing is offered there at all.
assert_eq!(at_cursor("relate 1b78a24 --clear blocked-by "), None);
}
/// The positions that take free text, where offering anything would be offering a guess.
#[test]
fn nothing_is_recognised_where_the_argument_is_free_text() {
for line in [
// `chown`'s first argument is a user, checked against nothing.
"chown ",
// `mv` has no second positional, and a comment body is prose.
"mv 1b78a24 ",
"comment 1b78a24 the ",
// `tags add` declares a word the board does not have yet, so the tags it does
// have are exactly the values it refuses.
"tags add ",
// And both `--tags` that take the whole list, where a single tag offered into
// `bug,tui` would be one the field never asked for.
"add --tags ",
"set 1b78a24 --tags bug,",
] {
assert_eq!(at_cursor(line), None, "`{line}` was offered a candidate where none goes");
}
}
/// **Every rule naming an option has to say which command it belongs to.** A bare
/// `complete -c worklane -l tag` tells fish the whole tool takes `--tag`, so
/// `worklane init --<TAB>` offered six options that only `relate` and `ls` have. This
@@ -522,6 +853,7 @@ mod tests {
.chain(TICKET_SECOND_COMMANDS.iter())
.chain(CAMPAIGN_COMMANDS.iter())
.copied()
.chain(TICKET_FLAGS.iter().map(|(command, _)| *command))
.chain(TAG_FLAGS.iter().map(|(command, _)| *command));
for name in top {
@@ -545,7 +877,9 @@ mod tests {
/// bare search for `-l clear` cannot tell them apart, which is what this used to do.
#[test]
fn each_clear_flag_is_completed_for_its_own_command() {
let script = fish_dynamic();
// Continuations joined first: a rule is one logical line, and the generated ones
// put the flag and its values on either side of a trailing backslash.
let script = fish_dynamic().replace("\\\n", " ");
let cli = command();
let rule_for = |name: &str| {
@@ -558,6 +892,7 @@ mod tests {
&& line.contains(&scope)
})
.unwrap_or_else(|| panic!("no --clear rule for {name}:\n{script}"))
.to_string()
};
let has_clear = |name: &str| {
@@ -584,26 +919,41 @@ mod tests {
"tickets offered where the kind goes: {relate}"
);
// `set --clear` takes a field name, which clap already offers, and `relate --clear`
// takes a kind. Only `chown`'s names a ticket, so only that pair is in the table.
assert!(
!TICKET_FLAGS.contains(&"clear"),
"--clear in TICKET_FLAGS would offer tickets to `set --clear`, which takes a field"
!TICKET_FLAGS.contains(&("set", "clear")),
"`set --clear` in TICKET_FLAGS would offer tickets where a field name goes"
);
assert!(
!TICKET_FLAGS.contains(&("relate", "clear")),
"`relate --clear` in TICKET_FLAGS would offer tickets where the kind goes"
);
assert!(
TICKET_FLAGS.contains(&("chown", "clear")),
"`chown --clear` names the ticket in the flag, so it belongs in TICKET_FLAGS"
);
}
/// The flags completed as tickets have to be `relate`'s actual flags, or the rule
/// completes an option nothing accepts.
/// Each flag completed as a ticket has to be an option its own command actually takes,
/// or the rule completes something nothing accepts.
///
/// The command is half of what is checked, which is what the pairs bought: a flat list
/// could only be walked against one command, and `--clear` is spelled the same on three.
#[test]
fn every_ticket_flag_is_a_real_option() {
let relate = command()
.find_subcommand("relate")
.expect("relate exists")
.clone();
let known: Vec<String> = relate
.get_arguments()
.filter_map(|arg| arg.get_long().map(str::to_string))
.collect();
for flag in TICKET_FLAGS {
assert!(known.contains(&flag.to_string()), "`relate` has no --{flag}");
let cli = command();
for (name, flag) in TICKET_FLAGS {
let subcommand = cli
.find_subcommand(name)
.unwrap_or_else(|| panic!("no such subcommand: {name}"));
assert!(
subcommand
.get_arguments()
.any(|arg| arg.get_long() == Some(flag)),
"`worklane {name}` has no --{flag}"
);
}
}
+416 -42
View File
@@ -501,7 +501,18 @@ fn move_ticket_file(
/// A target the board does not have warns and allows the move. Refusing there would
/// wedge the ticket behind a bookkeeping fault with no way out but `--force`, and a
/// dangling uuid is not a dependency.
fn check_blockers(worklane_dir: &Path, content: &str, title: &str, target: Status) -> Result<()> {
///
/// The warning goes through the `sink` rather than through `eprintln!`, which is why a
/// helper that says nothing on the happy path takes one at all: this runs from the
/// board's command prompt as well as from `main`, and there the process's stderr is the
/// alternate screen. The refusal takes its colour from the sink for the same reason.
fn check_blockers(
worklane_dir: &Path,
content: &str,
title: &str,
target: Status,
sink: &mut Sink,
) -> Result<()> {
let edges: Vec<Relation> = parse_relations(content, title)?
.into_iter()
.filter(|relation| relation.kind == RelationKind::BlockedBy)
@@ -522,15 +533,15 @@ fn check_blockers(worklane_dir: &Path, content: &str, title: &str, target: Statu
Some(blocker) if !blocks_move(target, &blocker.status) => {}
Some(blocker) => behind.push(format!(
" ({}) {} [{}]",
color_text(short_id(&blocker.uuid), Color::Red),
sink.color(short_id(&blocker.uuid), Color::Red),
blocker.title,
color_text(&blocker.status, Color::Orange),
sink.color(&blocker.status, Color::Orange),
)),
None => eprintln!(
None => sink.warnln(&format!(
"Warning: ticket '{}' is blocked by {}, which is not on the board.",
title,
short_id(&edge.target),
),
))?,
}
}
@@ -544,8 +555,8 @@ fn check_blockers(worklane_dir: &Path, content: &str, title: &str, target: Statu
// next stage is otherwise told nothing about what changed.
Err(anyhow!(
"Cannot move '{}' to {} while it is blocked by:\n{}\nA ticket cannot move ahead of what it waits on. Use --force (-f) to move it anyway.",
color_text(title, Color::Green),
color_text(target.as_str(), Color::Orange),
sink.color(title, Color::Green),
sink.color(target.as_str(), Color::Orange),
behind.join("\n"),
))
}
@@ -558,7 +569,11 @@ fn check_blockers(worklane_dir: &Path, content: &str, title: &str, target: Statu
///
/// Tickets already done or discarded do not hold it up: a dependency that was satisfied
/// or abandoned is nobody's plan anymore.
fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str) -> Result<()> {
///
/// The `sink` is here for the colour alone, the rule [`check_blockers`] follows: this
/// refusal is drawn by the board as well as printed by the CLI, and a helper that asks
/// the process about its stdout answers about a terminal the message is not going to.
fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str, sink: &mut Sink) -> Result<()> {
let index = RelationIndex::load(worklane_dir)?;
// Every open dependent, not the first, for the reason `check_blockers` names them
@@ -575,9 +590,9 @@ fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str) -> Result<()>
.map(|ticket| {
format!(
" ({}) {} [{}]",
color_text(short_id(&ticket.uuid), Color::Red),
sink.color(short_id(&ticket.uuid), Color::Red),
ticket.title,
color_text(&ticket.status, Color::Orange),
sink.color(&ticket.status, Color::Orange),
)
})
.collect();
@@ -588,7 +603,7 @@ fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str) -> Result<()>
Err(anyhow!(
"Cannot discard '{}' while open tickets are blocked by it:\n{}\nUse --force (-f) to discard it anyway.",
color_text(title, Color::Green),
sink.color(title, Color::Green),
waiting.join("\n"),
))
}
@@ -596,7 +611,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, sink: &mut Sink) -> Result<()> {
pub fn cmd_mv(args: &MvArgs, start: &Path, by: Attribution, sink: &mut Sink) -> Result<()> {
let MvArgs {
ticket: ticket_id,
status: target,
@@ -694,8 +709,10 @@ pub fn cmd_mv(args: &MvArgs, start: &Path, sink: &mut Sink) -> Result<()> {
// it.
if !force {
match discarding {
true => check_dependents(&worklane_dir, &parse_ticket_field(&resolved, "ID"), &title)?,
false => check_blockers(&worklane_dir, &resolved, &title, *target)?,
true => {
check_dependents(&worklane_dir, &parse_ticket_field(&resolved, "ID"), &title, sink)?
}
false => check_blockers(&worklane_dir, &resolved, &title, *target, sink)?,
}
}
@@ -741,7 +758,7 @@ pub fn cmd_mv(args: &MvArgs, start: &Path, sink: &mut Sink) -> Result<()> {
&parse_ticket_field(&resolved, "ID"),
Kind::Status,
&change(&current_status, target_status),
&resolve_actor(actor.as_deref(), *actor_from_git),
&resolve_actor(actor.as_deref(), *actor_from_git, by),
&reason,
)?;
@@ -761,6 +778,7 @@ pub fn cmd_comment(
actor: &Option<String>,
actor_from_git: bool,
start: &Path,
by: Attribution,
sink: &mut Sink,
) -> Result<()> {
if body.is_empty() {
@@ -780,7 +798,7 @@ pub fn cmd_comment(
&ticket_uuid,
Kind::Comment,
body,
&resolve_actor(actor.as_deref(), actor_from_git),
&resolve_actor(actor.as_deref(), actor_from_git, by),
"",
)?;
@@ -959,7 +977,7 @@ fn report_in(
Ok(())
}
pub fn cmd_set(args: &SetArgs, start: &Path, sink: &mut Sink) -> Result<()> {
pub fn cmd_set(args: &SetArgs, start: &Path, by: Attribution, sink: &mut Sink) -> Result<()> {
if let Some(field) = args.contested() {
let name = field.name();
return Err(anyhow!(
@@ -1041,7 +1059,7 @@ pub fn cmd_set(args: &SetArgs, start: &Path, sink: &mut Sink) -> Result<()> {
&parse_ticket_field(&original, "Tags"),
&parse_ticket_field(&content, "Tags"),
),
&resolve_actor(args.actor.as_deref(), args.actor_from_git),
&resolve_actor(args.actor.as_deref(), args.actor_from_git, by),
"",
)?;
}
@@ -1072,7 +1090,7 @@ pub fn cmd_set(args: &SetArgs, start: &Path, sink: &mut Sink) -> 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, sink: &mut Sink) -> Result<()> {
pub fn cmd_chown(args: &ChownArgs, start: &Path, by: Attribution, 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")
})?;
@@ -1100,7 +1118,7 @@ pub fn cmd_chown(args: &ChownArgs, start: &Path, sink: &mut Sink) -> Result<()>
&parse_ticket_field(&original, "Owner"),
&parse_ticket_field(&content, "Owner"),
),
&resolve_actor(args.actor.as_deref(), args.actor_from_git),
&resolve_actor(args.actor.as_deref(), args.actor_from_git, by),
"",
)?;
@@ -1112,7 +1130,7 @@ pub fn cmd_chown(args: &ChownArgs, start: &Path, sink: &mut Sink) -> Result<()>
Ok(())
}
pub fn cmd_append(args: &AppendArgs, start: &Path, sink: &mut Sink) -> Result<()> {
pub fn cmd_append(args: &AppendArgs, start: &Path, by: Attribution, 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");
@@ -1163,7 +1181,7 @@ pub fn cmd_append(args: &AppendArgs, start: &Path, sink: &mut Sink) -> Result<()
&parse_ticket_field(&original, "Tags"),
&parse_ticket_field(&content, "Tags"),
),
&resolve_actor(args.actor.as_deref(), args.actor_from_git),
&resolve_actor(args.actor.as_deref(), args.actor_from_git, by),
"",
)?;
}
@@ -1468,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(());
@@ -1493,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,
))?;
}
@@ -1527,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.
///
@@ -1868,6 +1989,7 @@ pub fn cmd_assign(
actor: &Option<String>,
actor_from_git: bool,
start: &Path,
by: Attribution,
sink: &mut Sink,
) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
@@ -1906,7 +2028,7 @@ pub fn cmd_assign(
&uuid,
Kind::Campaign,
&change(&before, campaign.name()),
&resolve_actor(actor.as_deref(), actor_from_git),
&resolve_actor(actor.as_deref(), actor_from_git, by),
"",
)?;
@@ -2231,6 +2353,12 @@ mod sink_tests {
}
fn ticket(dir: &Path, status: &str, uuid: &str) {
ticket_with(dir, status, uuid, "");
}
/// The same ticket with `extra` appended, for a test about a section the plain
/// fixture does not carry.
fn ticket_with(dir: &Path, status: &str, uuid: &str, extra: &str) {
fs::write(
dir.join(status).join(format!("{}_ticket.md", uuid)),
format!(
@@ -2246,14 +2374,93 @@ mod sink_tests {
- **Tags**: _None_\n\
- **Owner**: alice\n\
- **Created At**: 2026-08-21 02:10:17\n\
- **Status**: {status}\n",
- **Status**: {status}\n\
{extra}",
u = uuid,
status = status,
extra = extra,
),
)
.unwrap();
}
/// A project directory with a real board under it, for a handler that takes the path
/// a shell would have been run from and walks up from it. [`temp_worklane`] is the
/// board itself, which is what a handler already handed one takes.
///
/// A [`Fixture`], so the tree goes when the test does whether it passed or not, which
/// is the rule for a unit-test fixture in this crate.
fn temp_project() -> Fixture {
let root = Fixture::new("wl-sink-project").child("project");
let dir = root.join(".worklane");
for status in status_dirs() {
fs::create_dir_all(dir.join(status)).unwrap();
}
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]
@@ -2314,4 +2521,171 @@ mod sink_tests {
fs::remove_dir_all(&dir).ok();
}
/// The aside `check_blockers` writes for a blocker the board does not hold goes to
/// the sink's warnings, and not into what the caller collects as the answer.
///
/// Two destinations because the CLI's two are two: this has always been stderr and
/// the answer stdout, and the board reads the answer back to draw it, so a warning
/// folded into it would be indistinguishable from what the command said. What it
/// must not be is an `eprintln!`, which reaches the process's own stderr — under the
/// board that is the alternate screen with the columns on it.
#[test]
fn a_dangling_blocker_warns_through_the_sink() {
let root = temp_project();
let dir = root.join(".worklane");
ticket_with(
&dir,
"backlog",
"aaaa1111-aaaa-4000-8000-000000000000",
"\n## Relations\n\n- blocked by cccc3333-cccc-4000-8000-000000000000\n",
);
let args = MvArgs {
ticket: "aaaa1111".to_string(),
status: Status::Committed,
force: false,
actor: None,
actor_from_git: false,
reason: None,
};
let mut buf = Vec::new();
let warned = {
let mut sink = Sink::buffer(&mut buf);
// A dangling uuid is a bookkeeping fault rather than a dependency, so the
// move happens and the warning is the whole of what is said about it.
cmd_mv(&args, &root, Attribution::Session, &mut sink).unwrap();
sink.warnings()
};
assert!(
warned.contains("not on the board"),
"the warning did not reach the sink:\n{warned}"
);
let out = String::from_utf8(buf).unwrap();
assert!(out.contains("Moved ticket"), "the move said nothing:\n{out}");
assert!(
!out.contains("not on the board"),
"the warning landed in the answer:\n{out}"
);
}
/// A sink whose warnings have a stream of their own holds nothing back: those bytes
/// are gone to stderr, which is what [`Sink::std`] is for. Read back as empty rather
/// than as a copy, since a caller acting on both would report the warning twice.
#[test]
fn a_sink_with_a_stream_for_its_warnings_holds_none() {
let mut answer = Vec::new();
let mut aside = Vec::new();
let mut sink = Sink::with_warnings(Box::new(&mut answer), Box::new(&mut aside), false);
sink.warnln("Warning: a blocker nothing holds").unwrap();
sink.writeln("Moved ticket").unwrap();
assert_eq!(sink.warnings(), "", "a warning with a stream was held as well as sent");
sink.flush().unwrap();
drop(sink);
assert_eq!(String::from_utf8(aside).unwrap(), "Warning: a blocker nothing holds\n");
assert_eq!(String::from_utf8(answer).unwrap(), "Moved ticket\n");
}
/// No handler and no helper reaches a print macro. Nowhere in `src`, not only in
/// this file.
///
/// The caller chooses where a command's words go — `main` its own stdout and stderr,
/// the board a buffer it reads back and draws — and a `print!` writes to the
/// process's streams instead, which under the board is the alternate screen with the
/// columns on it. That is c680e24: one `eprintln!` in `check_blockers` outlived
/// fa5662a because a helper had no sink to reach, and ratatui does not repaint a cell
/// it believes is unchanged, so the fragment stayed on the columns until something
/// else redrew them.
///
/// Over the directory rather than over a list of `include_str!`s, so a module added
/// tomorrow is scanned the day it is added: a list is what the fifty-first print site
/// hides behind. Each file is cut at its own test module, and comments are dropped,
/// because the docs around here name these macros to say why they are not called.
#[test]
fn no_handler_or_helper_reaches_a_print_macro() {
// The one site outside a test module that may, and it is not output: the fixture
// guard naming a directory it was told to leave behind, for the person reading the
// run rather than for anything collecting an answer.
let allowed = "eprintln!(\"kept fixture {}\", self.root.display());";
let mut printing: Vec<String> = Vec::new();
for entry in fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")).unwrap() {
let path = entry.unwrap().path();
if path.extension().and_then(|ext| ext.to_str()) != Some("rs") {
continue;
}
let source = fs::read_to_string(&path).unwrap();
let name = path.file_name().unwrap().to_string_lossy().to_string();
printing.extend(
body_of(&source)
.map(str::trim)
.filter(|line| !line.starts_with("//") && *line != allowed)
.filter(|line| {
["print!(", "println!(", "eprint!(", "eprintln!("]
.iter()
.any(|macro_call| line.contains(macro_call))
})
.map(|line| format!("{name}: {line}")),
);
}
assert!(
printing.is_empty(),
"a print macro writes to the process's own streams, which under the board is \
the alternate screen. Take a `Sink` and use `writeln` for an answer or \
`warnln` for an aside:\n{printing:#?}"
);
}
/// A handler takes the attribution `dispatch` was given and never decides one of its
/// own.
///
/// That parameter is what makes a command added tomorrow attributed correctly from
/// both callers at once. A handler naming `Attribution::Session` outright would be
/// the person's own keystrokes recorded as the agent's again, and it would compile,
/// so the compiler cannot be the thing that catches it.
#[test]
fn no_handler_decides_its_own_attribution() {
let mut deciding: Vec<String> = Vec::new();
for entry in fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")).unwrap() {
let path = entry.unwrap().path();
if path.extension().and_then(|ext| ext.to_str()) != Some("rs") {
continue;
}
let source = fs::read_to_string(&path).unwrap();
let name = path.file_name().unwrap().to_string_lossy().to_string();
deciding.extend(
body_of(&source)
.map(str::trim)
.filter(|line| !line.starts_with("//"))
// The definition itself, which is where the parameter is named.
.filter(|line| {
line.contains("resolve_actor(") && !line.contains("fn resolve_actor(")
})
.filter(|line| !line.ends_with(", by)") && !line.ends_with(", by),"))
.map(|line| format!("{name}: {line}")),
);
}
assert!(
deciding.is_empty(),
"a handler passes the attribution it was dispatched with, `by`, so a line \
typed at the board stays the person's:\n{deciding:#?}"
);
}
/// A file's lines up to its test module, which in this crate is the only inline
/// `mod` at column 0. A file's own assertions are allowed to name a macro the file
/// may not call, this test's own body first among them.
fn body_of(source: &str) -> impl Iterator<Item = &str> {
source
.lines()
.take_while(|line| !(line.starts_with("mod ") && line.ends_with(" {")))
}
}
+17 -10
View File
@@ -62,7 +62,9 @@ fn main() -> Result<()> {
// it opens the board above the working directory.
None => run_tui(&[], &start),
Some(Command::Tui { paths }) => run_tui(&paths, &start),
Some(command) => dispatch(&command, &start, &mut sink),
// Every call `main` dispatches came from a shell or a script, so the session's
// own chain answers: `WORKLANE_ACTOR` first, which is what it is set for.
Some(command) => dispatch(&command, &start, Attribution::Session, &mut sink),
};
// The board (and every handler) own their own writing, so flush what the last one
@@ -84,7 +86,12 @@ fn main() -> Result<()> {
/// A command added to [`Command`] therefore lands here once and is runnable from both.
/// The match is exhaustive for exactly that reason: there is no `_` arm for a new verb to
/// fall into and do nothing.
pub fn dispatch(command: &Command, start: &Path, sink: &mut Sink) -> Result<()> {
///
/// `by` is who the call is being made by, and it is a parameter here rather than a field
/// the prompt writes into the parsed arguments: an entry-writing command added tomorrow
/// is attributed correctly from both callers without an arm anywhere rewriting what clap
/// produced. `main` is the session, the prompt is the person at the board.
pub fn dispatch(command: &Command, start: &Path, by: Attribution, sink: &mut Sink) -> Result<()> {
match command {
// Reachable only from the prompt, since `main` takes this arm before it gets
// here. A board is not something a board can open.
@@ -99,11 +106,11 @@ pub fn dispatch(command: &Command, start: &Path, sink: &mut Sink) -> Result<()>
let worklane_dir = find_worklane_dir(start)?;
cmd_show(id, &worklane_dir, sink)
}
Command::Mv(args) => cmd_mv(args, start, sink),
Command::Set(args) => cmd_set(args, start, sink),
Command::Append(args) => cmd_append(args, start, sink),
Command::Mv(args) => cmd_mv(args, start, by, sink),
Command::Set(args) => cmd_set(args, start, by, sink),
Command::Append(args) => cmd_append(args, start, by, sink),
Command::Relate(args) => cmd_relate(args, start, sink),
Command::Chown(args) => cmd_chown(args, start, sink),
Command::Chown(args) => cmd_chown(args, start, by, sink),
Command::Check(args) => cmd_check(args, true, start, sink),
Command::Uncheck(args) => cmd_check(args, false, start, sink),
Command::Comment {
@@ -111,12 +118,12 @@ pub fn dispatch(command: &Command, start: &Path, sink: &mut Sink) -> Result<()>
body,
actor,
actor_from_git,
} => cmd_comment(ticket, body, actor, *actor_from_git, start, sink),
} => 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),
@@ -130,7 +137,7 @@ pub fn dispatch(command: &Command, start: &Path, sink: &mut Sink) -> Result<()>
ticket,
actor,
actor_from_git,
} => cmd_assign(campaign, ticket, actor, *actor_from_git, start, sink),
} => cmd_assign(campaign, ticket, actor, *actor_from_git, start, by, sink),
// 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
// spellings cannot be allowed to drift into two behaviours.
+821 -19
View File
@@ -28,6 +28,7 @@ use ratatui::widgets::{Block, Borders, Clear, Padding, Paragraph, Tabs, Wrap};
use crate::campaign::{CAMPAIGNS_DIR, CampaignIndex, Standing};
use crate::command::{Cli, Command};
use crate::completions::{Argument, argument_at};
use crate::history::{HistoryPart, history_parts, history_root, read_history};
use crate::split::{Unclosed, split_line};
use crate::tag::{NO_ANNOTATION, TAGS_FILE, TagIndex};
@@ -741,6 +742,26 @@ pub struct Prompt {
/// The half typed line `up` walked away from, put back by walking down past the newest
/// entry. `Some` exactly while `position` is.
pending: Option<String>,
/// Where a `tab` walk has got to, or `None` while nothing on the row came from one.
///
/// Cleared by every edit of the line, beside `refused` and for the same reason: the walk
/// is about an argument, and a line that has changed is a different argument.
completing: Option<Completing>,
}
/// A `tab` walk in progress: the line as it stood before the first press, and how many
/// presses have landed on it since.
///
/// The line rather than the candidate it chose, so each press rebuilds the row from what was
/// typed and reads the candidates fresh. Holding the list instead would be a copy going
/// stale between two presses, and holding the last candidate would narrow the list to it —
/// a walk that stepped once and then stood still.
#[derive(Debug)]
struct Completing {
line: String,
cursor: usize,
/// How many times `tab` has been pressed with nothing else in between, counting from 1.
presses: usize,
}
impl Prompt {
@@ -748,11 +769,11 @@ impl Prompt {
/// `esc` and `enter`: those two are the mode's rather than the line's, and they are
/// answered by [`Board::prompt_key`] before it gets here.
///
/// Left, right, home, end, backspace and `ctrl-w` behave as they do in a shell. There
/// is no `tab`: suggesting the selected ticket is 00a14e7, and until then it is a key
/// that must not reach the project tabs. Every other control combination lands on the
/// last arm and does nothing, which is what stops `ctrl-d` reaching the action bound
/// to `d`.
/// Left, right, home, end, backspace and `ctrl-w` behave as they do in a shell. `tab`
/// is not here either: it takes the suggestion, which is the board's rather than the
/// line's, since the selected card is what it is made of. Every other control
/// combination lands on the last arm and does nothing, which is what stops `ctrl-d`
/// reaching the action bound to `d`.
fn key(&mut self, key: KeyEvent, control: bool) {
match key.code {
KeyCode::Left if !control => self.cursor = self.left_of(),
@@ -763,15 +784,23 @@ impl Prompt {
// with it. Movement above deliberately does not clear it.
KeyCode::Backspace if !control => self.cut(self.left_of()),
KeyCode::Char('w') if control => self.cut(self.word_start()),
KeyCode::Char(typed) if !control => {
self.line.insert(self.cursor, typed);
self.cursor += typed.len_utf8();
self.refused = None;
}
KeyCode::Char(typed) if !control => self.insert(typed.encode_utf8(&mut [0; 4])),
_ => {}
}
}
/// Put `text` into the line at the cursor and leave the cursor after it, which is what
/// typing it would have done.
///
/// The message about the last enter goes with it, for the reason every other edit takes
/// it away: it was about a line that is no longer on the row.
fn insert(&mut self, text: &str) {
self.line.insert_str(self.cursor, text);
self.cursor += text.len();
self.refused = None;
self.completing = None;
}
/// The offset one character to the left of the cursor, or the cursor itself at the
/// start of the line. By characters, so a cursor never lands inside one.
fn left_of(&self) -> usize {
@@ -830,6 +859,7 @@ impl Prompt {
self.line.replace_range(from..self.cursor, "");
self.cursor = from;
self.refused = None;
self.completing = None;
}
/// Put a recalled line on the row with the cursor at its end, the way a shell hands
@@ -842,6 +872,7 @@ impl Prompt {
self.cursor = line.len();
self.line = line;
self.refused = None;
self.completing = None;
}
}
@@ -2355,6 +2386,9 @@ impl Board {
// the whole board rather than the prompt alone.
KeyCode::Up if !control => self.recall_back(),
KeyCode::Down if !control => self.recall_forward(),
// The mode's too, and never the tabs': every key belongs to the prompt while it
// is open, and what this one takes is made of the selected card.
KeyCode::Tab if !control => self.complete(),
_ => {
if let Some(prompt) = &mut self.prompt {
prompt.key(key, control);
@@ -2365,6 +2399,179 @@ impl Board {
true
}
/// Every candidate for the argument the cursor is in, and what has been typed into it.
///
/// The one question the row's suggestion and the `tab` walk both ask, so what is drawn
/// and what a press takes cannot come apart. Derived on every call and held nowhere:
/// the line is edited and the board reloads under it, and a list kept between two
/// presses would describe neither.
///
/// **What goes where is [`argument_at`]'s**, off the tables the fish completions are
/// generated from, and **what the board holds of it is this file's**. Nothing here reads
/// the tree: a ticket is the selected card, a campaign and a tag are the tab's own rows,
/// rebuilt at every reload beside the columns, and everything else is written down once
/// in the clap definition.
///
/// Two things have to hold, each its own answer to the reader:
///
/// - **The cursor is at the end of the line.** The suggestion is drawn after it and a
/// press replaces the argument it is in, so with the line continuing past the cursor
/// both would land in the middle of something already typed. That is the rule a
/// shell's own suggestion keeps.
/// - **A candidate still starts with what is typed.** An offer that no longer matches
/// the argument under it describes nothing.
///
/// The line it reads is the one that was on the row before `tab` was first pressed,
/// where a walk is under way: what is on the row then is a candidate, and reading the
/// stem off it would narrow the list to the candidate the last press chose.
fn completion(&self) -> Option<(String, Vec<String>)> {
let prompt = self.prompt.as_ref()?;
if prompt.cursor != prompt.line.len() {
return None;
}
let line = match &prompt.completing {
Some(walk) => walk.line.as_str(),
None => prompt.line.as_str(),
};
let split = split_line(line, line.len());
// Empty where the argument has been opened and nothing of it lies behind the
// cursor, which is every candidate offered.
let stem = match split.at_new_arg {
true => String::new(),
false => split.args[split.cursor_arg].clone(),
};
let offers: Vec<String> = self
.candidates(&split.args, split.cursor_arg)
.into_iter()
.filter(|candidate| candidate.starts_with(&stem))
.collect();
(!offers.is_empty()).then_some((stem, offers))
}
/// What the board currently holds of whatever the argument names.
///
/// The tab's own rows for a campaign and a tag, which `reload` rebuilds beside the
/// columns and the `c` and `t` pickers draw: the answer is already in memory, and a
/// read of the tree on a keypress would be a second source for it.
///
/// A campaign is offered by codename, which is what the board draws on every card in it
/// and the shortest thing that addresses it. One that has none falls back to its short
/// id, which is what the board labels it with and what `assign` resolves — leaving it
/// out would hide a campaign from the only place the reader can reach it by typing.
fn candidates(&self, args: &[String], index: usize) -> Vec<String> {
let tab = self.current();
let mut found: Vec<String> = match argument_at(args, index) {
None => return Vec::new(),
Some(Argument::Fixed(values)) => values,
Some(Argument::Ticket) => tab
.selected()
.map(|card| card.ticket.id.clone())
.into_iter()
.collect(),
Some(Argument::Campaign) => tab
.campaigns
.iter()
.map(|row| match &row.codename {
Some(codename) => codename.clone(),
None => short_id(&row.uuid).to_string(),
})
.collect(),
Some(Argument::Tag { declared }) => tab
.tags
.iter()
.filter(|row| !declared || row.declared())
.map(|row| row.name.clone())
.collect(),
};
// The merge tab holds several boards' campaigns, so one codename can arrive twice.
// A repeat is a press that appears to do nothing, which is worse than the tab
// costing a moment here.
let mut seen = std::collections::HashSet::new();
found.retain(|candidate| seen.insert(candidate.clone()));
found
}
/// What the row draws after the cursor: the part of the common prefix of the candidates
/// that is not typed yet, which is exactly what the next `tab` takes.
///
/// One rule for one candidate and for many. With a ticket there is only ever the
/// selected card, so what is drawn is the rest of its id; with the five statuses there
/// is nothing every candidate agrees on, so nothing is drawn and `tab` steps through
/// them instead. What the row shows is never something a press would not do.
///
/// Nothing while a walk is under way: the row is holding a whole candidate then, and a
/// second one drawn against it would read as part of the same word.
pub fn suggestion(&self) -> Option<String> {
if self.prompt.as_ref()?.completing.is_some() {
return None;
}
let (stem, offers) = self.completion()?;
common_prefix(&offers)
.strip_prefix(&stem)
.filter(|rest| !rest.is_empty())
.map(str::to_string)
}
/// `tab`: take what every candidate agrees on, and then step through them one press at
/// a time.
///
/// The first press takes the common prefix where there is more of it than has been
/// typed, which is the whole candidate when there is only one. From there each press
/// puts one candidate on the row in place of the last, wrapping at the end. A shell
/// does the same, and it needs no list drawn over the columns — which is the trade this
/// makes, since the board behind the prompt is what the reader is reading.
///
/// **Each press rebuilds the row from the line as it stood before the first**, so the
/// candidates are read fresh every time and nothing is stored but where the walk has
/// got to. Stepping off a candidate the last press typed would narrow the list to it.
///
/// The whole board rather than the prompt alone, for the reason the recall walk is:
/// what is on offer is made of the board and the line is only where it lands.
fn complete(&mut self) {
let Some((stem, offers)) = self.completion() else {
return;
};
let presses = self
.prompt
.as_ref()
.and_then(|prompt| prompt.completing.as_ref())
.map_or(0, |walk| walk.presses)
+ 1;
// The prefix step is only a step where it adds something. With the statuses, which
// agree on nothing, the first press is already the first candidate.
let common = common_prefix(&offers);
let taken = match (common.len() > stem.len(), presses) {
(true, 1) => common.as_str(),
(true, step) => offers[(step - 2) % offers.len()].as_str(),
(false, step) => offers[(step - 1) % offers.len()].as_str(),
};
let rest = taken[stem.len()..].to_string();
let Some(prompt) = &mut self.prompt else {
return;
};
let (line, cursor) = match prompt.completing.take() {
Some(walk) => (walk.line, walk.cursor),
None => (prompt.line.clone(), prompt.cursor),
};
prompt.line = line.clone();
prompt.cursor = cursor;
// After the insert, which clears the walk the way every other edit of the line does.
prompt.insert(&rest);
prompt.completing = Some(Completing { line, cursor, presses });
}
/// `up`: one line further back, or the newest line when the reader is still on their
/// own.
///
@@ -2535,14 +2742,27 @@ impl Board {
.filter(|(uuid, _)| !is_unknown_value(uuid));
let mut buffer: Vec<u8> = Vec::new();
let outcome = {
let (outcome, warned) = {
let mut sink = Sink::buffer(&mut buffer);
crate::dispatch(command, &root, &mut sink).and_then(|()| sink.flush())
// The person's, not the session's. Nothing but the reader can type this line,
// so `WORKLANE_ACTOR` — set where the agents on this machine pick it up, and
// inherited by the shell that opened the board — does not describe whoever
// pressed enter.
let outcome = crate::dispatch(command, &root, Attribution::Person, &mut sink)
.and_then(|()| sink.flush());
// Read on both outcomes and reported on both: a `mv` that warns about a
// dangling blocker and is then refused by a real one wrote the warning
// first, and dropping it there would lose the half that says why the
// refusal names one blocker and the ticket records two.
(outcome, sink.warnings())
};
// The warning ahead of the answer, the order the handler wrote them in and the
// order a shell shows the two streams in.
//
// Plain by construction, since the sink is: stripped anyway, because an escape
// drawn into a ratatui paragraph is printed rather than obeyed, and this is the
// one seam where a handler's bytes become a frame.
let said = without_escapes(&String::from_utf8_lossy(&buffer))
let said = without_escapes(&format!("{warned}{}", String::from_utf8_lossy(&buffer)))
.trim_end()
.to_string();
@@ -2556,7 +2776,14 @@ impl Board {
let moved = held.and_then(|(uuid, id)| self.reselect(&uuid, &id, screen));
match outcome {
Err(err) => self.notice = Some(Notice::failed(error_lines(&err))),
// The warning above the refusal, the order they were written in.
Err(err) => {
let failure = match said.is_empty() {
true => error_lines(&err),
false => format!("{said}\n{}", error_lines(&err)),
};
self.notice = Some(Notice::failed(failure));
}
Ok(()) => {
self.prompt = None;
let words = match said.is_empty() {
@@ -4539,7 +4766,7 @@ fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) {
// and is asked first: an input cannot be covered, and it is the newest of the three
// things that can hold the row. Only one of the two prompts can be open at a time.
if let Some(prompt) = &board.prompt {
draw_prompt(frame, prompt, area);
draw_prompt(frame, prompt, board.suggestion().as_deref(), area);
return;
}
@@ -4745,7 +4972,14 @@ const PROMPT_OPENING: &str = " :";
///
/// `run` and not `check`: enter hands the line to the same handler the shell reaches, and
/// the row has to say which of the two it is about to do.
fn draw_prompt(frame: &mut Frame, prompt: &Prompt, area: Rect) {
///
/// The suggestion is drawn after the line in grey, which is what the palette already spends
/// on a value that is not one: it is not in the line until `tab` puts it there, and the
/// reader has to be able to tell the two apart at a glance. It takes what the line leaves
/// of the field rather than a field of its own, so a long command loses the offer instead
/// of pushing the keys off the row. The terminal cursor sits on its first cell, which is
/// where the cursor already was: what is under a cursor is still what will be typed over.
fn draw_prompt(frame: &mut Frame, prompt: &Prompt, suggestion: Option<&str>, area: Rect) {
let keys = key_hints(&[("↵", "run"), ("esc", "cancel")]);
let spent: usize = PROMPT_OPENING.chars().count()
+ KEY_GAP.chars().count()
@@ -4760,6 +4994,18 @@ fn draw_prompt(frame: &mut Frame, prompt: &Prompt, area: Rect) {
let (visible, at) = prompt_window(&prompt.line, prompt.cursor, room);
let mut spans = vec![Span::raw(format!("{PROMPT_OPENING}{visible}"))];
// Only ever drawn where the cursor is at the end of the line, which is what `visible`
// then ends at, so this follows the cursor rather than landing in front of the tail of
// a command.
if let Some(rest) = suggestion {
let left = room.saturating_sub(visible.chars().count());
let shown: String = rest.chars().take(left).collect();
if !shown.is_empty() {
spans.push(Span::styled(shown, Style::default().fg(Color::Grey.into())));
}
}
match &prompt.refused {
Some(message) => spans.push(Span::styled(
format!("{KEY_GAP}{message}"),
@@ -4779,6 +5025,28 @@ fn draw_prompt(frame: &mut Frame, prompt: &Prompt, area: Rect) {
frame.set_cursor_position((area.x + column.min(area.width.saturating_sub(1)), area.y));
}
/// The longest opening every one of `values` shares, which is what one `tab` can take
/// without choosing between them.
///
/// Counted in characters rather than bytes, so a tag spelled in more than ascii is cut on
/// one of its own letters. An empty list has no prefix and neither has a list whose members
/// start differently, which is the answer that puts the first press on the first candidate
/// instead.
fn common_prefix(values: &[String]) -> String {
let Some(first) = values.first() else {
return String::new();
};
values[1..].iter().fold(first.clone(), |prefix, value| {
prefix
.chars()
.zip(value.chars())
.take_while(|(held, c)| held == c)
.map(|(held, _)| held)
.collect()
})
}
/// The part of `line` a field `room` cells wide shows with the cursor at `cursor`, and the
/// column the cursor lands on inside it.
///
@@ -8159,6 +8427,57 @@ approach";
);
}
/// An entry the prompt writes is the reader's own, whatever `WORKLANE_ACTOR` says.
///
/// The variable is set in the environment an agent runs in, and a person configuring
/// it for the agents on their machine exports it where their own shell picks it up
/// too — so the shell that opened this board carries it, and without the attribution
/// parameter this entry would name the agent.
///
/// Read against `get_git_user` rather than a literal, since the name depends on the
/// machine the suite runs on. With no git user configured there is nobody to name and
/// the entry reads `unknown`, which is the same rule and not a fallback to the
/// variable.
#[test]
fn an_entry_written_from_the_prompt_names_the_person() {
let (root, mut board) = runnable();
let dir = root.join(".worklane");
run_line(&mut board, "comment 1111111 \"typed at the board\"");
assert!(board.prompt.is_none(), "the line was refused: {:?}", refused(&board));
let log = read_history(&dir, "11111111-0000-4000-8000-000000000000").unwrap();
let entry = log
.iter()
.find(|entry| entry.body == "typed at the board")
.expect("the comment was not written");
assert_eq!(
entry.author,
get_git_user().unwrap_or_else(|| UNKNOWN_ACTOR.to_string()),
"the board attributed the reader's own line to somebody else"
);
// And `--actor` still wins, which is how the reader puts somebody else's name on
// their own keystrokes.
run_line(&mut board, "comment 1111111 \"for alice\" --actor alice");
let log = read_history(&dir, "11111111-0000-4000-8000-000000000000").unwrap();
let entry = log
.iter()
.find(|entry| entry.body == "for alice")
.expect("the second comment was not written");
assert_eq!(entry.author, "alice", "the flag lost to the board's own attribution");
// The two flags together are clap's refusal, reached here because the prompt
// parses against the same definition the shell does rather than a grammar of its
// own. A line it refuses keeps the prompt open with the line intact.
run_line(&mut board, "comment 1111111 both --actor alice --actor-from-git");
assert!(
refused(&board).is_some_and(|said| said.contains("cannot be used with")),
"the contradictory pair was taken: {:?}",
refused(&board)
);
}
/// What the handler said is what the board reports, word for word: those messages are
/// already written for a person, and a second set kept on the board would go stale the
/// first time one of them changed.
@@ -8178,7 +8497,7 @@ approach";
.unwrap();
{
let mut sink = Sink::buffer(&mut buffer);
crate::dispatch(&command, &root, &mut sink).unwrap();
crate::dispatch(&command, &root, Attribution::Session, &mut sink).unwrap();
sink.flush().unwrap();
}
let said = String::from_utf8(buffer).unwrap().trim_end().to_string();
@@ -8226,6 +8545,85 @@ approach";
);
}
/// A warning comes back with the answer instead of going to stderr, which under the
/// board is the alternate screen: `eprintln!` drew the line straight onto the
/// columns, and ratatui does not repaint a cell it believes is unchanged, so the
/// fragment stayed there until something else redrew them. That is c680e24.
///
/// Asserted on the notice for the reason `the_footer_reports_the_handlers_own_words`
/// is: the words being *there* is what says they were collected rather than printed.
#[test]
fn a_warning_is_reported_with_the_answer_rather_than_printed() {
let (root, mut board) = runnable();
write_ticket(
&root.join(".worklane"),
"backlog",
WAITER,
"The waiter",
&blocked_by(ELSEWHERE),
);
// A dangling blocker is a bookkeeping fault rather than a dependency, so the
// move happens and the warning is the whole of what is said about it.
run_line(&mut board, "mv bbbbbbb --status committed");
let notice = board.notice.as_ref().expect("the command said nothing");
assert!(!notice.failed, "a dangling blocker refused the move: {}", notice.text);
assert_eq!(column_of(&board, "The waiter"), Some("committed"));
let warning = notice.text.find("not on the board");
let answer = notice.text.find("Moved ticket");
assert!(warning.is_some(), "the warning never reached the board: {}", notice.text);
assert!(
warning < answer,
"the aside was not put above the answer it came before: {}",
notice.text
);
let screen = screen_text(&board);
for line in notice.lines() {
assert!(screen.contains(line.trim()), "`{line}` never reached the frame:\n{screen}");
}
}
/// Warned and then refused, which is one blocker the board does not hold and one it
/// does. Both are reported: the refusal names the blocker in the way and the ticket
/// records two, so dropping the aside is dropping the answer to why.
#[test]
fn a_refused_move_keeps_the_warning_that_came_before_it() {
let (root, mut board) = runnable();
write_ticket(
&root.join(".worklane"),
"backlog",
WAITER,
"The waiter",
// `Alpha first`, which `runnable` leaves in the backlog: a blocker a ticket
// may stand level with and not move ahead of.
&format!(
"\n## Relations\n\n- blocked by {ELSEWHERE}\n\
- blocked by 11111111-0000-4000-8000-000000000000\n"
),
);
run_line(&mut board, "mv bbbbbbb --status committed");
let notice = board.notice.as_ref().expect("the refusal said nothing");
assert!(notice.failed, "a refused move was reported as a success");
assert_eq!(
column_of(&board, "The waiter"),
Some("backlog"),
"the move happened anyway"
);
let warning = notice.text.find("not on the board");
let refusal = notice.text.find("Cannot move");
assert!(
warning.is_some(),
"the warning was dropped on the error path: {}",
notice.text
);
assert!(refusal.is_some(), "the refusal was dropped: {}", notice.text);
assert!(warning < refusal, "the aside came after the refusal: {}", notice.text);
}
/// A handler that errors leaves the prompt open with the line exactly as it was: the
/// usual cause is an ambiguous id, and the fix is two more characters rather than the
/// whole line retyped from `:`.
@@ -8444,8 +8842,8 @@ approach";
// What the board calls instead.
assert!(
here.contains("crate::dispatch(command, &root, &mut sink)"),
"the board does not go through the table"
here.contains("crate::dispatch(command, &root, Attribution::Person, &mut sink)"),
"the board does not go through the table, or it does not attribute to the person"
);
}
@@ -8953,6 +9351,410 @@ approach";
assert_eq!(prompt_line(&board), Some("ls backlog"), "the walk did not happen");
}
// ---------------------------------------------------------------- the suggestion --
/// The id of the card the selection is on, which is what every suggestion is made of.
fn selected_id(board: &Board) -> String {
board.selected().expect("a card is selected").ticket.id.clone()
}
/// Open a fresh prompt, type `line` into it, and answer what is suggested at the end
/// of it.
fn suggested(board: &mut Board, line: &str) -> Option<String> {
board.open_prompt();
type_line(board, line);
let rest = board.suggestion();
board.prompt = None;
rest
}
/// The same, for every candidate the argument at the end of `line` has rather than the
/// part of them the row draws.
fn offered(board: &mut Board, line: &str) -> Vec<String> {
board.open_prompt();
type_line(board, line);
let found = board.completion().map(|(_, offers)| offers).unwrap_or_default();
board.prompt = None;
found
}
/// Type `line` and then press tab `presses` times, and answer what is on the row.
fn tabbed(board: &mut Board, line: &str, presses: usize) -> String {
board.open_prompt();
type_line(board, line);
for _ in 0..presses {
press_prompt(board, KeyCode::Tab);
}
let row = prompt_line(board).expect("the prompt closed").to_string();
board.prompt = None;
row
}
/// Every position a command takes a ticket in, driven as a line typed at the prompt.
///
/// The whole id where the argument has been opened and nothing typed into it, which is
/// the ordinary case: the reader has the card in front of them and presses tab.
#[test]
fn the_selected_id_is_suggested_wherever_a_ticket_argument_goes() {
let (_root, mut board) = runnable();
let id = selected_id(&board);
for line in [
// The first positional.
"show ",
"mv ",
"comment ",
// The second, which is where `chown` and `assign` put it on purpose.
"chown alice ",
"assign v1 ",
// `relate`'s three flags, and `chown --clear`, which names the ticket in the
// flag since there is no user to give.
"relate 2222222 --blocked-by ",
"relate 2222222 --regression-of ",
"relate 2222222 --relates-to ",
"chown --clear ",
] {
assert_eq!(
suggested(&mut board, line).as_deref(),
Some(id.as_str()),
"`{line}` takes a ticket and was offered nothing"
);
}
}
/// And every position that takes something else, which is the half a version counting
/// the first argument alone gets wrong.
///
/// Asked of the candidates rather than of the row, because several of these positions
/// now have candidates of their own: what has to be true is that none of them is the
/// card under the selection.
#[test]
fn the_selected_id_is_not_offered_where_the_argument_is_not_a_ticket() {
let (_root, mut board) = runnable();
let id = selected_id(&board);
for line in [
// The verb itself, empty and half typed.
"",
"sh",
// `chown` takes a user first and `assign` a campaign.
"chown ",
"assign ",
// A status, and a campaign under its own command.
"ls ",
"campaign show ",
// The two `--clear` flags spelled like `chown`'s: a relation kind, and a field.
"relate 2222222 --clear ",
"set 2222222 --clear ",
// And `relate --clear`'s second value, which is a target the board may no
// longer hold.
"relate 2222222 --clear blocked-by ",
// One past the ticket, where `mv` wants a status.
"mv 2222222 ",
] {
assert!(
!offered(&mut board, line).contains(&id),
"`{line}` was offered the selected ticket where none goes"
);
}
}
/// A partly typed argument is completed rather than restated, and only while the
/// selected id still starts with what is on the row.
#[test]
fn a_half_typed_argument_is_suggested_only_while_the_id_starts_with_it() {
let (_root, mut board) = runnable();
let id = selected_id(&board);
let head = &id[..3];
assert_eq!(
suggested(&mut board, &format!("show {head}")).as_deref(),
Some(&id[3..]),
"the part already typed was offered a second time"
);
// The whole id typed leaves nothing to add, which is not a suggestion of nothing.
assert_eq!(suggested(&mut board, &format!("show {id}")), None);
// And a prefix the selection does not match describes another ticket entirely.
assert_eq!(suggested(&mut board, "show 9"), None);
}
/// Nothing is suggested with no card under the selection: on the frame, where the
/// selection is on a campaign or a tag rather than a ticket, and on an empty board.
#[test]
fn nothing_is_suggested_when_no_card_is_selected() {
let (_root, mut board) = runnable();
board.current_mut().focus = Focus::Frame;
assert_eq!(suggested(&mut board, "show "), None, "the frame offered a ticket");
let empty = board_dir();
let mut bare = one_board(&empty);
assert_eq!(suggested(&mut bare, "show "), None, "an empty board offered a ticket");
}
/// What the row shows: the suggestion after the cursor, in grey, and not in the line.
#[test]
fn the_suggestion_is_drawn_after_the_cursor_in_grey_and_is_not_yet_the_line() {
let (_root, mut board) = runnable();
let id = selected_id(&board);
board.open_prompt();
type_line(&mut board, "show ");
let row = footer(&board, SCREEN.width, SCREEN.height);
assert!(row.contains(&format!(":show {id}")), "the suggestion is not drawn: {row}");
assert_eq!(prompt_line(&board), Some("show "), "the suggestion went into the line");
let (colour, _) = footer_style(&board, SCREEN.width, SCREEN.height, &id);
assert_eq!(colour, Color::Grey.into(), "the suggestion is not drawn as a placeholder");
// The cursor stays where the line ends, which is the first cell of the suggestion.
let mut terminal = Terminal::new(TestBackend::new(SCREEN.width, SCREEN.height)).unwrap();
terminal.draw(|frame| draw(frame, &board)).unwrap();
let at = terminal.get_cursor_position().unwrap();
assert_eq!(at.x as usize, PROMPT_OPENING.chars().count() + "show ".len());
}
/// Tab takes it, and any other key leaves the line to say what was typed.
#[test]
fn tab_takes_the_suggestion_into_the_line_and_another_key_drops_it() {
let (_root, mut board) = runnable();
let id = selected_id(&board);
board.open_prompt();
type_line(&mut board, "show ");
press_prompt(&mut board, KeyCode::Tab);
assert_eq!(prompt_line(&board), Some(format!("show {id}").as_str()));
// Nothing is left to offer once the whole id is on the row, so a second press
// cannot double it.
press_prompt(&mut board, KeyCode::Tab);
assert_eq!(prompt_line(&board), Some(format!("show {id}").as_str()));
// And a key that takes the line off the id drops the offer rather than holding it.
board.prompt = None;
board.open_prompt();
type_line(&mut board, "show 9");
assert_eq!(board.suggestion(), None);
press_prompt(&mut board, KeyCode::Tab);
assert_eq!(prompt_line(&board), Some("show 9"), "tab typed a suggestion that had gone");
}
/// The swallow contract for the one key this ticket gives the prompt: `tab` is the
/// project key on the board and must not be while a command is being typed.
#[test]
fn tab_in_the_prompt_never_changes_the_project_tab() {
let alpha = board_dir();
let beta = board_dir();
write_ticket(&alpha, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", "");
write_ticket(&beta, "backlog", "22222222-0000-4000-8000-000000000000", "Beta", "");
let mut board = boards(&[("alpha", &alpha), ("beta", &beta)]);
assert!(board.tabbed(), "the fixture has nothing to switch between");
board.open_prompt();
// Both with something to take and with nothing, since the arm has to be the
// prompt's either way.
for line in ["show ", "ls "] {
board.prompt = Some(Prompt::default());
type_line(&mut board, line);
assert!(board.prompt_key(typed(KeyCode::Tab), SCREEN), "tab was not taken");
assert_eq!(board.tab, 0, "`{line}` let tab through to the tabs");
}
}
/// A board carrying everything the prompt completes off the tab's own rows: two
/// campaigns, one without a codename, and a vocabulary with a tag nothing declares.
fn completable() -> (Fixture, Board) {
let dir = board_dir();
write_tag_ticket(
&dir,
"backlog",
"11111111-0000-4000-8000-000000000000",
"One",
"bug,sync",
);
write_tag_ticket(&dir, "committed", "22222222-0000-4000-8000-000000000000", "Two", "bug");
write_campaign(&dir, "aaaaaaaa-0000-4000-8000-000000000000", "First release", "v1", "One.");
write_campaign(&dir, "bbbbbbbb-0000-4000-8000-000000000000", "Nameless", "", "Two.");
write_vocabulary(
&dir,
&[
("bug", "Behaviour that contradicts what the tool says."),
("chore", "Work."),
],
);
let board = one_board(&dir);
(dir, board)
}
/// The verb position, which is clap's own subcommands and the campaign group's own.
#[test]
fn the_verb_is_completed_from_the_subcommands() {
let (_dir, mut board) = completable();
assert!(offered(&mut board, "").contains(&"relate".to_string()));
// Narrowed to what has been typed, and the common opening taken on the first press.
assert_eq!(offered(&mut board, "comm"), ["comment"]);
assert_eq!(tabbed(&mut board, "comm", 1), "comment");
// A group's verbs sit where a top-level command's first argument does.
assert_eq!(tabbed(&mut board, "campaign sh", 1), "campaign show");
}
/// The five statuses, in both places one is named.
#[test]
fn a_status_argument_is_completed_from_the_status_enum() {
let (_dir, mut board) = completable();
let listed: Vec<String> = Status::ALL.iter().map(|s| s.as_str().to_string()).collect();
assert_eq!(offered(&mut board, "mv 1111111 --status "), listed);
assert_eq!(offered(&mut board, "ls "), listed);
// And narrowed by what is typed, where `d` reaches two of them.
assert_eq!(offered(&mut board, "ls d"), ["done", "discarded"]);
}
/// Tags and campaigns, which come off the rows the tab already holds.
#[test]
fn a_tag_and_a_campaign_are_completed_from_the_tabs_own_rows() {
let (_dir, mut board) = completable();
// Every tag the board declares or carries, which is what `--tag` matches.
assert_eq!(offered(&mut board, "ls --tag "), ["bug", "chore", "sync"]);
assert_eq!(offered(&mut board, "append 1111111 --tags s"), ["sync"]);
// A campaign by its codename, and by its short id where it has none: that is what
// the board labels it with and what `assign` resolves.
assert_eq!(offered(&mut board, "assign "), ["v1", "bbbbbbb"]);
assert_eq!(offered(&mut board, "campaign show v"), ["v1"]);
assert_eq!(offered(&mut board, "ls --campaign v"), ["v1"]);
}
/// `tags set` refuses a tag the vocabulary does not declare, so the prompt does not
/// offer one. That is the fish half's 193f9be, which this deliberately does not inherit.
#[test]
fn the_prompt_offers_no_candidate_the_command_would_refuse() {
let (_dir, mut board) = completable();
assert_eq!(offered(&mut board, "tags set "), ["bug", "chore"]);
assert!(
!offered(&mut board, "tags set ").contains(&"sync".to_string()),
"a carried but undeclared tag was offered where only a declared one is taken"
);
// `tags add` takes a word the board does not have yet, so every tag it has is a
// value it refuses, and both `--tags` that take the whole list would have one tag
// replace what is already in it.
for line in ["tags add ", "add --tags ", "set 1111111 --tags bug,"] {
assert!(offered(&mut board, line).is_empty(), "`{line}` offered a candidate");
}
}
/// The candidates are what the tab already holds, so a keypress never goes to disk.
///
/// Pinned by taking the board away from under it: a completion that read the tree would
/// answer nothing here, and one reading the rows `reload` built answers exactly what it
/// answered before. The rows outlive the directory because they are the same rows the
/// `c` and `t` pickers draw.
#[test]
fn the_candidates_come_off_the_loaded_rows_and_never_off_the_tree() {
let (dir, mut board) = completable();
let tags = offered(&mut board, "ls --tag ");
let campaigns = offered(&mut board, "assign ");
let id = selected_id(&board);
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(offered(&mut board, "ls --tag "), tags, "the tags were read off the tree");
assert_eq!(offered(&mut board, "assign "), campaigns, "the campaigns were");
assert_eq!(offered(&mut board, "show "), [id], "the ticket was");
// And the fixed lists were never anywhere but the clap definition.
assert!(offered(&mut board, "ls ").contains(&"backlog".to_string()));
}
/// `relate --clear` takes the kind first, and the three kinds are what is offered there
/// rather than the board listing the other three flags get.
#[test]
fn relate_clear_is_completed_with_the_relation_kinds() {
let (_dir, mut board) = completable();
let kinds: Vec<String> = RelationKind::ALL
.iter()
.map(|kind| kind.flag().to_string())
.collect();
assert_eq!(offered(&mut board, "relate 1111111 --clear "), kinds);
assert_eq!(
tabbed(&mut board, "relate 1111111 --clear b", 1),
"relate 1111111 --clear blocked-by"
);
// And the target after it is one the board may no longer hold.
assert!(offered(&mut board, "relate 1111111 --clear blocked-by ").is_empty());
}
/// The walk itself: the common opening on the first press, then one candidate per press
/// in place of the last, round to the start again.
#[test]
fn tab_takes_the_common_prefix_and_then_steps_through_the_candidates() {
let (_dir, mut board) = completable();
// `comment` and `completions` are what `co` narrows to, and `com` is as far as one
// press can go without choosing between them.
assert_eq!(tabbed(&mut board, "co", 0), "co");
assert_eq!(tabbed(&mut board, "co", 1), "com");
assert_eq!(tabbed(&mut board, "co", 2), "comment");
assert_eq!(tabbed(&mut board, "co", 3), "completions");
assert_eq!(tabbed(&mut board, "co", 4), "comment", "the walk did not come round");
// With nothing in common the first press is already the first candidate, and each
// one replaces the last rather than being typed after it.
assert_eq!(tabbed(&mut board, "ls ", 0), "ls ");
assert_eq!(tabbed(&mut board, "ls ", 1), "ls backlog");
assert_eq!(tabbed(&mut board, "ls ", 2), "ls committed");
assert_eq!(tabbed(&mut board, "ls ", 6), "ls backlog");
}
/// What the row draws is what the next press takes, which is why it is nothing where
/// the candidates agree on nothing.
#[test]
fn the_row_draws_the_common_prefix_and_nothing_where_there_is_none() {
let (_dir, mut board) = completable();
assert_eq!(suggested(&mut board, "comm").as_deref(), Some("ent"));
assert_eq!(
suggested(&mut board, "co").as_deref(),
Some("m"),
"`comment` and `completions` agree on one more letter"
);
assert_eq!(suggested(&mut board, "ls "), None, "the five statuses agree on nothing");
// And nothing at all while a walk is on the row: what is there is a whole candidate.
board.open_prompt();
type_line(&mut board, "co");
press_prompt(&mut board, KeyCode::Tab);
press_prompt(&mut board, KeyCode::Tab);
assert_eq!(prompt_line(&board), Some("comment"));
assert_eq!(board.suggestion(), None, "a second offer was drawn against a candidate");
}
/// The walk is over by the next keypress, so a candidate stepped onto is kept and the
/// next press starts a new one.
#[test]
fn an_edit_ends_the_walk_and_leaves_what_it_chose_on_the_row() {
let (_dir, mut board) = completable();
board.open_prompt();
type_line(&mut board, "ls d");
press_prompt(&mut board, KeyCode::Tab);
assert_eq!(prompt_line(&board), Some("ls done"));
// A backspace is an edit, so the next press walks the line as it now stands rather
// than stepping on from where the last one had got to.
press_prompt(&mut board, KeyCode::Backspace);
assert_eq!(prompt_line(&board), Some("ls don"));
press_prompt(&mut board, KeyCode::Tab);
assert_eq!(prompt_line(&board), Some("ls done"));
}
// ------------------------------------------------------------------ the copy key --
/// A sink that records what it was handed, standing in for the clipboard.
+238 -26
View File
@@ -349,12 +349,33 @@ pub fn without_escapes(text: &str) -> String {
/// `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.
///
/// A warning is the second stream, [`Warnings`], for the same reason the first one
/// exists: `eprintln!` in a helper reaches the process's stderr, which under the board
/// is the alternate screen.
pub struct Sink<'a> {
writer: Box<dyn Write + 'a>,
/// Where a warning goes, which is not where the answer goes.
warnings: Warnings<'a>,
/// Whether the bytes this sink writes carry colour escapes.
pub use_color: bool,
}
/// What a sink does with a warning: the aside a command writes on its way to an
/// answer, which the reader wants and no caller parses.
///
/// Two streams rather than one, because the CLI's two are two: a warning has always
/// gone to stderr and the answer to stdout, and [`Sink::std`] cannot fold them
/// together without changing what a shell reads. Under the board neither is a stream
/// at all — stdout is the alternate screen in raw mode, and so is stderr — so the
/// warning is held instead and the board reports it beside the answer.
enum Warnings<'a> {
/// A writer of its own: `main`'s stderr.
Stream(Box<dyn Write + 'a>),
/// Kept in memory for a caller that reads it back through [`Sink::warnings`].
Held(Vec<u8>),
}
impl<'a> Sink<'a> {
/// The process's stdout, coloured by what the terminal wants.
///
@@ -362,8 +383,14 @@ impl<'a> Sink<'a> {
/// 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())
// The one sink whose warnings have a stream to go to, and the reason there is a
// choice at all: stderr here is a terminal or a pipe the caller is reading, and
// holding a warning back would take it off a shell's screen.
Sink::with_warnings(
Box::new(std::io::stdout()),
Box::new(std::io::stderr()),
should_use_colors(),
)
}
/// An in-memory buffer, plain, for a test or a caller that colours the text
@@ -373,15 +400,33 @@ impl<'a> Sink<'a> {
/// and the board styles them with ratatui, which is also why it must not be handed
/// a coloured one — a paragraph prints an escape rather than obeying it.
pub fn buffer(target: &'a mut Vec<u8>) -> Sink<'a> {
Sink::new(Box::new(target), false)
}
/// Any writer, with the colour decision given. Its warnings are held: a caller
/// that named one destination named nowhere for an aside to go, and `main`'s
/// stderr is [`Sink::std`]'s alone.
pub fn new(writer: Box<dyn Write + 'a>, use_color: bool) -> Sink<'a> {
Sink {
writer: Box::new(target),
use_color: false,
writer,
warnings: Warnings::Held(Vec::new()),
use_color,
}
}
/// Any writer, with the colour decision given.
pub fn new(writer: Box<dyn Write + 'a>, use_color: bool) -> Sink<'a> {
Sink { writer, use_color }
/// An answer and the asides that go with it, as two writers, with the colour
/// decision given. What [`Sink::std`] is built from, and the only way to a sink
/// whose warnings leave it rather than being held.
pub fn with_warnings(
writer: Box<dyn Write + 'a>,
warnings: Box<dyn Write + 'a>,
use_color: bool,
) -> Sink<'a> {
Sink {
writer,
warnings: Warnings::Stream(warnings),
use_color,
}
}
/// The writer, for a caller that already knows how to fill it (the completions
@@ -404,9 +449,51 @@ impl<'a> Sink<'a> {
Ok(())
}
/// Write `text` and a newline as a warning, the way `eprintln!` did.
///
/// For the aside a command makes on its way to an answer: something the reader
/// should know that does not stop the command and that nothing reading its output
/// should have to skip past. A handler reaching `eprintln!` instead wrote straight
/// to the process's stderr, which under the board is the alternate screen, and
/// ratatui does not repaint a cell it believes is unchanged — so the fragment stayed
/// on the columns until something else redrew them.
pub fn warnln(&mut self, text: &str) -> Result<()> {
match &mut self.warnings {
Warnings::Stream(writer) => {
writer.write_all(text.as_bytes())?;
writer.write_all(b"\n")?;
}
Warnings::Held(bytes) => {
bytes.extend_from_slice(text.as_bytes());
bytes.push(b'\n');
}
}
Ok(())
}
/// What this sink held back, for the caller that reads its warnings rather than
/// letting them reach a stream.
///
/// Empty for a sink whose warnings have somewhere of their own to go, since those
/// bytes are already gone. Read it after the handler returns and on both outcomes:
/// a command that warns and is then refused wrote both, and the warning is the half
/// that says why the refusal names one blocker and not two.
pub fn warnings(&self) -> String {
match &self.warnings {
Warnings::Stream(_) => String::new(),
Warnings::Held(bytes) => String::from_utf8_lossy(bytes).to_string(),
}
}
/// Flush the writer, so a prompt reaches the terminal before a read.
///
/// Both writers: a warning left in stderr's buffer while the answer reached stdout
/// is a warning the reader sees after the sentence it was about, or not at all.
pub fn flush(&mut self) -> Result<()> {
self.writer.flush()?;
if let Warnings::Stream(writer) = &mut self.warnings {
writer.flush()?;
}
Ok(())
}
@@ -562,6 +649,32 @@ pub const ACTOR_ENV: &str = "WORKLANE_ACTOR";
/// The author written when nothing names one.
pub const UNKNOWN_ACTOR: &str = "unknown";
/// Who is making the call, which decides whether [`ACTOR_ENV`] describes them.
///
/// The variable is set once in the environment an agent runs in, so every call that agent
/// makes carries its name, which is exactly what a board several agents write to needs. A
/// line typed at the command prompt is not one of those calls: nothing but the reader can
/// type it, and a person who exported the variable where their own shell picks it up —
/// the obvious way to configure it for the agents on that machine — would otherwise watch
/// their own `mv` recorded as the agent's.
///
/// So the board attributes to the person, which is `--actor-from-git`'s precedence
/// applied by default rather than asked for. It is a parameter of [`dispatch`] and not a
/// field on the parsed arguments, so a command that grows an `--actor` tomorrow is
/// attributed correctly from both callers without an arm anywhere rewriting what clap
/// produced.
///
/// [`dispatch`]: crate::dispatch
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Attribution {
/// The process's own session: the variable, then the git user. Every call from a
/// shell or a script, which is every call `main` dispatches.
Session,
/// The person at the board: the git user, and [`UNKNOWN_ACTOR`] where none is
/// configured, never the variable.
Person,
}
/// The actor for the whole run, from the variable alone.
///
/// Split out from the caching wrapper for the reason `colors_wanted` is: a threaded test
@@ -588,11 +701,18 @@ fn session_actor(env: Option<&str>) -> Option<String> {
/// has nobody to name, which reads [`UNKNOWN_ACTOR`] rather than quietly attributing
/// back to the agent. Without it, today's chain: the variable, then the git user.
///
/// [`Attribution::Person`] asks for that same lift without the flag, because a line typed
/// at the board is the reader's own action and there is nothing to say. The two are one
/// branch rather than two: a `--actor-from-git` typed at the prompt asks for what the
/// prompt does anyway, and an explicit `--actor` outranks both, which is how the reader
/// puts somebody else's name on their own keystrokes.
///
/// `git_user` is a closure in both branches so the subprocess it costs is not run when
/// something ahead of it already answered.
fn entry_actor(
flag: Option<&str>,
from_git: bool,
by: Attribution,
session: Option<&str>,
git_user: impl FnOnce() -> Option<String>,
) -> String {
@@ -600,7 +720,7 @@ fn entry_actor(
return name.to_string();
}
if from_git {
if from_git || matches!(by, Attribution::Person) {
return git_user().unwrap_or_else(|| UNKNOWN_ACTOR.to_string());
}
@@ -611,13 +731,14 @@ fn entry_actor(
git_user().unwrap_or_else(|| UNKNOWN_ACTOR.to_string())
}
/// Who to attribute an entry to, from the flags the call carried.
/// Who to attribute an entry to, from the flags the call carried and who is calling.
///
/// Precedence: flag, then — unless `from_git` lifted it — `WORKLANE_ACTOR`, then the git
/// user, then `unknown`. Every entry the CLI writes goes through here, so a board
/// several agents write to says which of them wrote what instead of attributing all of
/// it to one human.
pub fn resolve_actor(flag: Option<&str>, from_git: bool) -> String {
/// Precedence: flag, then — unless `from_git` or [`Attribution::Person`] lifted it —
/// `WORKLANE_ACTOR`, then the git user, then `unknown`. Every entry the CLI writes goes
/// through here, so a board several agents write to says which of them wrote what
/// instead of attributing all of it to one human, and a line the person typed at the
/// board is theirs rather than whichever agent's variable their shell exports.
pub fn resolve_actor(flag: Option<&str>, from_git: bool, by: Attribution) -> String {
// Each half is decided once, the way should_use_colors is: neither input can change
// mid-run, and the git user costs a subprocess. They are two caches rather than one,
// because baking the git user into the session's answer would leave `--actor-from-git`
@@ -631,7 +752,7 @@ pub fn resolve_actor(flag: Option<&str>, from_git: bool) -> String {
session_actor(env.as_deref())
});
entry_actor(flag, from_git, session.as_deref(), || {
entry_actor(flag, from_git, by, session.as_deref(), || {
GIT_USER.get_or_init(get_git_user).clone()
})
}
@@ -3928,14 +4049,17 @@ mod tests {
fn the_variable_names_the_actor() {
let session = session_actor(Some("claude"));
let git_user = || Some("Ansho Rei".to_string());
assert_eq!(entry_actor(None, false, session.as_deref(), git_user), "claude");
assert_eq!(
entry_actor(None, false, Attribution::Session, session.as_deref(), git_user),
"claude"
);
}
#[test]
fn the_flag_overrides_the_variable() {
let session = session_actor(Some("claude"));
assert_eq!(
entry_actor(Some("opencode"), false, session.as_deref(), || None),
entry_actor(Some("opencode"), false, Attribution::Session, session.as_deref(), || None),
"opencode"
);
}
@@ -3945,7 +4069,13 @@ mod tests {
fn the_git_user_is_the_fallback() {
let git_user = || Some("Ansho Rei".to_string());
assert_eq!(
entry_actor(None, false, session_actor(None).as_deref(), git_user),
entry_actor(
None,
false,
Attribution::Session,
session_actor(None).as_deref(),
git_user
),
"Ansho Rei"
);
}
@@ -3958,7 +4088,10 @@ mod tests {
let git_user = || Some("Ansho Rei".to_string());
for raw in ["", " "] {
let session = session_actor(Some(raw));
assert_eq!(entry_actor(None, false, session.as_deref(), git_user), "Ansho Rei");
assert_eq!(
entry_actor(None, false, Attribution::Session, session.as_deref(), git_user),
"Ansho Rei"
);
}
}
@@ -3966,9 +4099,15 @@ mod tests {
#[test]
fn nothing_at_all_is_unknown() {
let session = session_actor(None);
assert_eq!(entry_actor(None, false, session.as_deref(), || None), UNKNOWN_ACTOR);
assert_eq!(
entry_actor(None, false, Attribution::Session, session.as_deref(), || None),
UNKNOWN_ACTOR
);
// An empty flag falls through rather than writing a blank author
assert_eq!(entry_actor(Some(""), false, None, || None), UNKNOWN_ACTOR);
assert_eq!(
entry_actor(Some(""), false, Attribution::Session, None, || None),
UNKNOWN_ACTOR
);
}
/// Free text, validated against nothing, the way the `chown` user is.
@@ -3976,7 +4115,7 @@ mod tests {
fn an_actor_is_free_text() {
let session = session_actor(Some("claude-code, session 3 (opus)"));
assert_eq!(
entry_actor(None, false, session.as_deref(), || None),
entry_actor(None, false, Attribution::Session, session.as_deref(), || None),
"claude-code, session 3 (opus)"
);
}
@@ -3987,7 +4126,10 @@ mod tests {
fn from_git_lifts_the_git_user_over_the_variable() {
let session = session_actor(Some("claude"));
let git_user = || Some("Ansho Rei".to_string());
assert_eq!(entry_actor(None, true, session.as_deref(), git_user), "Ansho Rei");
assert_eq!(
entry_actor(None, true, Attribution::Session, session.as_deref(), git_user),
"Ansho Rei"
);
}
/// An explicit `--actor` still wins outright beside the lift: it names somebody
@@ -3997,7 +4139,7 @@ mod tests {
let session = session_actor(Some("claude"));
let git_user = || Some("Ansho Rei".to_string());
assert_eq!(
entry_actor(Some("opencode"), true, session.as_deref(), git_user),
entry_actor(Some("opencode"), true, Attribution::Session, session.as_deref(), git_user),
"opencode"
);
}
@@ -4007,7 +4149,10 @@ mod tests {
#[test]
fn from_git_with_no_git_user_is_unknown_not_the_variable() {
let session = session_actor(Some("claude"));
assert_eq!(entry_actor(None, true, session.as_deref(), || None), UNKNOWN_ACTOR);
assert_eq!(
entry_actor(None, true, Attribution::Session, session.as_deref(), || None),
UNKNOWN_ACTOR
);
}
/// An empty variable still counts as unset with the lift on, which here means the
@@ -4016,11 +4161,78 @@ mod tests {
fn from_git_leaves_the_empty_variable_unset() {
let git_user = || Some("Ansho Rei".to_string());
assert_eq!(
entry_actor(None, true, session_actor(Some("")).as_deref(), git_user),
entry_actor(
None,
true,
Attribution::Session,
session_actor(Some("")).as_deref(),
git_user
),
"Ansho Rei"
);
}
/// The board's own case, and the reason this parameter exists: the person who
/// exported `WORKLANE_ACTOR` for the agents on their machine types a command at the
/// prompt, and the entry is theirs. No flag was given and none should have to be.
#[test]
fn a_line_typed_at_the_board_is_the_persons() {
let session = session_actor(Some("claude"));
let git_user = || Some("Ansho Rei".to_string());
assert_eq!(
entry_actor(None, false, Attribution::Person, session.as_deref(), git_user),
"Ansho Rei"
);
}
/// `--actor` still wins there, which is how the reader puts somebody else's name on
/// their own keystrokes.
#[test]
fn the_flag_wins_over_the_board_too() {
let session = session_actor(Some("claude"));
let git_user = || Some("Ansho Rei".to_string());
assert_eq!(
entry_actor(Some("alice"), false, Attribution::Person, session.as_deref(), git_user),
"alice"
);
}
/// And the lift is not a fallback here either. A machine with no git user configured
/// has nobody to name, and writing the variable's value would be the agent's name on
/// the person's move, which is the whole thing this avoids.
#[test]
fn the_board_with_no_git_user_is_unknown_not_the_variable() {
let session = session_actor(Some("claude"));
assert_eq!(
entry_actor(None, false, Attribution::Person, session.as_deref(), || None),
UNKNOWN_ACTOR
);
}
/// `--actor-from-git` typed at the prompt asks for what the prompt does anyway, so
/// the two together are the one lift rather than two that could disagree.
#[test]
fn from_git_at_the_board_is_the_same_lift() {
let session = session_actor(Some("claude"));
let git_user = || Some("Ansho Rei".to_string());
assert_eq!(
entry_actor(None, true, Attribution::Person, session.as_deref(), git_user),
"Ansho Rei"
);
}
/// The session's own chain is untouched: the same command typed in a shell is still
/// the variable's, which is what keeps a board several agents write to legible.
#[test]
fn the_session_keeps_the_variable_over_the_git_user() {
let session = session_actor(Some("claude"));
let git_user = || Some("Ansho Rei".to_string());
assert_eq!(
entry_actor(None, false, Attribution::Session, session.as_deref(), git_user),
"claude"
);
}
#[test]
fn unset_values_are_dimmed_and_set_ones_are_not() {
// Both paths, now that the colour decision is a parameter: with colour off the
+149 -4
View File
@@ -131,6 +131,21 @@ fn stderr(out: &std::process::Output) -> String {
String::from_utf8_lossy(&out.stderr).to_string()
}
/// A listing with its column padding collapsed, for an assertion about what a row says
/// rather than about where its columns sit.
///
/// The alignment is the subject of `campaign_ls_lines_its_columns_up_whatever_the_titles_are`
/// and of the colour test beside `cmd_campaign_ls`; every other test is about the words,
/// and one that spelled the padding out would have to be edited whenever a fixture gained
/// a longer title.
fn squeezed(listing: &str) -> String {
listing
.lines()
.map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join("\n")
}
fn find(worklane: &Path, uuid: &str) -> PathBuf {
for status in ["backlog", "committed", "reviewing", "done"] {
for entry in fs::read_dir(worklane.join(status))
@@ -433,7 +448,7 @@ fn campaign_ls_lists_campaigns_with_their_member_counts() {
let out = run(&temp, &["campaign", "ls"]);
assert!(out.status.success(), "{}", stderr(&out));
let listing = stdout(&out);
let listing = squeezed(&stdout(&out));
// One of the two members is in done, so the campaign is open and half finished.
assert!(listing.contains("v1 release | 1/2 done [open]"), "{listing}");
// Nothing has been filed against the other one.
@@ -481,6 +496,136 @@ fn campaign_ls_ids_says_nothing_on_a_board_with_no_campaigns() {
assert!(stdout(&run(&temp, &["campaign", "ls"])).contains("No campaigns yet"));
}
/// The state filter, against the same three answers `Standing::state` gives: a campaign
/// with work left, one with none, and one nothing has been filed against.
#[test]
fn campaign_ls_state_lists_only_the_campaigns_in_that_state() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
// v1 holds a backlog member and v2 holds a done one, so the two are open and done.
run(&temp, &["assign", "v1 release", MEMBER]);
run(&temp, &["assign", "v2 release", OTHER]);
run(&temp, &["campaign", "add", "--title", "Nothing filed yet"]);
let open = squeezed(&stdout(&run(&temp, &["campaign", "ls", "--state", "open"])));
assert!(open.contains("v1 release | 0/1 done [open]"), "{open}");
assert!(!open.contains("v2 release"), "a done campaign was listed as open: {open}");
assert!(!open.contains("Nothing filed yet"), "{open}");
let done = squeezed(&stdout(&run(&temp, &["campaign", "ls", "--state", "done"])));
assert!(done.contains("v2 release | 1/1 done [done]"), "{done}");
assert!(!done.contains("v1 release"), "{done}");
// The third value, which is what makes every campaign on the board reachable: a
// memberless one is neither open nor done, deliberately, and it is the one a
// grooming sweep is looking for.
let empty = squeezed(&stdout(&run(&temp, &["campaign", "ls", "--state", "empty"])));
assert!(empty.contains("Nothing filed yet | no members"), "{empty}");
assert!(!empty.contains("v1 release"), "{empty}");
assert!(!empty.contains("v2 release"), "{empty}");
// And it reaches the machine-readable listing the way `ls --ids` keeps its filters.
let ids = stdout(&run(&temp, &["campaign", "ls", "--ids", "--state", "empty"]));
assert_eq!(ids.lines().count(), 1, "{ids}");
assert!(ids.contains("Nothing filed yet"), "{ids}");
}
/// A value the enum does not hold is clap's to refuse, so nothing is read and the exit
/// code is the usage error's.
#[test]
fn campaign_ls_refuses_a_state_that_is_not_one() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
let out = run(&temp, &["campaign", "ls", "--state", "backlog"]);
assert_eq!(out.status.code(), Some(2), "{}", stderr(&out));
let said = stderr(&out);
assert!(said.contains("open"), "{said}");
assert!(said.contains("empty"), "{said}");
}
/// A filter that matches nothing says so and names what was asked for. Going silent
/// would read as the other empty case, a board with no campaigns on it, which has a
/// message of its own.
#[test]
fn campaign_ls_says_when_the_filter_matched_nothing() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
let out = run(&temp, &["campaign", "ls", "--state", "done"]);
assert!(out.status.success(), "{}", stderr(&out));
let said = stdout(&out);
assert!(said.contains("--state done"), "the filter is not named: {said}");
assert!(!said.contains("No campaigns yet"), "the other empty case: {said}");
// The completion path stays silent, filtered or not.
assert_eq!(stdout(&run(&temp, &["campaign", "ls", "--ids", "--state", "done"])), "");
}
/// The columns line up whatever the titles are, which is what the padding is for. The
/// fixture's two titles are the same length, so this one files a third with a long title
/// and a codename: the row that pushes the column is the row that proves it moved for
/// every other row too.
#[test]
fn campaign_ls_lines_its_columns_up_whatever_the_titles_are() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
run(
&temp,
&[
"campaign",
"add",
"--title",
"A campaign with a much longer title than the others",
"--codename",
"beaver",
],
);
run(&temp, &["assign", "v1 release", MEMBER]);
let listing = stdout(&run(&temp, &["campaign", "ls"]));
let rows: Vec<&str> = listing.lines().filter(|line| line.contains(" | ")).collect();
assert_eq!(rows.len(), 3, "{listing}");
for column in [" (", " | "] {
let offsets: Vec<Option<usize>> = rows.iter().map(|row| row.find(column)).collect();
assert!(
offsets.iter().all(|at| *at == offsets[0]),
"`{column}` is ragged across the rows:\n{listing}"
);
}
// The state sits at one offset too, on the rows that have one: a campaign with no
// members has nothing in brackets and pads to where the next row's bracket is.
let states: Vec<Option<usize>> = rows
.iter()
.filter(|row| row.contains('['))
.map(|row| row.find('['))
.collect();
assert!(!states.is_empty(), "no row carried a state: {listing}");
assert!(
states.iter().all(|at| *at == states[0]),
"the state column is ragged:\n{listing}"
);
}
/// The created stamp the campaign file already carries, in the form `ls` prints one in
/// rather than a second spelling of a date.
#[test]
fn campaign_ls_shows_the_created_date() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
let listing = stdout(&run(&temp, &["campaign", "ls"]));
assert!(listing.contains("26-08-21:02"), "no created stamp: {listing}");
// Not in the machine-readable listing, which is the id and the title and nothing else.
let ids = stdout(&run(&temp, &["campaign", "ls", "--ids"]));
assert!(!ids.contains("26-08-21"), "{ids}");
}
/// A campaign is done when it holds members and every one of them is done. An empty one
/// is neither, which is why it reads `no members` rather than `0/0 done`.
#[test]
@@ -490,7 +635,7 @@ fn a_campaign_whose_every_member_is_done_reads_done() {
run(&temp, &["assign", "v1 release", OTHER]);
let listing = stdout(&run(&temp, &["campaign", "ls"]));
let listing = squeezed(&stdout(&run(&temp, &["campaign", "ls"])));
assert!(listing.contains("v1 release | 1/1 done [done]"), "{listing}");
}
@@ -1726,13 +1871,13 @@ fn a_discarded_member_counts_as_finished() {
run(&temp, &["assign", "v1 release", OTHER]);
// Two members, one done and one in the backlog: open and half finished.
let listing = stdout(&run(&temp, &["campaign", "ls"]));
let listing = squeezed(&stdout(&run(&temp, &["campaign", "ls"])));
assert!(listing.contains("v1 release | 1/2 done [open]"), "{listing}");
let discarded = run(&temp, &["mv", MEMBER, "--status", "discarded"]);
assert!(discarded.status.success(), "{}", stderr(&discarded));
let listing = stdout(&run(&temp, &["campaign", "ls"]));
let listing = squeezed(&stdout(&run(&temp, &["campaign", "ls"])));
assert!(listing.contains("v1 release | 2/2 done [done]"), "{listing}");
}
+14 -3
View File
@@ -906,6 +906,11 @@ fn mv_does_not_check_the_blockers_on_a_no_op() {
/// A dangling target is a bookkeeping fault, not a dependency. Refusing there would
/// wedge the ticket with no way out but `--force`.
///
/// The stderr is asserted whole rather than searched, and that is the point of the
/// assertion: c680e24 moved this warning off `eprintln!` and onto the sink's second
/// stream so the board could collect it, and a shell has to go on reading the line it
/// always read, on the stream it always read it from.
#[test]
fn mv_warns_and_allows_when_a_blocker_is_not_on_the_board() {
let temp = TempDir::new().unwrap();
@@ -920,10 +925,16 @@ fn mv_warns_and_allows_when_a_blocker_is_not_on_the_board() {
let out = move_ticket(&temp, "aaaa1111", "committed", false);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(
String::from_utf8_lossy(&out.stderr),
"Warning: ticket 'Gated Task' is blocked by bbbb222, which is not on the board.\n",
"the warning is not the line it was, on the stream it was on"
);
// And it stays off stdout, which is what a caller reads the answer from.
assert!(
String::from_utf8_lossy(&out.stderr).contains("not on the board"),
"{}",
String::from_utf8_lossy(&out.stderr)
!String::from_utf8_lossy(&out.stdout).contains("not on the board"),
"the warning landed in the answer: {}",
String::from_utf8_lossy(&out.stdout)
);
assert!(worklane.join("committed").join(&filename).exists());
}