Compare commits

..
3 Commits
Author SHA1 Message Date
Ansho ReiandClaude Opus 5 c437d87e9e (2f3796e) Add a --tag filter to worklane ls, and bump to 0.14.0
Tickets carry a Tags field, but ls could not select on it: finding what is
tagged bug meant reading the board. Step 1 of the plan was already done by
e41802b, which put tags: Vec<String> on TicketItem through parse_tags, so this
is the flag, the filter and the tests.

Whole values, not the field. parse_tags has already split and trimmed the
comma-separated field, so filter_by_tag compares against those values: --tag
bug is not answered by a ticket tagged bugfix, --tag "cli, filter" matches
nothing because the field as written is not itself a tag, and a ticket with no
tags matches none, however it spells it.

Case sensitive, which is the opinion the field already takes everywhere else.
tag_color draws Bug and bug in two colours because they are two tags to the
field, and a filter that folded them would list tickets carrying a tag nobody
asked for while hiding exactly the split a grooming sweep is looking for.

One tag per invocation. Several would have to decide between and and or, and
that decision is its own ticket, along with substring or regex matching and a
tag filter on the board.

A tag nothing carries lists nothing rather than being refused, deliberately
the opposite of --campaign. A campaign is an object that exists or does not,
so it is resolved before anything is read; a tag is free text with no
registry, and refusing an unknown one would mean maintaining a vocabulary the
format does not have. An emptied status keeps the message ls already gives
rather than one per filter naming what excluded them, which is what --priority
and --campaign already do.

The filter goes through filtered, the one call the three collect sites share,
so the counts are filtered by the same set as the rows. Every filter is an
Option and none asked for keeps everything, which is what makes them compose
in any combination. cmd_ls is now at four filters and the directory, two of
them adjacent &Option<String> parameters a caller can swap silently: left as
positionals rather than refactored mid-feature, with AGENTS.md recording that
the next filter takes an LsArgs struct the way add took AddArgs.

assets/PLAN.md said in as many words that there was no tag filter yet, so it
would have been actively wrong. It now says what --tag can and cannot answer:
it finds what is tagged bug, it does not enumerate the vocabulary, which is
the question a grooming sweep starts from. The README's ls row also gained
--campaign, which had never been documented there.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 14:54:50 +02:00
Ansho ReiandClaude Opus 5 0ce3fdb246 (0546fc5) Copy the selected id with y in the tui, and bump to 0.13.7
The board is where a ticket is found and the CLI is where it is acted on, and
the only thing joining them was seven characters retyped off the screen. y
reads as yank to the readers a keyboard board is for, and was the letter left
after q, esc, enter, space, hjkl, the arrows, pgup, pgdn, tab, backtab, d and
/ took theirs.

The mechanism was chosen against ssh, which is where a board is often read.
OSC 52 crosses the connection, because it is the terminal at the reader's own
end that owns the clipboard. A crate wants X11 and Wayland libraries at build
time and, on X11, hands the selection to the process that set it: copy an id,
quit, and the paste buffer is empty, which is precisely the flow this key
exists for. Shelling out to wl-copy, xclip or pbcopy is platform sniffing plus
a spawn, and does nothing where none of them is installed. crossterm 0.28 is
what ratatui 0.29 pins and ships no clipboard command, so the sequence and its
base64 are twenty lines in src/clipboard.rs, pinned on the RFC 4648 vectors.

The cost is recorded rather than hidden, in AGENTS.md under The Copy Key: a
terminal that ignores OSC 52 ignores it silently, and tmux needs set-clipboard
on. What clipboard::copy reports is whether the sequence was written, and the
footer says no more than that. There is no reply to read either, since the
query form is refused by most emulators.

What is copied is ticket.id, the seven characters the card already prints and
every command already resolves, decided by Board::copy_text so the string is a
question the suite can ask without a clipboard. None on an empty column: an
empty string would take away whatever the reader had there and give nothing
back. The project is left off even on the merge tab, since a second word would
have to be deleted out of every paste.

Board::copy_selected_id takes the clipboard as an argument, clipboard::copy
from the dispatch and a closure from a test, which is what makes the hit and
the refusal both drivable. A failure is said in the footer rather than
returned: there is nobody above it to handle one, and an error swallowed there
would look exactly like a copy that worked until the paste came out wrong.

Notice is the board's first channel for saying something in words, and it has
to be, because a copy leaves nothing on screen to look at. failed means
nothing reached the clipboard, so an empty column and a refused write are one
answer to the reader, both in brightred like the search's no match. It takes
the whole footer row, since a message squeezed in beside the keys would move
every key in it. Cleared by the next keypress rather than on a timer: no clock
on the board, no wakeup in the loop, and never in tick, which runs four times
a second. clear_notice goes ahead of search_key as well as the arms, because a
key typed into a query is still a key.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 14:36:09 +02:00
Ansho ReiandClaude Opus 5 37dbd722e0 (3b16540) Open a search with / in the tui, and bump to 0.13.6
Finding a ticket meant scrolling four columns and reading, which is what the
id and the title are for.

The real work was the input mode: every key in the dispatch was a single-shot
action, and a query needs one that swallows the keys bound to them. That is
Board::search_key, offered every key ahead of the action arms and reporting
what it took. With no prompt open it takes nothing, so every other state's
dispatch is unchanged. On Board for the reason dismiss is: the arm is not
reachable from a test.

ctrl-c is the one key the prompt declines, since a terminal application
always honours it. Every other control combination is swallowed and does
nothing: it must not type its letter, and it must not fall through either,
because the action arms match on the code alone and ctrl-d would reach the
arm bound to d.

first_match runs over every card in the visible columns, in reading order,
not the rows on screen: a query that answered differently on a tall terminal
and a short one is not a search, and the jump scrolls the match into view. A
hidden done column stays out, or the highlight would land on a ticket that is
not on the board. Id and title only, both lowercased.

The jump goes through select_at, extracted as the tail select_card already
used, so follow_selection scrolls the match's own column and refresh_detail
keeps an open overlay on it. Nothing calculates either a second way.

A hit closes the prompt; a miss keeps it open, marked in brightred beside the
query it is about, with the selection untouched, so the query can be
corrected in place rather than retyped from /. The mark clears on the next
edit. An empty query matches nothing rather than everything.

