diff --git a/AGENTS.md b/AGENTS.md index 15aef53..36f6945 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,6 +111,9 @@ and this file is for what someone changing worklane's own code needs. - **What clap does and does not emit.** It emits the possible values of an *option*, which is why `mv --status ` needs nothing here, and nothing for a *positional*, which is why the `ls` status and the `completions` shell are listed in the fish half. Both lists are read off the enums with `possible_values`, never written out, so a fifth status appears in the script on its own - **Position is counted, not inferred.** The four `__worklane_*` predicates all read `$tokens[2]` and the token count rather than using `__fish_seen_subcommand_from`, because `campaign ls` and `campaign show` are also an `ls` and a `show` that fish has seen, and because matching against the ticket list would run worklane again inside the condition. `first_arg_of` and `second_arg_of` count a top-level command's arguments, `nested_arg_of` matches a parent and a child so `campaign show ` can be told from `chown alice `, which sit at the same token count, and `command_is` asks only which command this is, at any position in it - **Every rule carrying `-l` needs a `__worklane_command_is`, and `every_rule_naming_an_option_is_scoped_to_a_command` is what enforces it.** A bare `complete -c worklane -l tag` does not just complete that option's values, it tells fish the whole tool accepts `--tag`: `worklane init --` offered six options that only `relate` and `ls` have. Fixed in 55ee6e3. `__fish_seen_subcommand_from ls` is not the scope to use, for the nesting reason above +- **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 - **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 - **`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 diff --git a/Cargo.lock b/Cargo.lock index e028472..9226213 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1503,7 +1503,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.32.18" +version = "0.32.19" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index b62811b..2a74438 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.32.18" +version = "0.32.19" edition = "2024" [dependencies] diff --git a/src/completions.rs b/src/completions.rs index 0497a68..69bda5d 100644 --- a/src/completions.rs +++ b/src/completions.rs @@ -512,8 +512,30 @@ mod tests { fn every_listed_command_is_a_real_subcommand() { let cli = command(); let known: Vec<&str> = cli.get_subcommands().map(|c| c.get_name()).collect(); - for name in TICKET_COMMANDS.iter().chain(TICKET_SECOND_COMMANDS.iter()) { - assert!(known.contains(name), "no such subcommand: {name}"); + + // Every list that names a top-level command, not only the ticket ones. The others + // were reachable only through the rule counts below, which fail with `expected 3, + // got 4` and name nothing: a stale entry is a `complete` line whose condition never + // matches, so fish offers nothing and says nothing about why. + let top = TICKET_COMMANDS + .iter() + .chain(TICKET_SECOND_COMMANDS.iter()) + .chain(CAMPAIGN_COMMANDS.iter()) + .copied() + .chain(TAG_FLAGS.iter().map(|(command, _)| *command)); + + for name in top { + assert!(known.contains(&name), "no such subcommand: {name}"); + } + + for (parent, child) in CAMPAIGN_NESTED_COMMANDS.iter().chain(TAG_NESTED_COMMANDS.iter()) { + let sub = cli + .find_subcommand(parent) + .unwrap_or_else(|| panic!("no such subcommand: {parent}")); + assert!( + sub.find_subcommand(child).is_some(), + "`worklane {parent}` has no `{child}` subcommand" + ); } } @@ -627,6 +649,12 @@ mod tests { .filter(|line| line.contains("(worklane tags")) .collect(); + // **Hardcoded on purpose, and not derivable from the lists above.** This number is + // what catches an entry naming a command or a flag that does not exist: the walkers + // go clap → list and never see an extra, so a bogus `("bogus", "nope")` in + // `TAG_FLAGS` produces a fourth rule and only this count notices. Writing it as + // `TAG_FLAGS.len() + TAG_NESTED_COMMANDS.len()` would grow with the bogus entry and + // pass, which is the improvement to not make. assert_eq!( reading.len(), 3, diff --git a/tests/cmd_completions.rs b/tests/cmd_completions.rs index fb28e08..aec7b3a 100644 --- a/tests/cmd_completions.rs +++ b/tests/cmd_completions.rs @@ -68,6 +68,232 @@ fn fish_is_offered_every_status() { assert!(out.contains("-a 'backlog committed reviewing done discarded' -d status")); } +/// A board holding one ticket and one tag, for the rules whose values come off a board. +/// +/// Returned with the ticket's id and the tag, since the assertions are that those exact +/// strings are what fish offers. +fn board() -> (assert_fs::TempDir, String, String) { + let temp = assert_fs::TempDir::new().unwrap(); + let mut init = Command::cargo_bin(BIN_NAME).unwrap(); + init.current_dir(temp.path()).arg("init").assert().success(); + + let mut add = Command::cargo_bin(BIN_NAME).unwrap(); + add.current_dir(temp.path()) + .args(["add", "--title", "A ticket to complete", "--tags", "atag"]) + .assert() + .success(); + + let mut ls = Command::cargo_bin(BIN_NAME).unwrap(); + let listed = ls + .current_dir(temp.path()) + .args(["ls", "--ids"]) + .assert() + .success(); + let listed = String::from_utf8(listed.get_output().stdout.clone()).unwrap(); + let id = listed.split('\t').next().unwrap().trim().to_string(); + + (temp, id, "atag".to_string()) +} + +/// What fish would actually offer for a half-typed line, or `None` when fish is absent. +/// +/// `complete -C` is fish's own answer to "what are the candidates here", so this asks the +/// question a person at a prompt asks rather than searching the script for the rule that +/// ought to produce the answer. Each candidate is a name and, after a tab, its description. +/// +/// **The shell is pointed at the binary under test and stood in a real board**, which is +/// what makes the dynamic half testable at all: its rules are command substitutions calling +/// `worklane ls --ids` and `worklane tags`, so with no board and no binary they return +/// nothing and every assertion about them would pass on an empty answer. The directory of +/// `CARGO_BIN_EXE_worklane` goes on the front of PATH so the substitution runs this build +/// rather than whatever is installed. +/// +/// **`fish_complete_path` is emptied first, and without that line this test cannot fail.** +/// `complete -C` autoloads completions for the command it is asked about, so a developer +/// who has ever run `worklane completions fish > ~/.config/fish/completions/worklane.fish` +/// gets that file merged into the answer. It was written by some earlier version of this +/// binary and answers for whatever the rules used to be: the first draft of this test +/// passed against a deliberately broken scope because the installed copy still had the +/// working one. Emptying the path is what makes the sourced script the only source. +fn candidates(board: &assert_fs::TempDir, line: &str) -> Option> { + // Beside the board rather than in it: a rule that fires nothing falls back to listing + // the directory, and a script sitting in there would appear among the candidates and + // read like an answer. + let holder = assert_fs::TempDir::new().unwrap(); + let path = holder.path().join("worklane.fish"); + std::fs::write(&path, script("fish")).unwrap(); + + let bin_dir = std::path::Path::new(BIN_NAME).parent().unwrap(); + let inherited = std::env::var("PATH").unwrap_or_default(); + + let asked = std::process::Command::new("fish") + .current_dir(board.path()) + .env("PATH", format!("{}:{inherited}", bin_dir.display())) + .arg("-c") + .arg(format!( + "set fish_complete_path; source {}; complete -C '{line}'", + path.display() + )) + .output(); + + match asked { + Ok(out) => Some( + String::from_utf8_lossy(&out.stdout) + .lines() + .map(str::to_string) + .collect(), + ), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => None, + Err(err) => panic!("could not run fish: {err}"), + } +} + +/// The name half of a candidate, dropping the description fish takes after the tab. +fn names(candidates: &[String]) -> Vec<&str> { + candidates + .iter() + .map(|line| line.split('\t').next().unwrap_or(line)) + .collect() +} + +/// **Ask fish what it offers, instead of asserting that the rule that should make it +/// offer that is in the file.** +/// +/// Every other test here reads the script as text, which cannot tell a rule that fires +/// from one whose condition stopped matching. That is how a completion actually breaks: +/// the clap definition moves, a list or a `__worklane_command_is` scope no longer names +/// anything, and the rule sits in the file offering nothing. Loading it into a real fish +/// and asking for the candidates is the only check that can see the difference. +/// +/// **Asserting the values, not only the names, is the point.** clap emits every option's +/// name on its own, so `--tags` and `--blocked-by` are offered whether or not the dynamic +/// half loaded: an assertion that they appear passes with every hand-written rule deleted. +/// What those rules add is the candidates *after* the flag, and that is what is pinned +/// here, against the board `board()` puts under the shell. +/// +/// Descriptions are read off deliberately and not asserted: every option carrying a +/// hand-written rule currently loses the help text clap gave it, which is its own ticket +/// rather than something to pin as correct here. +/// +/// **Skipped when fish is not on PATH, and it says so.** There is no CI here and fish is +/// the shell this tool is written for, so failing a machine that never had it would be a +/// guard nobody could satisfy. A missing fish means the check did not run, not that it +/// passed. +#[test] +fn fish_offers_the_commands_the_statuses_and_the_values() { + let (temp, id, tag) = board(); + + let Some(commands) = candidates(&temp, "worklane ") else { + eprintln!("skipped: fish is not on PATH, so nothing asked it for candidates"); + return; + }; + for command in [ + "add", "ls", "show", "mv", "set", "append", "relate", "campaign", + ] { + assert!( + names(&commands).contains(&command), + "`worklane ` never offers {command}" + ); + } + + // The `ls` status positional, which clap emits nothing for, so this answer comes from + // the dynamic half alone and an empty one means that half stopped loading. + let statuses = candidates(&temp, "worklane ls ").unwrap(); + for status in ["backlog", "committed", "reviewing", "done", "discarded"] { + assert!( + names(&statuses).contains(&status), + "`worklane ls ` never offers {status}" + ); + } + + let shells = candidates(&temp, "worklane completions ").unwrap(); + for shell in ["fish", "bash", "zsh"] { + assert!( + names(&shells).contains(&shell), + "`worklane completions ` never offers {shell}" + ); + } + + // Every rule whose values come off the board, one per list it is generated from. + let ticket_value = [ + ("worklane show ", "TICKET_COMMANDS"), + ("worklane chown alice ", "TICKET_SECOND_COMMANDS"), + ("worklane relate --blocked-by ", "TICKET_FLAGS"), + ("worklane chown --clear ", "the chown --clear rule"), + ]; + for (line, list) in ticket_value { + let offered = candidates(&temp, line).unwrap(); + assert!( + names(&offered).contains(&id.as_str()), + "`{line}` never offers the one ticket on the board, so {list} is not reaching it: {offered:?}" + ); + } + + let tag_value = [ + ("worklane ls --tag ", "TAG_FLAGS"), + ("worklane append --tags ", "TAG_FLAGS"), + ("worklane tags set ", "TAG_NESTED_COMMANDS"), + ]; + for (line, list) in tag_value { + let offered = candidates(&temp, line).unwrap(); + assert!( + names(&offered).contains(&tag.as_str()), + "`{line}` never offers the one tag on the board, so {list} is not reaching it: {offered:?}" + ); + } +} + +/// **The script is handed to fish, which parses it without running it.** +/// +/// The fish half is a hand-written `format!` string carrying single quotes, command +/// substitutions and backslash line continuations, and every text assertion in this file +/// is a `contains`, which a broken script satisfies exactly as well as a correct one. +/// `--no-execute` is the parse without the run. +/// +/// **What it catches is a script that does not parse**: quotes still open at the end of +/// the file, an unclosed block. That is narrower than it sounds and the limit is worth +/// writing down, because it was measured rather than assumed. An apostrophe interpolated +/// into a `-d` description partway down the file re-balances against the next quote and +/// parses, corrupting every rule in between while this test passes; the same apostrophe in +/// the *last* rule reaches the end unbalanced and is caught. So this is a floor, not an +/// oracle, and `fish_offers_the_commands_the_statuses_and_the_flags` is the one that reads +/// what the rules actually do. +/// +/// Only fish, because only fish gets a hand-written half. What the other four shells are +/// given is clap's output whole, which `no_other_shell_gets_the_fish_half` pins, so a +/// syntax error there would be clap's bug and not this repo's to catch. +/// +/// **Skipped when fish is not on PATH, and it says so.** The trade is deliberate: there is +/// no CI here and fish is the shell this tool is written for, so failing a machine that +/// never had it would be a guard nobody could satisfy. A missing fish means the check did +/// not run, not that it passed. +#[test] +fn fish_parses_the_script_it_is_given() { + let temp = assert_fs::TempDir::new().unwrap(); + let path = temp.path().join("worklane.fish"); + std::fs::write(&path, script("fish")).unwrap(); + + let parsed = std::process::Command::new("fish") + .arg("--no-execute") + .arg(&path) + .output(); + + let out = match parsed { + Ok(out) => out, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + eprintln!("skipped: fish is not on PATH, so the generated script went unparsed"); + return; + } + Err(err) => panic!("could not run fish: {err}"), + }; + + assert!( + out.status.success(), + "fish refuses the script `worklane completions fish` writes:\n{}", + String::from_utf8_lossy(&out.stderr) + ); +} + #[test] fn an_unknown_shell_is_a_usage_error() { let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();