The prompt takes the whole footer row, since the key list it replaces
describes nothing that works while every key goes into the buffer. The real
terminal cursor sits after the query: ratatui shows it only for a frame that
asked, so it is also what says "you are typing" on an empty query. Both
closed footers now name / search.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 13:29:30 +02:00
12 changed files with 1222 additions and 19 deletions
+38
View File
@@ -7,6 +7,7 @@
- `src/util.rs` - the ticket format, resolution, rendering and the palette
- `src/campaign.rs` - the campaign file format, its resolution, its index and its members
- `src/tui.rs` - board state, the change digest, and the ratatui draw
- `src/clipboard.rs` - the OSC 52 write and the base64 it carries, the board's only way out to the clipboard
- `src/install.rs` - the embedded agent assets and the compare-and-refuse install
- `assets/SKILL.md` - the agent skill for the CLI itself, embedded with `include_str!`
- `assets/REVIEW.md` - the agent skill for reviewing a finished ticket, shipped the same way. Assets are named after the role they teach; `SKILL.md` keeps its name because the role it teaches is the CLI
@@ -63,6 +64,15 @@ and this file is for what someone changing worklane's own code needs.
- **A paragraph break in a description is an empty `--description` value.** `cmd_add` joins the values with a single newline, so `-d "First." -d "" -d "Second."` writes the blank line. `trim_blank_ends()` drops blank values at either end, so a break never lands against a section heading, and an all-blank description reads as no description. Interior runs are kept verbatim rather than collapsed
- `--acceptance` and `--plan` are lists, one criterium or step per value, so a blank there is spacing rather than content and the opencode wrapper drops it. Only `--description` preserves blanks
### Filtering the Listing
- **The filters are one call, `filtered`,** because `ls` collects a column in three places (a named status, the counts, and the grouped listing) and three call sites are three chances to apply a different set. Every filter is an `Option` and none asked for keeps everything, which is what makes them compose in any combination without a rule per pair
- **`--tag` matches whole values, not the field.** `parse_tags` has already split the comma-separated field, so the filter compares against those trimmed values: `--tag bug` is not answered by a ticket tagged `bugfix`, and `--tag "cli, filter"` matches nothing, because the field as written is not itself a tag. A ticket with no tags matches none
- **Case sensitive**, the opinion the field already takes: `tag_color` draws `Bug` and `bug` in two colours because they are two tags. A filter that folded them would list tickets carrying a tag nobody asked for, and would hide exactly the split a grooming sweep is looking for
- **One tag per invocation.** Several would have to decide between and and or, and neither reading is obviously right for a board this size. That decision is its own ticket, along with a substring or regex match and a tag filter on the tui
- **A tag nothing carries lists nothing rather than being refused**, which is the opposite of `--campaign`. A campaign is an object that either exists or does not, so it is resolved before anything is read and an unknown one is an error. A tag is free text with no registry: there is nothing to resolve against, and refusing an unknown one would mean maintaining a vocabulary the format deliberately does not have. `assets/PLAN.md` tells the agent to check the spelling when a listing comes back empty, since that is the failure this trades for
- An emptied status keeps the message `ls` already gives, `No tickets in '<status>' status.`, rather than one per filter naming what excluded them. That is pre-existing behaviour for `--priority` and `--campaign`, and one message for every filter is the consistent half of it. If it should name the filter, that is a change to what the CLI prints for three flags at once and belongs in its own ticket
- **`cmd_ls` is now at the boundary the Rust Style rule names:** four filters and the directory. Two of them are adjacent `&Option<String>` parameters, which a caller can swap silently, so the next filter added here takes an `LsArgs` struct the way `add` took `AddArgs`, rather than a fifth positional
### Editing a Ticket
- `set` replaces a field, `append` adds to a section. The verb carries the meaning, so no flag needs a replace-or-append prefix, and `append` only offers the sections that hold multiple lines
- **One field, one writer.** `set` has no `--owner` (that is `chown`'s) and no `--status` (that is `mv`'s). Do not add either
@@ -163,6 +173,34 @@ and this file is for what someone changing worklane's own code needs.
- The choice is not remembered between runs. worklane has no config file and one flag is not a reason to start one; if it should persist, that is its own ticket
- **Assert a column heading against the top border row, not the whole screen.** The footer names done too, so `screen.contains("done (0)")` passes on the footer whether the column is drawn or not. Three tests went vacuous that way the moment done was hidden; `headings()` and `footer()` exist so the next one does not. `headings()` locates the row through `board_area()` rather than taking row zero, since the tab row sits above it when more than one board is monitored
### The Search Prompt
- **`search: Option<Search>` is the whole mode**, the shape `detail` uses: "the prompt is open" and "what is in it" cannot disagree, and closing it leaves nothing to reset. `Search` also carries `missed`, set when enter found nothing and cleared by the next edit, since the message is about the query that missed
- **The prompt swallows every key it is given.** `Board::search_key` runs ahead of the action arms in `main.rs` and reports what it took, rather than every arm below asking whether a search is open. Typing `d` into a query must not toggle done and `q` must not quit; with no prompt open it takes nothing, so the dispatch is unchanged for every other state. The rule is on `Board` for the reason `dismiss` is: the arm is not reachable from a test
- **`ctrl-c` is the one key it declines**, because a terminal application always honours it and a prompt that ate it would leave no way off the board. Every *other* control combination is swallowed and does nothing: it must not type its letter, and it must not fall through either, since the action arms match on the code alone and `ctrl-d` would reach the one bound to `d`
- **Esc is consumed by the search before it can mean anything else**, which is the collision e7612de left behind: `esc` and `q` close the overlay, and both have to lose to an open prompt. It falls out of the pre-branch rather than being ordered by hand
- **`first_match` searches the *visible columns*, every card in them, not the rows on screen.** A query that answered differently on a tall terminal and a short one is not a search, and the jump scrolls the match into view anyway. Hidden columns stay out: with done hidden, a match there would put the highlight on a ticket that is not on the board. Reading order is column by column, then top to bottom
- Id and title only, per 3b16540, both lowercased. The title has to be case insensitive to be worth typing, and giving the id the same treatment lets a pasted id match whatever case it was copied in. An empty or all-space query matches **nothing** rather than everything
- **The jump goes through `select_at`, the tail `select_card` already used.** `follow_selection` scrolls the column the card is in, and the offsets are per column and on the `Tab`, so a jump across columns moves the right one; `refresh_detail` keeps an open overlay on the ticket the selection names. A second version of either is how a jump comes to scroll differently from the arrow keys
- **A hit closes the prompt and a miss keeps it open**, marked, with the selection untouched. The query can then be corrected in place instead of retyped from `/`. Doing nothing visible is what makes a reader retype a query that was already right
- **The prompt takes the whole footer row**, because the key list it replaces describes nothing that currently works while every key is going into the buffer. The typed query is drawn in the default foreground and the keys in grey: one is content, the other is chrome. `no match` is brightred beside the query it is about, since grey chrome is what a reader skips
- **The real terminal cursor goes after the query**, not a glyph standing in for one. ratatui shows the cursor only for a frame that asked for it, so `set_cursor_position` is also what says "you are typing" while the query is still empty. Clamped to the row, so a query longer than the terminal leaves it on the last cell
- Both closed footers name `/`, since the jump works with a ticket open as well: it moves the selection and the overlay follows
- Out of scope on purpose, each its own ticket once the input mode exists: `n` and `N` for the next and previous match, searching the description, tags or owner, regex, and filtering the board down to matches rather than selecting one
### The Copy Key
- **`y` copies the selected card's short id, over OSC 52 written by hand.** The board is where a ticket is found and the CLI is where it is acted on, and the only thing joining them was seven characters retyped off the screen. `y` reads as yank to the readers a keyboard board is for, and was the letter left: `q`, `esc`, `enter`, `space`, `hjkl`, the arrows, `pgup`, `pgdn`, `tab`, `backtab`, `d` and `/` were taken
- **The mechanism was chosen against ssh**, which is where a board is often read. An escape sequence is the only one of the three ways that crosses the connection, since it is the terminal at the reader's end that owns the clipboard. A crate (`arboard` and its kind) wants X11 and Wayland libraries at build time, and on X11 the selection belongs to the process that set it: copy an id, quit, and the paste buffer is empty, which is precisely this flow. Shelling out to `wl-copy`, `xclip` or `pbcopy` is platform sniffing plus a process spawn, and does nothing on a machine where none of them is installed or on the far end of a connection. crossterm 0.28 is what ratatui 0.29 pins and it ships no clipboard command, and the backend types have to match whatever ratatui pins, so a newer crossterm cannot be picked up on its own
- **The cost is paid knowingly: a terminal that ignores OSC 52 ignores it silently**, and tmux needs `set-clipboard on`. What `clipboard::copy` reports is whether the sequence was written, not whether it was honoured, and the footer message says no more than that. There is no reply to read: the query form of OSC 52 is refused by most emulators as a security matter, so nothing better is available to us
- Base64 is twenty lines here rather than a dependency, because the only thing that goes through it is a seven-character id. Pinned on the RFC 4648 vectors, which cover both padding forms, since a wrong encoder would put plausible-looking rubbish on the clipboard
- **`c` and not `p`**: the clipboard proper, not the X11 primary selection, since this is pasted into a command line. Terminated with BEL, which is what tmux documents and what every emulator that implements this at all accepts
- **What is copied is `ticket.id`, the seven characters the card prints**, not the full uuid: they are what stops the retyping and what `show`, `mv` and `comment` all resolve. Decided by `Board::copy_text` rather than inside the arm that copies, so the string is a question the suite can ask without a clipboard. `None` on an empty column, since an empty string would take away whatever the reader had there and give nothing back
- The project is left off even on the merge tab, where the id alone is not an address. This goes onto a clipboard to be pasted into a command line, and a second word in it would have to be deleted every time; running the command in the wrong project fails to resolve rather than acting on the wrong ticket
- **The clipboard is handed to `Board::copy_selected_id` as an argument**, `clipboard::copy` from the dispatch and a closure from a test. That is what makes both answers drivable, and it keeps the terminal write out of the board state
- **A failure is said in the footer, not returned.** There is nobody above it to handle one: the board goes on being drawn, and an error swallowed there would look exactly like a copy that worked until the paste came out wrong
- **`Notice` is the board's one channel for saying something in words**, since a copy leaves nothing on screen to look at. `failed` means "nothing reached the clipboard" rather than "an error occurred", so an empty column and a refused write are one answer to the reader, both in brightred for the reason `no match` is
- **It takes the whole footer row**, on a weaker reason than the prompt's: every key still works while a notice is up. It is that a message squeezed in beside the key list would move every key in it, and the row is the only part of the board that is not a ticket. Drawn after the prompt, which is an input and cannot be covered
- **The notice is cleared by the next keypress, not by a timer.** No clock on the board and no wakeup in the loop, and the moment the reader does anything else the message has been read or was never going to be. Doing nothing leaves it up, which is the one state where it is still worth reading. `Board::clear_notice` runs ahead of `search_key` as well as the arms, since a key typed into a query is still a key, and it must never move into `tick`: the board redraws four times a second and a notice cleared there would never be read
### Monitoring Several Boards
- `worklane tui <path>...` takes any number of paths, each resolved through `find_worklane_dir` the way the working directory is: the first `.worklane` at or above it. No path is the working directory, so a bare `worklane` and `worklane tui` are unchanged
- The failure **names the path** that had no board, since with several arguments "No .worklane directory found" does not say which one was wrong. Only when a path was given: a bare `worklane` has no path to name and keeps the message every other command gives, which is what its integration test asserts
Generated
+1 -1
View File
@@ -1494,7 +1494,7 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.13.5"
version = "0.14.0"
dependencies = [
"anyhow",
"assert_cmd",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "worklane"
version = "0.13.5"
version = "0.14.0"
edition = "2024"
[dependencies]
+2 -2
View File
@@ -5,10 +5,10 @@ Worklane is a local Kanban flow for agentic software development.
## Commands
| Command | Description |
|---------|-------------|
| `worklane` or `worklane tui [path...]` | Opens the board: four status columns, redrawn when the tree changes. Read only. Opens on backlog, committed and reviewing; `d` shows or hides done, whose count stays in the footer either way. Arrows or `hjkl` to move, `enter` for detail, `pgup`/`pgdn` to scroll an open ticket, `q` to quit. Each path opens the first `.worklane` at or above it, the working directory by default. Several paths are monitored together, as a tab per project plus an `all` tab that merges them, with `tab` and `shift+tab` between them |
| `worklane` or `worklane tui [path...]` | Opens the board: four status columns, redrawn when the tree changes. Read only. Opens on backlog, committed and reviewing; `d` shows or hides done, whose count stays in the footer either way. Arrows or `hjkl` to move, `enter` for detail, `pgup`/`pgdn` to scroll an open ticket, `/` to jump to the first ticket whose id or title matches, `y` to copy the selected ticket's short id to the clipboard, `q` to quit. Each path opens the first `.worklane` at or above it, the working directory by default. Several paths are monitored together, as a tab per project plus an `all` tab that merges them, with `tab` and `shift+tab` between them |
| `worklane init` | Creates `.worklane/` with backlog, committed, reviewing, done directories |
| `worklane add` | Creates a ticket in backlog with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--owner`, `--priority` flags. `--due` takes `YYYY-MM-DD` and refuses anything else at parse time |
| `worklane ls [status]` | Lists tickets, sorted by priority then title. Optional positional status, and `--priority <1-5>` |
| `worklane ls [status]` | Lists tickets, sorted by priority then title. Optional positional status, and `--priority <1-5>`, `--tag <tag>` and `--campaign <campaign>`, which compose in any combination. `--tag` matches a whole value of the comma-separated Tags field, case sensitively, so `--tag bug` does not list a ticket tagged `bugfix` or one tagged `Bug` |
| `worklane show <id>` | Shows ticket by UUID prefix (4+ chars), title substring, or filename substring |
| `worklane mv <id> --status <target> [-f]` | Moves ticket between statuses. Default: forward only, one stage at a time. `-f` bypasses both restrictions |
| `worklane set <ticket>` | Replaces fields with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--priority`. At least one required. Changing the title renames the file, keeping the UUID |
+7 -4
View File
@@ -56,14 +56,17 @@ The last two rows are in the table to be recognised, not used. See the closing s
worklane ls # every status, counts then tickets
worklane ls backlog # one status
worklane ls --priority 1 # the top of the pile
worklane ls --tag bug # one tag's worth of the board
worklane show 1b78a24 # one ticket, with its relations and comments
worklane campaign ls # the goals that already exist
```
`ls` prints the mark, the id, the title, the owner and the due date. It does **not**
print tags, and there is no tag filter yet, so any judgement about tags means reading the
tickets themselves. On a board of a few dozen that is a `show` per ticket and is worth
doing rather than guessing from titles.
print tags, so the vocabulary itself still has to be read off the tickets: `--tag` answers
"what is tagged `bug`" and cannot answer "what tags exist", which is the question a
grooming sweep starts from. Count the vocabulary with a `show` per ticket, then use
`--tag` to check each candidate, and remember that `--tag` matches whole values case
sensitively: `bug` and `Bug` are two answers, which is exactly the split worth reporting.
Read `done` too when the question is about what to do next. What was finished last is the
best evidence of what this board actually moves at, and a plan that ignores it is a wish.
@@ -137,7 +140,7 @@ what is actually used, and show the count before proposing anything. What to rep
that will disagree with it. This board already made that mistake once with priority and
undid it deliberately.
- **An untagged ticket** in a board where everything else is tagged. It is invisible to
every question asked by tag.
every question asked by tag, `worklane ls --tag` included.
Tags are for kind, not for state and not for goal. State is the status directory and the
fields; a goal is a campaign.
+8
View File
@@ -41,11 +41,19 @@ A move is also refused while the ticket is blocked by one that is not done yet,
worklane ls # every status, counts then tickets
worklane ls backlog # one status
worklane ls --priority 1 # only the most urgent
worklane ls --tag bug # only the tickets carrying that tag
worklane show 1b78a24 # one ticket, body and comments
```
`ls` prints a seven-character id per ticket. That is what you address it by.
The filters compose in any combination, with each other and with the status positional:
`worklane ls backlog --tag bug --priority 1`. `--tag` takes one tag and matches it
against the whole values of the comma-separated `Tags` field, case sensitively, so
`--tag bug` finds neither a ticket tagged `bugfix` nor one tagged `Bug`. A ticket with no
tags matches none. A tag nothing carries lists nothing rather than failing, so when a
listing comes back empty check the spelling against a ticket you know is tagged.
## Working a ticket
```
+90
View File
@@ -0,0 +1,90 @@
//! Putting text on the clipboard of whatever terminal is drawing the board.
//!
//! OSC 52, written by hand, and the reasoning is in AGENTS.md under The Copy Key. The
//! short of it: the board is often being read over ssh, and an escape sequence is the
//! only one of the three ways that crosses the connection. crossterm 0.28 is what
//! ratatui 0.29 pins and it ships no clipboard command, so the sequence and the base64
//! it carries are written here rather than pulled in.
//!
//! The honest limit is that a terminal which ignores OSC 52 ignores it silently: what
//! this reports is whether the sequence was written, not whether it was honoured.
use std::io::Write;
use anyhow::{Context, Result};
/// Ask the terminal to put `text` on the system clipboard.
///
/// `52;c` is the clipboard proper rather than `p`, the X11 primary selection, because
/// this is for pasting into a command line with ctrl-shift-v or cmd-v. Terminated with
/// BEL rather than ST: both are accepted, and BEL is what tmux's `set-clipboard`
/// documents and what every emulator that implements this at all takes.
///
/// Written straight to stdout, which is where ratatui's own frames go, and flushed
/// before returning so a failure belongs to this call rather than to the next draw.
pub fn copy(text: &str) -> Result<()> {
let mut out = std::io::stdout();
write!(out, "\x1b]52;c;{}\x07", base64(text.as_bytes()))
.and_then(|()| out.flush())
.context("could not write to the terminal")
}
/// Standard base64, the alphabet OSC 52 requires, padding included.
///
/// Twenty lines against a dependency: the only thing encoded here is a seven-character
/// id, and the crate would be carried for its own sake.
fn base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
// The missing bytes of a short chunk read as zero, and the characters they
// would have produced are the ones that become padding below.
let triple = chunk
.iter()
.chain([0u8; 2].iter())
.take(3)
.fold(0u32, |acc, byte| (acc << 8) | u32::from(*byte));
for slot in 0..4 {
match slot <= chunk.len() {
true => out.push(char::from(ALPHABET[(triple >> (18 - 6 * slot) & 0x3f) as usize])),
false => out.push('='),
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// The vectors from RFC 4648, which is what a terminal decodes with. Every chunk
/// length is in here, so the padding is covered in both of its forms.
#[test]
fn base64_encodes_the_rfc_vectors() {
assert_eq!(base64(b""), "");
assert_eq!(base64(b"f"), "Zg==");
assert_eq!(base64(b"fo"), "Zm8=");
assert_eq!(base64(b"foo"), "Zm9v");
assert_eq!(base64(b"foob"), "Zm9vYg==");
assert_eq!(base64(b"fooba"), "Zm9vYmE=");
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
}
/// What actually goes on the wire for a short id, which is the whole use.
#[test]
fn base64_encodes_a_short_id() {
assert_eq!(base64(b"0546fc5"), "MDU0NmZjNQ==");
}
/// The high bits reach the end of the alphabet, which an off-by-one in the shift
/// would miss entirely on ascii input.
#[test]
fn base64_reaches_the_whole_alphabet() {
assert_eq!(base64(&[0xff, 0xff, 0xff]), "////");
assert_eq!(base64(&[0xfb, 0xff, 0xfe]), "+//+");
assert_eq!(base64(&[0x00, 0x00, 0x00]), "AAAA");
}
}
+4
View File
@@ -120,6 +120,10 @@ pub enum Command {
#[arg(long, value_parser = priority_level)]
priority: Option<u8>,
/// Only show tickets carrying this tag, matched whole
#[arg(long, value_parser = non_empty)]
tag: Option<String>,
/// Only show the members of this campaign, by UUID or title
#[arg(long, value_parser = non_empty)]
campaign: Option<String>,
+37 -5
View File
@@ -40,6 +40,7 @@ pub fn cmd_init(start: &Path) -> Result<()> {
pub fn cmd_ls(
status_filter: &Option<String>,
priority_filter: Option<u8>,
tag_filter: &Option<String>,
campaign_filter: &Option<String>,
worklane_dir: &Path,
) -> Result<()> {
@@ -50,6 +51,7 @@ pub fn cmd_ls(
None => None,
};
let uuid = campaign.as_ref().map(|campaign| campaign.uuid.as_str());
let tag = tag_filter.as_deref();
if let Some(campaign) = &campaign {
println!(
@@ -68,7 +70,7 @@ pub fn cmd_ls(
));
}
let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid);
let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid, tag);
if items.is_empty() {
println!("No tickets in '{}' status.", status);
@@ -86,7 +88,7 @@ pub fn cmd_ls(
if !status_path.exists() {
continue;
}
let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid);
let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid, tag);
let count = items.len();
let label = if count == 1 { "ticket" } else { "tickets" };
println!(" [{}] {} {}", status.to_uppercase(), count, label);
@@ -102,7 +104,7 @@ pub fn cmd_ls(
continue;
}
let items = match collect_ticket_items(&status_path) {
Ok(items) => filtered(items, priority_filter, uuid),
Ok(items) => filtered(items, priority_filter, uuid, tag),
Err(_) => continue,
};
if items.is_empty() {
@@ -119,8 +121,38 @@ pub fn cmd_ls(
/// The listing filters in one call, so the three places `ls` collects a column cannot
/// end up applying a different set of them.
fn filtered(items: Vec<TicketItem>, level: Option<u8>, campaign: Option<&str>) -> Vec<TicketItem> {
filter_by_campaign(filter_by_priority(items, level), campaign)
///
/// Every filter is `Option`, and none asked for is everything kept, which is what makes
/// them compose in any combination without a rule per pair.
fn filtered(
items: Vec<TicketItem>,
level: Option<u8>,
campaign: Option<&str>,
tag: Option<&str>,
) -> Vec<TicketItem> {
filter_by_tag(
filter_by_campaign(filter_by_priority(items, level), campaign),
tag,
)
}
/// Keep only the tickets carrying `tag`, or everything when none was asked for.
///
/// Matched against the whole values `parse_tags` split out of the field rather than as a
/// substring of it, so `--tag bug` is not answered by a ticket tagged `bugfix`, and a
/// ticket with no tags matches nothing at all.
///
/// Case sensitive, the opinion the field already takes everywhere else: `tag_color`
/// draws `Bug` and `bug` in two colours because they are two tags, and a filter that
/// folded them would list tickets carrying a tag nobody asked for.
fn filter_by_tag(items: Vec<TicketItem>, tag: Option<&str>) -> Vec<TicketItem> {
match tag {
Some(tag) => items
.into_iter()
.filter(|item| item.tags.iter().any(|carried| carried == tag))
.collect(),
None => items,
}
}
/// Keep only the members of `campaign`, or everything when none was asked for.
+28 -1
View File
@@ -2,6 +2,7 @@ use anyhow::Result;
use clap::Parser;
mod campaign;
mod clipboard;
mod command;
mod handlers;
mod install;
@@ -48,10 +49,11 @@ fn main() -> Result<()> {
Some(Command::Ls {
status,
priority,
tag,
campaign,
}) => {
let worklane_dir = find_worklane_dir(&start)?;
cmd_ls(&status, priority, &campaign, &worklane_dir)
cmd_ls(&status, priority, &tag, &campaign, &worklane_dir)
}
Some(Command::Show { id }) => {
let worklane_dir = find_worklane_dir(&start)?;
@@ -163,6 +165,22 @@ fn run_tui(paths: &[std::path::PathBuf], start: &std::path::Path) -> Result<()>
continue;
}
// Every keypress takes away what the last one said, so a notice never
// outlives the moment it belongs to. Ahead of the prompt as well as the
// arms: a key typed into a query is still a key. The rule is
// `Board::clear_notice`, where a test can reach it, and the arm below that
// sets one runs after this.
board.clear_notice();
// Ahead of the arms, because a prompt has to swallow every key it is
// given: typing `d` into a query must not toggle the done column and `q`
// must not quit. It reports what it took, so the arms below stay a plain
// match on the keys it did not, and it takes nothing when no prompt is open.
// The rule is `Board::search_key`, where a test can reach it.
if board.search_key(key, screen) {
continue;
}
match key.code {
// One arm, because the two keys mean one thing: close what is open, and
// quit when there is nothing left to close. Two arms carrying one rule
@@ -192,6 +210,15 @@ fn run_tui(paths: &[std::path::PathBuf], start: &std::path::Path) -> Result<()>
KeyCode::BackTab => board.select_tab(-1, screen),
// Free of the other bindings, and the footer names it in both states.
KeyCode::Char('d') => board.toggle_done(screen),
// An ordinary single-shot action like the rest: it opens the prompt, and
// from the next keypress on `search_key` above has the keyboard. A `/`
// typed into an open prompt is taken there as a character, so this arm
// is only ever the way in.
KeyCode::Char('/') => board.open_search(),
// `y` as in yank, for the readers this board is for, and the only letter
// left that a vim hand would reach for. The clipboard is handed in rather
// than reached for inside `Board`, so the suite can drive both answers.
KeyCode::Char('y') => board.copy_selected_id(clipboard::copy),
_ => {}
}
}
+832 -5
View File
@@ -13,6 +13,7 @@ use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use anyhow::{Context, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::{Constraint, Direction, Layout, Margin, Rect, Size};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
@@ -204,6 +205,50 @@ pub struct Detail {
pub text: String,
}
/// The open search prompt: what has been typed, and whether the last enter missed.
///
/// One field on `Board` rather than a buffer beside a bool saying whether it is open,
/// the shape `detail` uses: "the prompt is open" and "what is in it" then cannot
/// disagree, and there is no state to reset when it closes.
#[derive(Debug, Default)]
pub struct Search {
pub query: String,
/// Set when enter found nothing, cleared by the next edit. The message is about the
/// query that missed, so it goes the moment the query changes.
pub missed: bool,
}
/// A line the footer carries in place of the key list until the next keypress.
///
/// The board otherwise says everything by drawing it, and a copy leaves nothing on the
/// screen to look at: the id was already there and the clipboard is somewhere else. So
/// this is the one thing the board has to say in words.
///
/// `failed` is "nothing reached the clipboard", not "an error occurred": an empty column
/// and a terminal that refused the write are the same answer to the reader, who pressed
/// a key and has nothing to paste. Both are drawn in red for the reason `no match` is.
#[derive(Debug)]
pub struct Notice {
pub text: String,
pub failed: bool,
}
impl Notice {
fn done(text: impl Into<String>) -> Self {
Notice {
text: text.into(),
failed: false,
}
}
fn failed(text: impl Into<String>) -> Self {
Notice {
text: text.into(),
failed: true,
}
}
}
/// What is on screen.
pub struct Board {
/// The monitored boards as tabs, the merge first when there is more than one.
@@ -214,6 +259,10 @@ pub struct Board {
pub detail: Option<Detail>,
/// First visible line of the detail view, counted in wrapped lines.
pub offset: u16,
/// The search prompt while it is open. `None` is the board reading keys as actions.
pub search: Option<Search>,
/// What the last action said, until the next keypress takes it away.
pub notice: Option<Notice>,
/// Whether the done column is drawn. Off at startup, and not remembered between
/// runs: worklane has no config file, and one flag is not a reason to start one.
/// Board-wide rather than per tab: it is a preference about the flow, not about a
@@ -249,6 +298,8 @@ impl Board {
tab: 0,
detail: None,
offset: 0,
search: None,
notice: None,
show_done: false,
should_quit: false,
projects,
@@ -420,7 +471,22 @@ impl Board {
return;
}
tab.card = (tab.card as isize + delta).clamp(0, count as isize - 1) as usize;
let column = tab.column;
let card = (tab.card as isize + delta).clamp(0, count as isize - 1) as usize;
self.select_at(column, card, screen);
}
/// Put the selection on one card, then bring it into view and follow it.
///
/// The tail every move shares. `follow_selection` scrolls the column the card is in,
/// and the offsets are per column and on the `Tab`, so a jump across columns moves
/// the right one. `refresh_detail` keeps an open overlay on the ticket the selection
/// names. A second version of either is how a jump comes to scroll differently from
/// the arrow keys.
fn select_at(&mut self, column: usize, card: usize, screen: Size) {
let tab = self.current_mut();
tab.column = column;
tab.card = card;
self.follow_selection(screen);
self.refresh_detail();
}
@@ -491,6 +557,135 @@ impl Board {
}
}
/// Open the prompt on an empty query.
///
/// Empty rather than the last query kept: that search is finished, and reopening on
/// it would make `/` and enter repeat a jump nobody asked for. Repeating a search is
/// `n`, which 3b16540 puts out of its own scope.
pub fn open_search(&mut self) {
self.search = Some(Search::default());
}
/// Feed a keypress to the open prompt, and say whether it was taken.
///
/// The prompt swallows every key it is given, the ones bound to actions included:
/// typing `d` into a query must not toggle the done column and `q` must not quit.
/// That is why this runs ahead of the action arms and reports what it took, rather
/// than every arm below asking whether a search is open. With no prompt open it
/// takes nothing, so the dispatch is unchanged for every other state.
///
/// `ctrl-c` is the one key it declines. A terminal application always honours it, and
/// a prompt that ate it would leave no way off the board without closing the prompt
/// first. Any other control combination is swallowed and does nothing: it must not
/// type its letter, and it must not fall through either, since the action arms match
/// on the code alone and `ctrl-d` would reach the one bound to `d`.
pub fn search_key(&mut self, key: KeyEvent, screen: Size) -> bool {
if self.search.is_none() {
return false;
}
let control = key.modifiers.contains(KeyModifiers::CONTROL);
if control && key.code == KeyCode::Char('c') {
return false;
}
match key.code {
KeyCode::Esc => self.search = None,
KeyCode::Enter => self.jump_to_match(screen),
KeyCode::Backspace => self.edit_query(|query| {
query.pop();
}),
KeyCode::Char(typed) if !control => self.edit_query(|query| query.push(typed)),
_ => {}
}
true
}
/// Change the query, and forget a miss that was about what it used to say.
fn edit_query(&mut self, edit: impl FnOnce(&mut String)) {
if let Some(search) = &mut self.search {
edit(&mut search.query);
search.missed = false;
}
}
/// Take the query to the first match, or say there was none.
///
/// A hit closes the prompt: it has done its job and the reader is back on the board.
/// A miss keeps it open and marks it, so the query can be corrected in place instead
/// of retyped from `/`, and the selection stays exactly where it was.
fn jump_to_match(&mut self, screen: Size) {
let Some(search) = &self.search else { return };
let query = search.query.clone();
let hit = first_match(self.visible(), &query);
match hit {
Some((column, card)) => {
self.search = None;
self.select_at(column, card, screen);
}
None => {
if let Some(search) = &mut self.search {
search.missed = true;
}
}
}
}
/// The string the copy key puts on the clipboard: the selected card's short id.
///
/// A method here rather than a line inside the arm that copies, so what gets copied
/// is a question a test can ask without a clipboard or a terminal to answer it.
///
/// The seven characters the card already prints and every command already takes,
/// `ticket.id` rather than the full uuid: the point of the key is to stop those seven
/// being retyped, and a `worklane show` resolves them. The project is left off on the
/// merge tab even though the id alone is not an address there. This goes on a
/// clipboard to be pasted into a command line, and a second word in it would have to
/// be deleted every time.
///
/// `None` on an empty column, so nothing is sent rather than an empty string put on
/// the clipboard over whatever the reader had there.
pub fn copy_text(&self) -> Option<String> {
self.selected().map(|card| card.ticket.id.clone())
}
/// Copy the selected id through `copy`, and say what happened.
///
/// The clipboard comes in as an argument rather than being reached for here, so the
/// suite can drive both answers: `crate::clipboard::copy` in the dispatch, a closure
/// in a test. Nothing else about the board changes, since a copy is not a move.
///
/// A failure is said in the footer rather than returned. There is nobody above this
/// to handle it: the board goes on being drawn, and an error swallowed here would
/// look exactly like a copy that worked until the paste came out wrong.
pub fn copy_selected_id(&mut self, copy: impl FnOnce(&str) -> Result<()>) {
let Some(text) = self.copy_text() else {
self.notice = Some(Notice::failed("nothing to copy"));
return;
};
self.notice = Some(match copy(&text) {
Ok(()) => Notice::done(format!("copied {text}")),
Err(err) => Notice::failed(format!("copy failed: {err}")),
});
}
/// Forget the notice, which is what every keypress does before it is dispatched.
///
/// A keypress rather than a timer: it needs no clock on the board and no wakeup in
/// the loop, and the moment the reader does anything else the message has been read
/// or was never going to be. Doing nothing leaves it up, which is the one state where
/// it is still worth reading.
///
/// Here rather than in the loop for the reason `dismiss` is: the dispatch in
/// `main.rs` is not reachable from a test, so a rule written into it is a rule
/// nothing can check.
pub fn clear_notice(&mut self) {
self.notice = None;
}
/// Scroll the open detail view by whole screenfuls, one line kept for overlap.
///
/// Up and down move the selection, so the scroll is on PageUp and PageDown. That is
@@ -649,6 +844,41 @@ fn merge(per_project: &[Vec<Column>], projects: &[Project]) -> Vec<Column> {
.collect()
}
/// The first card whose id or title holds `query`, as its column and its place in it.
///
/// Reading order: column by column left to right, then top to bottom inside a column,
/// which is how the board is laid out and how it is read.
///
/// Over every card in the columns it is given, not the rows on screen. A query that
/// answered differently on a tall terminal and a short one is not a search, and the jump
/// scrolls the match into view anyway. The caller passes the *visible* columns, so a
/// hidden done column is never searched: selecting a ticket that is not on the board
/// would leave the highlight nowhere.
///
/// Id and title only, per 3b16540, and both lowercased. The title has to be case
/// insensitive to be worth typing; giving the id the same treatment costs nothing and
/// lets a pasted id match whatever case it was copied in.
///
/// An empty query matches nothing rather than everything. Enter on a prompt nobody typed
/// into should leave the selection where it is, not jump to the first card on the board.
fn first_match(columns: &[Column], query: &str) -> Option<(usize, usize)> {
let needle = query.trim().to_lowercase();
if needle.is_empty() {
return None;
}
columns.iter().enumerate().find_map(|(index, column)| {
column
.cards
.iter()
.position(|card| {
card.ticket.id.to_lowercase().contains(&needle)
|| card.ticket.title.to_lowercase().contains(&needle)
})
.map(|card| (index, card))
})
}
/// The fingerprint of every monitored board, so a change in any of them redraws.
fn digest_of(projects: &[Project]) -> u64 {
let mut hasher = DefaultHasher::new();
@@ -1206,6 +1436,24 @@ fn with_ellipsis(row: &str, width: usize) -> String {
}
fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) {
// The prompt takes the whole row while it is open. The footer is one line and
// already says what the state allows, and with every key going into the buffer the
// key list it replaces describes nothing that currently works.
if let Some(search) = &board.search {
draw_search(frame, search, area);
return;
}
// And a notice takes it for the one keypress it lives, for a weaker reason than the
// prompt's: every key still works while it is up. It is that a message squeezed in
// beside the list would move every key in it, and the row is the only place on the
// board that is not a ticket. Ordered after the prompt, which is an input and cannot
// be covered, and a keypress clears the notice before it can open one anyway.
if let Some(notice) = &board.notice {
draw_notice(frame, notice, area);
return;
}
// While done is hidden its count goes here, which is the board's version of the
// summary line `ls` prints above a listing that leaves done out.
let done = match board.show_done {
@@ -1224,10 +1472,12 @@ fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) {
// the only key left that quits in one press. Naming `q quit` over an open overlay
// would be the fault 1b78a24 was, a footer describing a key by what it used to do.
let keys = match board.detail {
Some(_) => {
format!(" {tabs}←→↑↓ select pgup/pgdn scroll enter/q close {done} ctrl-c quit ")
}
None => format!(" {tabs}←→ column ↑↓ card enter detail {done} q quit "),
Some(_) => format!(
" {tabs}←→↑↓ select pgup/pgdn scroll / search y copy id enter/q close {done} ctrl-c quit "
),
None => format!(
" {tabs}←→ column ↑↓ card / search y copy id enter detail {done} q quit "
),
};
frame.render_widget(
@@ -1236,6 +1486,56 @@ fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) {
);
}
/// What the last keypress did, where the keys would otherwise be.
///
/// Red when nothing reached the clipboard, so a copy that did not happen does not read
/// like one that did, and the default foreground when it did: the same division the
/// prompt draws its query and its miss with.
fn draw_notice(frame: &mut Frame, notice: &Notice, area: Rect) {
let style = match notice.failed {
true => Style::default().fg(Color::BrightRed.into()),
false => Style::default(),
};
frame.render_widget(
Paragraph::new(Span::styled(format!(" {}", notice.text), style)),
area,
);
}
/// The prompt, in place of the key list it would otherwise describe wrongly.
///
/// The real terminal cursor goes after the query rather than a glyph standing in for
/// one: ratatui shows the cursor only for a frame that asked for it, and that is also
/// what tells the reader they are in an input while the query is still empty.
///
/// What was typed is drawn in the default foreground and the keys in grey, because one
/// of them is content and the other is chrome. A miss is said beside the query it is
/// about, in brightred, since grey chrome is exactly what a reader skips. Colour
/// accentuates here as it does on a card; the words carry the meaning either way.
fn draw_search(frame: &mut Frame, search: &Search, area: Rect) {
let prompt = format!(" /{}", search.query);
let mut spans = vec![Span::raw(prompt.clone())];
if search.missed {
spans.push(Span::styled(
" no match",
Style::default().fg(Color::BrightRed.into()),
));
}
spans.push(Span::styled(
" enter jump esc cancel ",
Style::default().fg(Color::Grey.into()),
));
frame.render_widget(Paragraph::new(Line::from(spans)), area);
// Held on the row, so a query longer than the terminal leaves the cursor on the last
// cell rather than off the frame.
let at = (prompt.chars().count() as u16).min(area.width.saturating_sub(1));
frame.set_cursor_position((area.x + at, area.y));
}
/// How many tickets are in done on the tab in view, drawn or not.
fn done_count(board: &Board) -> usize {
board
@@ -2706,6 +3006,533 @@ mod tests {
assert!(row.contains("ctrl-c quit"), "nothing says what quits from here:\n{row}");
}
// ------------------------------------------------------------------- searching --
/// A keypress with nothing held, which is what typing into a prompt is.
fn typed(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn letter(c: char) -> KeyEvent {
typed(KeyCode::Char(c))
}
/// Type a whole query into an open prompt, one key at a time, the way it arrives.
fn type_query(board: &mut Board, query: &str) {
for c in query.chars() {
assert!(board.search_key(letter(c), SCREEN), "'{c}' was not taken");
}
}
/// A board with something to find in three columns, done included.
fn searchable() -> PathBuf {
let dir = board_dir();
write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha first", "");
write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta second", "");
write_ticket(&dir, "committed", "33333333-0000-4000-8000-000000000000", "Gamma third", "");
write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Delta finished", "");
dir
}
/// The prompt takes the row, and the board is still drawn behind it.
#[test]
fn the_prompt_replaces_the_footer_and_leaves_the_board_up() {
let dir = searchable();
let mut board = one_board(&dir);
board.open_search();
let screen = render(&board, SCREEN.width, SCREEN.height);
let row = screen.last().expect("no rows rendered");
assert!(row.contains("enter jump"), "{row}");
assert!(row.contains("esc cancel"), "{row}");
assert!(!row.contains("q quit"), "the key list survived the prompt:\n{row}");
assert!(
screen.join("\n").contains("Alpha first"),
"the board went away behind the prompt"
);
type_query(&mut board, "gam");
let row = footer(&board, SCREEN.width, SCREEN.height);
assert!(row.contains("/gam"), "the query is not drawn: {row}");
}
/// The whole point of an input mode. Every one of these keys does something on the
/// board, and none of it may happen while a query is being typed.
#[test]
fn the_prompt_swallows_the_keys_that_are_bound_to_actions() {
let dir = searchable();
let mut board = one_board(&dir);
let before = selected_title(&board);
board.open_search();
for key in [
letter('d'),
letter('q'),
letter('j'),
letter('h'),
typed(KeyCode::Up),
typed(KeyCode::Down),
typed(KeyCode::Left),
typed(KeyCode::Right),
typed(KeyCode::Tab),
typed(KeyCode::PageDown),
] {
assert!(board.search_key(key, SCREEN), "{key:?} was not taken");
}
assert!(!board.show_done, "typing 'd' toggled the done column");
assert!(!board.should_quit, "typing 'q' quit the board");
assert_eq!(selected_title(&board), before, "an arrow moved the selection");
// The letters landed in the query; the keys that are not characters did not.
assert_eq!(board.search.as_ref().map(|s| s.query.as_str()), Some("dqjh"));
}
/// `ctrl-c` is the exception, since a terminal application always honours it. Every
/// other control combination is swallowed and does nothing: it must not type its
/// letter, and it must not reach the action arm that matches on the code alone.
#[test]
fn the_prompt_declines_ctrl_c_and_eats_every_other_control_key() {
let dir = searchable();
let mut board = one_board(&dir);
board.open_search();
let ctrl = |c: char| KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL);
assert!(
!board.search_key(ctrl('c'), SCREEN),
"the prompt ate ctrl-c and left no way off the board"
);
assert!(board.search_key(ctrl('d'), SCREEN), "ctrl-d fell through to the 'd' arm");
assert_eq!(board.search.as_ref().map(|s| s.query.as_str()), Some(""));
}
/// Esc is consumed by the search, so it never reaches the arm that closes an overlay
/// or quits, and it leaves the selection alone.
#[test]
fn esc_leaves_the_search_without_touching_the_selection_or_the_overlay() {
let dir = searchable();
let mut board = one_board(&dir);
board.toggle_detail();
let before = selected_title(&board);
board.open_search();
type_query(&mut board, "gamma");
assert!(board.search_key(typed(KeyCode::Esc), SCREEN), "esc was not taken");
assert!(board.search.is_none(), "the prompt stayed open");
assert!(board.detail.is_some(), "esc reached the overlay arm");
assert!(!board.should_quit, "esc reached the quit arm");
assert_eq!(selected_title(&board), before, "the selection moved on a cancel");
// And the next esc is the overlay's again.
assert!(!board.search_key(typed(KeyCode::Esc), SCREEN));
}
/// The jump itself: enter takes the selection to the match and puts the prompt away.
#[test]
fn enter_selects_the_first_match_and_closes_the_prompt() {
let dir = searchable();
let mut board = one_board(&dir);
board.open_search();
type_query(&mut board, "beta");
assert!(board.search_key(typed(KeyCode::Enter), SCREEN), "enter was not taken");
assert!(board.search.is_none(), "the prompt stayed open on a hit");
assert_eq!(selected_title(&board).as_deref(), Some("Beta second"));
}
/// Reading order, left to right then top to bottom, which is how the board is laid
/// out and how it is read. Not the rows on screen: the second match here is in a
/// column the selection is not in.
#[test]
fn a_match_in_another_column_moves_the_column_and_scrolls_it_into_view() {
let dir = board_dir();
// Enough cards above the match that its column has to scroll to show it.
for n in 0..12 {
write_ticket(
&dir,
"committed",
&format!("1111111{n:x}-0000-4000-8000-000000000000"),
&format!("Filler {n:02}"),
"",
);
}
write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Alpha first", "");
write_ticket(&dir, "committed", "33333333-0000-4000-8000-000000000000", "Zulu last", "");
let mut board = one_board(&dir);
board.open_search();
type_query(&mut board, "zulu");
board.search_key(typed(KeyCode::Enter), SCREEN);
assert_eq!(selected_title(&board).as_deref(), Some("Zulu last"));
assert_eq!(board.current().column, 1, "the column did not move with the card");
assert!(
board.current().offsets[1] > 0,
"the match's column was not scrolled to show it: {:?}",
board.current().offsets
);
// Drawn, not merely selected, which is what follow_selection is for.
let screen = render(&board, SCREEN.width, SCREEN.height).join("\n");
assert!(screen.contains("Zulu last"), "the match is off screen:\n{screen}");
}
/// A hidden column is not on the board, so a match in it would put the highlight
/// nowhere. Revealing done brings it back into range.
#[test]
fn a_hidden_done_column_is_never_searched() {
let dir = searchable();
let mut board = one_board(&dir);
let before = selected_title(&board);
board.open_search();
type_query(&mut board, "delta");
board.search_key(typed(KeyCode::Enter), SCREEN);
assert_eq!(selected_title(&board), before, "a hidden ticket was selected");
assert!(
board.search.as_ref().is_some_and(|search| search.missed),
"a match in a hidden column was reported as a hit"
);
board.search_key(typed(KeyCode::Esc), SCREEN);
board.toggle_done(SCREEN);
board.open_search();
type_query(&mut board, "delta");
board.search_key(typed(KeyCode::Enter), SCREEN);
assert_eq!(selected_title(&board).as_deref(), Some("Delta finished"));
}
/// The id and the title, both case insensitive, and nothing else on the ticket.
#[test]
fn a_search_reads_the_id_and_the_title_and_neither_case_matters() {
let dir = searchable();
let board = one_board(&dir);
let columns = board.visible();
let title_of = |hit: Option<(usize, usize)>| {
hit.map(|(column, card)| columns[column].cards[card].ticket.title.clone())
};
assert_eq!(title_of(first_match(columns, "GAMMA")).as_deref(), Some("Gamma third"));
assert_eq!(title_of(first_match(columns, "gamma")).as_deref(), Some("Gamma third"));
// The seven characters the card prints, in either case.
assert_eq!(title_of(first_match(columns, "3333333")).as_deref(), Some("Gamma third"));
// On the ticket, but not in the id or the title.
assert_eq!(first_match(columns, "A description."), None);
assert_eq!(first_match(columns, "alice"), None);
}
/// Reading order is column by column, then down inside a column, so a query matching
/// several cards lands on the leftmost and highest of them.
#[test]
fn the_first_match_is_the_first_in_reading_order() {
let dir = searchable();
let board = one_board(&dir);
// Every ticket here ends in a letter, so this matches all four.
assert_eq!(first_match(board.visible(), "a"), Some((0, 0)));
// Only the second column's, so the column index moves and the card index does not.
assert_eq!(first_match(board.visible(), "gamma"), Some((1, 0)));
}
/// Doing nothing visible is what makes a reader retype a query that was already
/// right, so a miss is said, the prompt stays open to be corrected, and the selection
/// does not move.
#[test]
fn a_query_matching_nothing_says_so_and_leaves_the_selection_alone() {
let dir = searchable();
let mut board = one_board(&dir);
let before = selected_title(&board);
board.open_search();
type_query(&mut board, "nothing here");
board.search_key(typed(KeyCode::Enter), SCREEN);
assert_eq!(selected_title(&board), before, "the selection moved on a miss");
assert!(board.search.is_some(), "the prompt closed on a miss");
let row = footer(&board, SCREEN.width, SCREEN.height);
assert!(row.contains("no match"), "the miss was silent: {row}");
// The message is about the query that missed, so the next edit takes it away.
board.search_key(typed(KeyCode::Backspace), SCREEN);
let row = footer(&board, SCREEN.width, SCREEN.height);
assert!(!row.contains("no match"), "the miss outlived its query: {row}");
}
/// Backspace edits, and enter on an empty query is a no-op rather than a match on
/// everything: nobody pressing enter on a prompt they have not typed into means
/// "select the first card on the board".
#[test]
fn backspace_edits_the_query_and_an_empty_one_matches_nothing() {
let dir = searchable();
let mut board = one_board(&dir);
let before = selected_title(&board);
board.open_search();
type_query(&mut board, "gamma");
for _ in 0..3 {
board.search_key(typed(KeyCode::Backspace), SCREEN);
}
assert_eq!(board.search.as_ref().map(|s| s.query.as_str()), Some("ga"));
// Past the start is empty, not a panic.
for _ in 0..5 {
board.search_key(typed(KeyCode::Backspace), SCREEN);
}
assert_eq!(board.search.as_ref().map(|s| s.query.as_str()), Some(""));
board.search_key(typed(KeyCode::Enter), SCREEN);
assert_eq!(selected_title(&board), before, "an empty query matched a card");
assert_eq!(first_match(board.visible(), ""), None);
assert_eq!(first_match(board.visible(), " "), None);
}
/// An overlay follows the jump the way it follows the arrow keys, which is what
/// `select_at` sharing `refresh_detail` with `select_card` buys.
#[test]
fn an_open_overlay_follows_the_jump() {
let dir = searchable();
let mut board = one_board(&dir);
board.toggle_detail();
assert!(
board.detail.as_ref().unwrap().text.contains("11111111"),
"{:?}",
board.detail
);
board.open_search();
type_query(&mut board, "gamma");
board.search_key(typed(KeyCode::Enter), SCREEN);
let detail = board.detail.as_ref().expect("the overlay closed on a jump");
assert_eq!(detail.title, "Gamma third");
assert!(detail.text.contains("33333333"), "{detail:?}");
}
/// With no prompt open the keyboard belongs to the action arms, so `search_key` has
/// to take nothing at all. Otherwise the pre-branch would swallow the whole board.
#[test]
fn nothing_is_taken_while_no_prompt_is_open() {
let dir = searchable();
let mut board = one_board(&dir);
for key in [letter('d'), letter('q'), letter('/'), typed(KeyCode::Esc)] {
assert!(!board.search_key(key, SCREEN), "{key:?} was taken with no prompt open");
}
assert!(board.search.is_none());
}
/// Both footers name the key, since the jump works with a ticket open as well: it
/// moves the selection, and the overlay follows.
#[test]
fn both_footers_name_the_search_key() {
let dir = searchable();
let mut board = one_board(&dir);
assert!(footer(&board, 120, 20).contains("/ search"));
board.toggle_detail();
assert!(footer(&board, 120, 20).contains("/ search"));
}
/// The real terminal cursor sits after the query, rather than a glyph standing in for
/// one. ratatui shows the cursor only for a frame that asked for it, so this is also
/// what says "you are typing" while the query is still empty.
#[test]
fn the_cursor_sits_after_the_query_on_the_prompt_row() {
let dir = searchable();
let mut board = one_board(&dir);
board.open_search();
type_query(&mut board, "gam");
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();
// The leading space, the `/`, and the three characters typed.
assert_eq!(at.x, 5, "the cursor is not after the query");
assert_eq!(at.y, SCREEN.height - 1, "the cursor left the prompt row");
}
/// `/` is the way in, and only from the action arms: typed into an open prompt it is
/// an ordinary character, which is what makes searching for a path possible.
#[test]
fn the_dispatch_opens_the_search_and_gives_the_prompt_the_keyboard_first() {
let source = include_str!("main.rs")
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
assert!(
source.contains("if board.search_key(key, screen) { continue; }"),
"the prompt has to be offered every key before the action arms, or typing \
'd' into a query toggles the done column"
);
assert!(
source.contains("KeyCode::Char('/') => board.open_search(),"),
"`/` has to open the prompt from the action arms"
);
}
// ------------------------------------------------------------------ the copy key --
/// A sink that records what it was handed, standing in for the clipboard.
fn recorder(taken: &mut Option<String>) -> impl FnOnce(&str) -> Result<()> + '_ {
move |text: &str| {
*taken = Some(text.to_string());
Ok(())
}
}
/// What the card prints and what every command takes: the seven characters, so the
/// point of the key is that they are not retyped.
#[test]
fn the_copy_key_puts_the_selected_short_id_on_the_clipboard() {
let dir = searchable();
let mut board = one_board(&dir);
assert_eq!(board.copy_text().as_deref(), Some("1111111"));
let mut taken = None;
board.copy_selected_id(recorder(&mut taken));
assert_eq!(taken.as_deref(), Some("1111111"));
// Said in words, because a copy leaves nothing on the screen to look at.
let row = footer(&board, 120, 20);
assert!(row.contains("copied 1111111"), "the copy was silent: {row}");
// The selection follows the copy: it is the card that was copied from.
let mut taken = None;
board.select_card(1, SCREEN);
board.copy_selected_id(recorder(&mut taken));
assert_eq!(taken.as_deref(), Some("2222222"));
}
/// The reader who has a ticket open is exactly the one who has decided to act on it,
/// so the key has to work there too, and the overlay stays where it was.
#[test]
fn the_copy_key_works_with_the_detail_overlay_open() {
let dir = searchable();
let mut board = one_board(&dir);
board.toggle_detail();
let mut taken = None;
board.copy_selected_id(recorder(&mut taken));
assert_eq!(taken.as_deref(), Some("1111111"));
assert!(board.detail.is_some(), "the copy closed the ticket it copied from");
}
/// Nothing selected is nothing to copy, and above all not an empty string: that would
/// take away whatever the reader had on the clipboard and give nothing back.
#[test]
fn an_empty_column_copies_nothing_at_all() {
let dir = searchable();
let mut board = one_board(&dir);
// reviewing, which `searchable` leaves empty.
board.select_column(2, SCREEN);
assert!(board.selected().is_none(), "the column was not empty");
assert_eq!(board.copy_text(), None);
let mut taken = None;
board.copy_selected_id(recorder(&mut taken));
assert_eq!(taken, None, "an empty column reached the clipboard");
// Said rather than ignored, and in red: the reader pressed a key and has nothing
// to paste, which is the same answer a failed write gives.
let notice = board.notice.as_ref().expect("nothing was said");
assert_eq!(notice.text, "nothing to copy");
assert!(notice.failed, "a copy that did not happen read as one that did");
let row = footer(&board, 120, 20);
assert!(row.contains("nothing to copy"), "{row}");
}
/// A copy that did not happen must not read like one that did, or the reader pastes
/// whatever was on the clipboard before and acts on the wrong ticket.
#[test]
fn a_clipboard_that_refuses_the_write_says_so() {
let dir = searchable();
let mut board = one_board(&dir);
board.copy_selected_id(|_| Err(anyhow::anyhow!("could not write to the terminal")));
let notice = board.notice.as_ref().expect("the failure was swallowed");
assert!(notice.failed, "a failed copy was reported as a success");
let row = footer(&board, 120, 20);
assert!(row.contains("copy failed"), "{row}");
// The reason travels with it: a bare "failed" leaves nothing to act on.
assert!(row.contains("could not write to the terminal"), "{row}");
assert!(!row.contains("copied 1111111"), "both answers were drawn: {row}");
}
/// The message belongs to the keypress that made it. It survives the tick, since the
/// board redraws four times a second and a notice cleared there would never be read,
/// and it goes the moment the reader does anything else.
#[test]
fn the_notice_outlives_the_tick_and_not_the_next_keypress() {
let dir = searchable();
let mut board = one_board(&dir);
let mut taken = None;
board.copy_selected_id(recorder(&mut taken));
board.tick().unwrap();
assert!(board.notice.is_some(), "the tick took the message away");
assert!(footer(&board, 120, 20).contains("copied"), "the message was not drawn");
board.clear_notice();
assert!(board.notice.is_none(), "the message outlived its keypress");
// And the keys are back, rather than the row staying spent on a read message.
let row = footer(&board, 120, 20);
assert!(row.contains("q quit"), "the key list did not come back: {row}");
}
/// Both footers name it, since the key works with a ticket open as well.
#[test]
fn both_footers_name_the_copy_key() {
let dir = searchable();
let mut board = one_board(&dir);
assert!(footer(&board, 120, 20).contains("y copy id"));
board.toggle_detail();
assert!(footer(&board, 120, 20).contains("y copy id"));
}
/// The rules are `copy_selected_id` and `clear_notice`, which the tests above reach.
/// What is left is the dispatch, which none of them can: that `y` is bound at all,
/// that it is handed the real clipboard, and that the clearing runs ahead of every
/// key rather than only ahead of the arms.
///
/// Scanned over whitespace-collapsed source, the way the other two dispatch tests
/// scan, so rustfmt cannot fail it.
#[test]
fn the_dispatch_binds_y_to_the_clipboard_and_clears_the_notice_on_every_key() {
let source = include_str!("main.rs")
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
assert!(
source.contains("KeyCode::Char('y') => board.copy_selected_id(clipboard::copy),"),
"`y` has to reach `Board::copy_selected_id` with the real clipboard: the \
argument is what the suite replaces, so the dispatch is the only place \
the OSC 52 write is named"
);
let cleared = source.find("board.clear_notice();").expect(
"a notice that nothing clears sits in the footer for the rest of the session",
);
let prompt = source.find("if board.search_key(key, screen)").unwrap();
assert!(
cleared < prompt,
"the notice has to be cleared ahead of the prompt as well as the arms: a \
key typed into a query is still a key"
);
}
// ------------------------------------------------------- several boards at once --
/// A project tree: a directory holding a `.worklane`, which is what a path argument
+174
View File
@@ -296,3 +296,177 @@ fn ls_shows_a_mark_for_the_level() {
// The raw number is not what the listing shows
assert!(!stdout.contains(" 1 "), "the digit leaked into the row");
}
/// A ticket whose Tags field is whatever the test needs it to be, written verbatim so a
/// missing field, an unset one and a real list are all reachable.
fn create_ticket_with_tags(
worklane_dir: &std::path::Path,
status: &str,
title: &str,
tags: &str,
priority: &str,
) {
let slug: String = title.to_lowercase().replace(' ', "-");
let body = format!(
"# {title}\n\n## Metadata\n\n - **ID**: 00000000-0000-0000-0000-000000000001\n - **Priority**: {priority}\n{tags} - **Due**: _Not set_\n- **Owner**: alice\n- **Status**: {status}\n"
);
fs::write(
worklane_dir
.join(status)
.join(format!("00000000-0000-0000-0000-000000000001_{slug}.md")),
body,
)
.unwrap();
}
/// The Tags line as a ticket carries it, for the common case of a real list.
fn tags(list: &str) -> String {
format!("- **Tags**: {list}\n")
}
#[test]
fn ls_filters_by_tag_and_composes_with_status_and_priority() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket_with_tags(&worklane, "backlog", "Tagged bug", &tags("bug,cli"), "1");
create_ticket_with_tags(&worklane, "backlog", "Tagged feature", &tags("feature"), "1");
create_ticket_with_tags(&worklane, "backlog", "Lower bug", &tags("bug"), "3");
create_ticket_with_tags(&worklane, "committed", "Started bug", &tags("bug"), "1");
// Alone, through the grouped listing: every status, only the tagged tickets.
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path()).args(["ls", "--tag", "bug"]);
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Tagged bug"), "{stdout}");
assert!(stdout.contains("Lower bug"), "{stdout}");
assert!(stdout.contains("Started bug"), "a tagged ticket in another status was dropped");
assert!(!stdout.contains("Tagged feature"), "an untagged ticket came through");
// The counts are filtered too, since they are the same collect.
assert!(stdout.contains("[BACKLOG] 2 tickets"), "{stdout}");
assert!(stdout.contains("[COMMITTED] 1 ticket"), "{stdout}");
// With the status positional.
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "backlog", "--tag", "bug"]);
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Tagged bug"));
assert!(stdout.contains("Lower bug"));
assert!(!stdout.contains("Started bug"), "the status was ignored");
// With --priority, and with both: none asked for is everything kept, so the three
// compose without a rule per pair.
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "--tag", "bug", "--priority", "1"]);
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Tagged bug"));
assert!(stdout.contains("Started bug"));
assert!(!stdout.contains("Lower bug"), "the priority was ignored");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "backlog", "--tag", "bug", "--priority", "1"]);
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Tagged bug"));
assert!(!stdout.contains("Lower bug"), "the priority was ignored");
assert!(!stdout.contains("Started bug"), "the status was ignored");
assert!(!stdout.contains("Tagged feature"), "the tag was ignored");
}
/// The field is a list of whole values, not a string to search: a ticket tagged `bugfix`
/// is not a ticket tagged `bug`, and neither is one tagged `Bug`. Case sensitive is the
/// opinion the field already takes, since `tag_color` draws those two differently.
#[test]
fn ls_matches_a_whole_tag_value_and_not_a_substring_or_another_case() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket_with_tags(&worklane, "backlog", "Real bug", &tags("bug"), "2");
create_ticket_with_tags(&worklane, "backlog", "Only bugfix", &tags("bugfix"), "2");
create_ticket_with_tags(&worklane, "backlog", "Capital Bug", &tags("Bug"), "2");
// A value that only appears with its neighbours around it, so a match on the raw
// field would find it and a match on the split values cannot.
create_ticket_with_tags(&worklane, "backlog", "Spaced list", &tags("cli, filter"), "2");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "backlog", "--tag", "bug"]);
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Real bug"), "{stdout}");
assert!(!stdout.contains("Only bugfix"), "bug matched bugfix");
assert!(!stdout.contains("Capital Bug"), "bug matched Bug");
// Trimmed on the way in, so the space after the comma is not part of the tag.
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "backlog", "--tag", "filter"]);
assert!(get_stdout(&mut cmd).contains("Spaced list"));
// And the field as written is not itself a tag.
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "backlog", "--tag", "cli, filter"]);
let stdout = get_stdout(&mut cmd);
assert!(!stdout.contains("Spaced list"), "the whole field matched as one tag");
}
/// No tags is no match, however the ticket spells it: the field absent, unset, or empty.
#[test]
fn ls_never_matches_a_ticket_carrying_no_tags() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket_with_tags(&worklane, "backlog", "Has one", &tags("bug"), "2");
create_ticket_with_tags(&worklane, "backlog", "Field unset", &tags("_None_"), "2");
create_ticket_with_tags(&worklane, "backlog", "Field empty", "- **Tags**:\n", "2");
create_ticket_with_tags(&worklane, "backlog", "Field missing", "", "2");
create_ticket_with_tags(&worklane, "backlog", "Only commas", &tags(", ,"), "2");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "backlog", "--tag", "bug"]);
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Has one"), "{stdout}");
for absent in ["Field unset", "Field empty", "Field missing", "Only commas"] {
assert!(!stdout.contains(absent), "{absent} matched a tag it does not carry");
}
// Nor does an empty tag reach the filter: the value parser refuses it, so nothing is
// listed rather than everything.
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "backlog", "--tag", ""]);
cmd.assert().failure().code(2);
}
/// A tag nothing carries lists nothing and still succeeds. The message is the one `ls`
/// already gives for a filter that empties a status, rather than a second one invented
/// here for tags alone.
#[test]
fn ls_with_a_tag_nothing_carries_lists_nothing() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket_with_tags(&worklane, "backlog", "Tagged bug", &tags("bug"), "2");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "backlog", "--tag", "frontend"]);
cmd.assert().success();
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
.args(["ls", "backlog", "--tag", "frontend"]);
let stdout = get_stdout(&mut cmd);
assert!(!stdout.contains("Tagged bug"), "{stdout}");
assert!(stdout.contains("No tickets in 'backlog' status."), "{stdout}");
// Through the grouped listing the counts go to zero and no section is drawn.
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path()).args(["ls", "--tag", "frontend"]);
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("[BACKLOG] 0 tickets"), "{stdout}");
assert!(!stdout.contains("Tagged bug"), "{stdout}");
}