//! Shell completions. //! //! Two halves, because neither alone is enough. //! //! `clap_complete` generates the structure (subcommands, flags, their arguments) //! straight from the clap definition, so a new flag never needs remembering here. But it //! can only offer values it knows at compile time, and the value worth completing for //! worklane is the ticket, which lives in the board the command is run above. //! //! So the fish output gets a hand-written block appended that asks worklane itself. That //! costs one `worklane ls --ids` per keypress, which measured at 2.5ms in release on a //! board of seventy-five tickets, comfortably below anything a person notices. //! //! Status values are half clap's: `Status` is a `ValueEnum`, so clap emits every one //! of them for `mv --status`, but the fish generator does not emit possible values for //! a *positional* and `ls ` gets nothing. Same for `completions `. So //! the block below lists those two, from the enums rather than by hand. use std::io; use clap::{CommandFactory, ValueEnum}; use clap_complete::Shell; use crate::install::SKILLS; use crate::util::{RelationKind, Status}; /// Subcommands whose first positional is a ticket. /// /// Kept honest by a test rather than by memory: a new ticket-taking subcommand that is /// missing here silently loses completion, which nothing else would catch. pub const TICKET_COMMANDS: [&str; 8] = [ "show", "mv", "comment", "set", "append", "relate", "check", "uncheck", ]; /// Subcommands whose *second* positional is the ticket, because they name two things. /// /// `chown alice ` and `assign "v1 release" `, which put the ticket /// second deliberately, see docs/editing-tickets.md. The first argument of each is a user or a /// campaign, and neither is completed. pub const TICKET_SECOND_COMMANDS: [&str; 2] = ["chown", "assign"]; /// Options whose value is a ticket, as the command that takes it and the flag's long name. /// /// Pairs rather than the flat list this was, for the reason [`TAG_FLAGS`] holds pairs: the /// commands spell their flags differently and one of the spellings is shared. `relate`'s /// three take a ticket, `chown --clear` takes one because there is no user to give it, and /// `set --clear` takes a field name and `relate --clear` a relation kind — so a list of /// bare flag names would offer tickets to those two as well. pub const TICKET_FLAGS: [(&str, &str); 4] = [ ("relate", "blocked-by"), ("relate", "regression-of"), ("relate", "relates-to"), ("chown", "clear"), ]; /// Subcommands whose first positional is a campaign. /// /// `assign` alone, which takes the campaign first and the ticket second. Kept honest by /// the same test the ticket lists are. pub const CAMPAIGN_COMMANDS: [&str; 1] = ["assign"]; /// Nested subcommands whose first argument is a campaign, as `parent child`. /// /// `campaign show`, `campaign set` and `campaign append`, and they are why the fish half /// needs a third position helper: their argument is the *third* token, where /// `__worklane_first_arg_of` reads the second and `__worklane_second_arg_of` counts a /// top-level command's arguments. Neither can tell `campaign show ` from /// `chown alice ` by position. pub const CAMPAIGN_NESTED_COMMANDS: [(&str, &str); 3] = [ ("campaign", "show"), ("campaign", "set"), ("campaign", "append"), ]; /// Options whose value is a campaign. pub const CAMPAIGN_FLAGS: [&str; 1] = ["campaign"]; /// Options whose value is a tag, as the command that takes it and the flag's long name. /// /// Its own list rather than a line in the block below, because the values come from a /// different command: a tag is not an object with an id, so `worklane tags` answers this /// one where `ls --ids` answers the tickets. /// /// Pairs rather than the flat list the other flag lists are, because the two spellings /// differ: `ls --tag` filters on one and `append --tags` adds them, so a single rule /// naming both options would tell fish that each command takes the other's flag. One /// rule per pair instead. /// /// `add --tags` and `set --tags` are deliberately absent. Both take the *whole* list, so /// the token being completed is `bug,tui` and fish replaces a token entire: offering one /// tag there would throw away the ones already typed. `append --tags` is the one where /// naming a single tag is the ordinary call. pub const TAG_FLAGS: [(&str, &str); 2] = [("ls", "tag"), ("append", "tags")]; /// Nested commands whose first argument is a tag the board already has. /// /// `tags set` changes what a declared tag means, so the values it takes are exactly the /// ones `worklane tags` prints. `tags add` is deliberately absent: the tag it takes is one /// the board does not have yet, so offering the ones it does would offer exactly the values /// it refuses. Which of the two a new tag positional belongs to is what /// `no_tag_taking_option_is_missing` makes somebody decide. pub const TAG_NESTED_COMMANDS: [(&str, &str); 1] = [("tags", "set")]; /// Options whose first value is a relation kind. /// /// `relate --clear` alone, and it is a list rather than a line in [`argument_at`] for the /// reason every other position is: what an argument names belongs beside the tables that /// answer the same question about the rest of them. It cannot come off clap the way a /// status does, which is why it is here at all — the flag takes a kind and then a target, /// two values of different kinds under one name, so possible values on it would refuse /// every target. pub const RELATION_KIND_FLAGS: [(&str, &str); 1] = [("relate", "clear")]; /// The long name of the flag a typed word spells, or nothing where it is not a flag. /// /// `--status` is its own name and `-s` is clap's to translate, off the command that holds /// the flag: a table of the shorts kept here would be a second list of every option the /// tool has, and it would go wrong the first time one was given a letter. /// /// **One letter, never a cluster.** `mv -fs done` is force and status and it is `status` /// that takes the word after it, so the last letter of a cluster would be the honest /// answer — but `--title`, `--description`, `--acceptance`, `--plan` and a comment body all /// take a leading hyphen on purpose, and reading `-fixes the offset` as a cluster would /// offer statuses inside a criterion. A clustered short is rare on a board where the line /// is typed a word at a time; a hyphen-leading prose value is a documented feature. fn long_name(arg: &str, holder: Option<&clap::Command>) -> Option { if let Some(long) = arg.strip_prefix("--") { return (!long.is_empty()).then(|| long.to_string()); } let mut letters = arg.strip_prefix('-')?.chars(); let short = match (letters.next(), letters.next()) { (Some(letter), None) => letter, _ => return None, }; holder? .get_arguments() .find(|option| option.get_short() == Some(short)) .and_then(|option| option.get_long()) .map(str::to_string) } /// What an argument of a typed line names, where worklane can answer what goes there. /// /// The board's command prompt completes against this: the tables above say *what* the /// position takes and the prompt says what the board currently holds of it. A ticket and a /// campaign and a tag are all "a word off the board" to clap and three different questions /// to the reader, which is why this is an enum rather than a candidate list — the values /// live where the board is and the positions live here. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Argument { /// A ticket on the board. One candidate, the card the reader has selected. Ticket, /// A campaign, which is named by its codename and drawn by it on every card it holds. Campaign, /// A tag. `declared` is `tags set`'s: it changes what a declared tag means and refuses /// one the vocabulary file does not declare, so offering a carried-but-undeclared tag /// there would offer exactly the values the command rejects. That is 193f9be in the /// fish half, and this is the prompt not inheriting it. Tag { declared: bool }, /// Values the tool itself holds: the subcommand names at a verb position, the possible /// values of an argument clap built from a `ValueEnum`, and the relation kinds. /// /// Read off the clap definition rather than written out, so a command, a status or a /// clearable field added anywhere is typeable on the board the day it is added. Fixed(Vec), } /// What the argument at `index` of a typed line names, `index` counting from the verb at 0, /// or nothing where worklane has nothing to offer. /// /// The tables above are what answer it, reached rather than restated: a second copy of the /// positions on the board would go wrong the next time a command grew a ticket argument, and /// it would go wrong silently, since the tests that keep these honest against clap would /// not read the copy. /// /// Position is counted rather than inferred, exactly as the fish half counts it, so /// `mv --status done ` is not recognised: the ticket is `mv`'s first *positional* /// and the third argument on the line. That is the fish rules' limit too, and one answer /// for both is worth more than two that disagree about the corner. /// /// The clap definition is rebuilt on every call, at 32µs in release, and the caller is a /// board that redraws four times a second: a definition cached beside the board would be a /// second copy of what `Cli::command()` already answers, for a cost nothing can measure. /// The fish half spends 2.5ms per keypress running worklane itself for the same answers. pub fn argument_at(args: &[String], index: usize) -> Option { let cli = crate::command::Cli::command(); // The verb itself, which is every subcommand the tool has. Hidden ones are left out: // they are not in the help either, and a candidate nobody can read about is one a // reader has to go and look up. if index == 0 { return Some(Argument::Fixed(subcommand_names(&cli))); } let verb = args.first().map(String::as_str)?; let group = cli.find_subcommand(verb); // The command a flag belongs to, which is the *nested* one where a group's child // carries it: `--state` is `campaign ls`'s and clap holds it on `ls`, not on // `campaign`. Falls back to the group itself, which is where every other flag is, and // to nothing for a line whose second word names no subcommand — `mv 1b78a24 --status` // reaches `mv`'s own arguments as it always did. let holder = args .get(1) .and_then(|child| group.and_then(|group| group.find_subcommand(child))) .or(group); // A flag's value is the argument after it, which is where the flag sits whether the // value is half typed or has not been started. Spelled long or short: `-s` is the same // flag as `--status` and the row has to answer both, which is what `long_name` is for. if let Some(flag) = args.get(index - 1).and_then(|arg| long_name(arg, holder)) { let flag = flag.as_str(); if TICKET_FLAGS.contains(&(verb, flag)) { return Some(Argument::Ticket); } if CAMPAIGN_FLAGS.contains(&flag) { return Some(Argument::Campaign); } if TAG_FLAGS.contains(&(verb, flag)) { return Some(Argument::Tag { declared: false }); } if RELATION_KIND_FLAGS.contains(&(verb, flag)) { let kinds = RelationKind::ALL.iter().map(|kind| kind.flag().to_string()); return Some(Argument::Fixed(kinds.collect())); } // And everything else the flag could take, which is whatever clap knows: `--status` // and `set --clear` are both `ValueEnum`s, so their values are already written down // once, in the enum. let arg = holder? .get_arguments() .find(|arg| arg.get_long() == Some(flag))?; return fixed(arg); } // The positionals, at the index each table records. match index { 1 if TICKET_COMMANDS.contains(&verb) => return Some(Argument::Ticket), 1 if CAMPAIGN_COMMANDS.contains(&verb) => return Some(Argument::Campaign), 2 if TICKET_SECOND_COMMANDS.contains(&verb) => return Some(Argument::Ticket), _ => {} } let group = group?; // The verb of a group, `campaign show` and `tags set`, which is a subcommand name // exactly as the top-level verb is. if index == 1 && group.has_subcommands() { return Some(Argument::Fixed(subcommand_names(group))); } // And the first argument of one, which is where a campaign and a declared tag are named. if index == 2 && let Some(child) = args.get(1).map(String::as_str) { if CAMPAIGN_NESTED_COMMANDS.contains(&(verb, child)) { return Some(Argument::Campaign); } if TAG_NESTED_COMMANDS.contains(&(verb, child)) { return Some(Argument::Tag { declared: true }); } } // And whatever else the positional itself knows, which is the `ls` status and the // `completions` shell: both are `ValueEnum`s that the fish generator has to list by // hand, because it emits possible values for an option and none for a positional. fixed(group.get_positionals().nth(index - 1)?) } /// The names a command answers to, hidden ones left out. fn subcommand_names(command: &clap::Command) -> Vec { command .get_subcommands() .filter(|sub| !sub.is_hide_set()) .map(|sub| sub.get_name().to_string()) .collect() } /// The possible values of one argument, or nothing for an argument that takes free text. /// /// `get_positionals` and `get_long` both read what the derive wrote, so nothing here needs /// the command built the way `get_index` would. fn fixed(arg: &clap::Arg) -> Option { let values: Vec = arg .get_possible_values() .iter() .filter(|value| !value.is_hide_set()) .map(|value| value.get_name().to_string()) .collect(); (!values.is_empty()).then_some(Argument::Fixed(values)) } pub fn generate(shell: Shell, out: &mut dyn io::Write) -> io::Result<()> { let mut command = crate::command::Cli::command(); clap_complete::generate(shell, &mut command, "worklane", out); if shell == Shell::Fish { write!(out, "{}", fish_dynamic())?; } Ok(()) } /// The dynamic half, appended to what clap generated. /// /// Fish merges completions from every `complete` call, so these add to the generated /// rules rather than replacing them. fn fish_dynamic() -> String { let ticket_commands = TICKET_COMMANDS.join(" "); let ticket_second_commands = TICKET_SECOND_COMMANDS.join(" "); let ticket_flags = TICKET_FLAGS .iter() .map(|(command, flag)| { let option = fish_option(command, flag); format!( "complete -c worklane -n '__worklane_command_is {command}' {option} \\\n \ -x -a '(worklane ls --ids)'" ) }) .collect::>() .join("\n"); let relation_kinds = RelationKind::ALL .iter() .map(|kind| kind.flag()) .collect::>() .join(" "); let campaign_commands = CAMPAIGN_COMMANDS.join(" "); let campaign_nested = CAMPAIGN_NESTED_COMMANDS .iter() .map(|(parent, child)| format!("__worklane_nested_arg_of {parent} {child}")) .collect::>() .join("; or "); let campaign_flags = flag_list("ls", &CAMPAIGN_FLAGS); let tag_flags = TAG_FLAGS .iter() .map(|(command, flag)| { let option = fish_option(command, flag); format!( "complete -c worklane -n '__worklane_command_is {command}' {option} \\\n \ -x -a '(worklane tags | cut -f1,3)'" ) }) .collect::>() .join("\n"); let tag_nested = TAG_NESTED_COMMANDS .iter() .map(|(parent, child)| format!("__worklane_nested_arg_of {parent} {child}")) .collect::>() .join("; or "); let statuses = possible_values(Status::value_variants()); let shells = possible_values(Shell::value_variants()); let skills = SKILLS .iter() .map(|skill| skill.name) .collect::>() .join(" "); format!( r#" # --------------------------------------------------------------------------- # Dynamic values, appended by `worklane completions fish`. Fish accumulates # completions, so these add to the generated rules above. # --------------------------------------------------------------------------- # Almost every argument worklane takes names something on the board rather than # something on disk, so stop fish falling back to the directory listing. Without this, # `worklane show 1b78a24 ` offers Cargo.toml and src/. complete -c worklane -f # The exception, and the reason the line above is not the whole story: `tui` takes # project paths, as many as you like. Directories only, since each is resolved to the # first `.worklane` at or above it. complete -c worklane -n '__worklane_command_is tui' \ -a '(__fish_complete_directories)' -d project # Position is counted rather than inferred from what has been typed: matching against # the ticket list would run worklane again inside the condition, and would also keep # offering tickets after one had been chosen. # # The subcommand is the second token, so its first argument is being typed once two # tokens are there. `$tokens[2]` rather than `__fish_seen_subcommand_from`, because # `campaign ls` and `campaign show` are also an `ls` and a `show` that fish has seen, # and their arguments are not what these complete. function __worklane_first_arg_of set -l tokens (commandline -opc) test (count $tokens) -eq 2; and contains -- $tokens[2] $argv end function __worklane_second_arg_of set -l tokens (commandline -opc) test (count $tokens) -eq 3; and contains -- $tokens[2] $argv end # The first argument of a nested subcommand, `worklane campaign show `. Three tokens # with both names matched, rather than the token counting the two above do: `campaign show` # puts its argument where a top-level command puts its second, so counting alone would # offer campaigns to `chown alice ` and tickets here. function __worklane_nested_arg_of set -l tokens (commandline -opc) test (count $tokens) -eq 3; and test "$tokens[2]" = "$argv[1]"; and test "$tokens[3]" = "$argv[2]" end # Which command this is, at any position in it. `$tokens[2]` again rather than # `__fish_seen_subcommand_from`, and for the reason spelled out above: `campaign ls` is an # `ls` that fish has seen, so scoping `--tag` with fish's own helper would offer it under a # command that does not take it. # # A rule carrying `-l` needs one of these. Without it fish takes the option as one the # whole tool accepts, and `worklane init --` offered `--blocked-by`, `--tag` and four # others that only `relate` and `ls` have. function __worklane_command_is set -l tokens (commandline -opc) test (count $tokens) -ge 2; and contains -- $tokens[2] $argv end # No `-d`: `ls --ids` prints the id and the title separated by a tab, which is fish's # own form for a candidate and its description, so every ticket carries its own. complete -c worklane \ -n '__worklane_first_arg_of {ticket_commands}; or __worklane_second_arg_of {ticket_second_commands}' \ -a '(worklane ls --ids)' # The options whose value is a ticket, one rule per command so that a flag is offered # only under the command that has it. `relate` takes its three targets this way rather # than by position, and `chown --clear` names the ticket in the flag because with no user # to give there is no second positional to put it in. Its `--clear` is scoped like every # other: `set` has one that takes a field name, which clap already offers. {ticket_flags} # `relate --clear` is the one `--clear` whose first value is not a ticket, which is why # that pair is not in `TICKET_FLAGS`: it takes the kind and then the target, and offering a # board listing where the kind goes would be offering values it refuses. The kinds come # from `RelationKind` rather than being spelled again. The target gets no rule at all, # deliberately: fish completes the value after the flag, and the case this flag exists for # is a target whose ticket is gone, which no listing of the board can offer. complete -c worklane -n '__worklane_command_is relate' -l clear -x -a '{relation_kinds}' # Campaigns, from `campaign ls --ids`, in the three places one is named: `assign`'s first # argument, `campaign show`'s only one, and `ls --campaign`. complete -c worklane \ -n '__worklane_first_arg_of {campaign_commands}; or {campaign_nested}' \ -a '(worklane campaign ls --ids)' complete -c worklane -n '__worklane_command_is ls' {campaign_flags} \ -x -a '(worklane campaign ls --ids)' # Tags come from `worklane tags` rather than from a listing of objects, since a tag has no # id. Three fields now, the tag, its count and its annotation, and fish takes everything # after the *first* tab as one description, so the count is dropped here rather than landing # in the middle of the prose. `cut` and not `string replace` because the columns are what is # being picked, and `cut -f1` is how a script reads this listing anyway. # # What is left is the annotation, and a tag the board carries but has never declared has # none: it is offered with no description at all, which is the near-duplicate the file was # added to catch. The count used to be the description and said the same thing more weakly. # # One rule per command, from `TAG_FLAGS`: `ls --tag` and `append --tags` are spelled # differently, so a single rule naming both options would offer each under the other. {tag_flags} # And `tags set` names one that is already declared, so it reads the same listing. `tags # add` has no rule on purpose: it takes a tag the board does not have, so the candidates # here are the values it refuses. complete -c worklane -n '{tag_nested}' -a '(worklane tags | cut -f1,3)' # clap emits the statuses for `mv --status`, which is an option, but the fish generator # emits nothing for the possible values of a positional. So the one place a status is # positional needs them listed, and the same goes for the shell below. complete -c worklane -n '__worklane_first_arg_of ls' -a '{statuses}' -d status complete -c worklane -n '__worklane_first_arg_of completions' -a '{shells}' -d shell # Shipped with the binary, so this list comes from `install::SKILLS` and cannot fall # behind it. complete -c worklane -n '__worklane_first_arg_of install-skill' -a '{skills}' -d skill "# ) } /// Option names as fish wants them on a `complete` line, `-s o -l one -l two`, for the /// options of one command. fn flag_list(command: &str, flags: &[&str]) -> String { flags .iter() .map(|flag| fish_option(command, flag)) .collect::>() .join(" ") } /// One option as fish names it: its long name, and its letter where clap gave it one. /// /// `-s g -l tags` rather than `-l tags` alone, or `append -g ` offers nothing where /// `append --tags ` offers the board's tags — the same hole the board's own prompt had /// until `long_name`, and the reason one table answers both halves is that neither may /// answer a spelling the other does not. The letter is read off the definition and never /// written here, so an option given one tomorrow is offered under it the day it is given. fn fish_option(command: &str, flag: &str) -> String { let cli = crate::command::Cli::command(); let short = cli .find_subcommand(command) .and_then(|command| { command .get_arguments() .find(|option| option.get_long() == Some(flag)) }) .and_then(|option| option.get_short()); match short { Some(letter) => format!("-s {letter} -l {flag}"), None => format!("-l {flag}"), } } /// The names a `ValueEnum` accepts, for a fish `-a` list. /// /// Read off the enum rather than written out, so a status or a shell added to either one /// is offered without anybody remembering this file. A variant marked hidden is left out, /// which is what `to_possible_value` returning `None` means. fn possible_values(variants: &[T]) -> String { variants .iter() .filter_map(|variant| variant.to_possible_value()) .map(|value| value.get_name().to_string()) .collect::>() .join(" ") } #[cfg(test)] mod tests { use super::*; /// Built, not just derived: an index is assigned when the command is built, and the /// positionals of an unbuilt one all report `None`. fn command() -> clap::Command { let mut cli = crate::command::Cli::command(); cli.build(); cli } /// Every argument in the tool, as the path that reaches it and the argument itself. /// /// One walker for the honesty tests below, rather than each one repeating the /// traversal: they differ only in which id they are looking for. Two levels, which is /// as deep as the tool goes, and `help` is skipped because clap generates it and it /// takes no object of ours. fn every_argument() -> Vec<(Vec, clap::Arg)> { let cli = command(); let mut found = Vec::new(); for subcommand in cli.get_subcommands() { let name = subcommand.get_name().to_string(); if name == "help" { continue; } for arg in subcommand.get_arguments() { found.push((vec![name.clone()], arg.clone())); } for nested in subcommand.get_subcommands() { let child = nested.get_name().to_string(); if child == "help" { continue; } for arg in nested.get_arguments() { found.push((vec![name.clone(), child.clone()], arg.clone())); } } } found } /// Every subcommand that takes a ticket must be listed, at the position it takes it, /// or it silently loses completion. /// /// Nested subcommands are walked now that `__worklane_nested_arg_of` exists, but /// nothing under `campaign` takes a ticket, so a nested one is a panic rather than a /// list: it would need a rule of its own in the fish block, and a name in a list here /// would look like it already had one. #[test] fn no_ticket_taking_subcommand_is_missing() { for (path, arg) in every_argument() { // `show` calls it `id`; everything else calls it `ticket`. if !matches!(arg.get_id().as_str(), "ticket" | "id") { continue; } let name = path.join(" "); if arg.is_positional() { assert_eq!( path.len(), 1, "`worklane {name}` takes a nested ticket argument, \ which needs a rule in the fish block" ); let top = path[0].as_str(); match arg.get_index() { Some(1) => assert!( TICKET_COMMANDS.contains(&top), "`worklane {name}` takes a ticket first but is not in TICKET_COMMANDS" ), Some(2) => assert!( TICKET_SECOND_COMMANDS.contains(&top), "`worklane {name}` takes a ticket second but is not in \ TICKET_SECOND_COMMANDS" ), index => panic!("`worklane {name}` takes a ticket at position {index:?}"), } } } } /// The same for campaigns, which is why the lists above are three rather than one: /// a campaign is named as a first positional, as a nested subcommand's only argument, /// and as an option value, and each needs a different rule in the fish block. #[test] fn no_campaign_taking_argument_is_missing() { let mut seen = 0; for (path, arg) in every_argument() { if arg.get_id().as_str() != "campaign" { continue; } seen += 1; let name = path.join(" "); if let Some(long) = arg.get_long() { assert!( CAMPAIGN_FLAGS.contains(&long), "`worklane {name} --{long}` takes a campaign but is not in CAMPAIGN_FLAGS" ); continue; } assert_eq!( arg.get_index(), Some(1), "`worklane {name}` takes a campaign somewhere the fish block has no rule for" ); match path.as_slice() { [top] => assert!( CAMPAIGN_COMMANDS.contains(&top.as_str()), "`worklane {name}` takes a campaign first but is not in CAMPAIGN_COMMANDS" ), [parent, child] => assert!( CAMPAIGN_NESTED_COMMANDS.contains(&(parent.as_str(), child.as_str())), "`worklane {name}` takes a campaign but is not in CAMPAIGN_NESTED_COMMANDS" ), _ => panic!("`worklane {name}` is nested deeper than the fish block goes"), } } // A guard on the walker itself: if it stopped finding arguments, every assertion // above would pass by never running. assert_eq!( seen, 5, "expected assign, campaign show, campaign set, campaign append and ls --campaign" ); } /// Commands whose tag positional names a tag that does not exist yet. /// /// `tags add` declares a word the board has never carried, so completing it from /// `worklane tags` would offer exactly the values the command refuses. Recorded rather /// than skipped, so the *next* tag positional has to say which it is: `tags set` takes /// a tag that is already declared and wants a rule in the fish block, and the test /// below fails until it gets one or lands here. /// /// In the test module because nothing outside it reads the list; the rule it encodes is /// about what the fish block is missing, which is a test's question. const TAG_NEW_COMMANDS: [(&str, &str); 1] = [("tags", "add")]; /// Options taking a whole comma-separated list of tags rather than one. /// /// `add --tags` and `set --tags` write the field entire, so what is being typed at the /// cursor is `bug,tui` and fish replaces a token whole: a rule offering one tag there /// would throw away the ones already in the token. `append --tags` adds to what is /// there, so a single tag is the ordinary value and it earns a rule. Recorded rather /// than skipped, for the reason `TAG_NEW_COMMANDS` is: the next `--tags` has to say /// which of the two it is. const TAG_LIST_FLAGS: [(&str, &str); 2] = [("add", "tags"), ("set", "tags")]; /// Tags have their own list because their values come from `worklane tags` rather than /// from a listing of objects, so a second tag-taking option would need that rule and /// not the campaign one. /// /// Both spellings are walked, `tag` and `tags`: they are the same object under two /// argument names, and looking at only the singular is how `set --tags` went years /// without anybody deciding whether it wanted a rule. #[test] fn no_tag_taking_option_is_missing() { let mut seen = 0; for (path, arg) in every_argument() { if !matches!(arg.get_id().as_str(), "tag" | "tags") { continue; } seen += 1; let name = path.join(" "); let Some(long) = arg.get_long() else { let known = match path.as_slice() { [parent, child] => { let pair = (parent.as_str(), child.as_str()); TAG_NESTED_COMMANDS.contains(&pair) || TAG_NEW_COMMANDS.contains(&pair) } _ => false, }; assert!( known, "`worklane {name}` takes a tag as a positional, so it belongs in \ TAG_NESTED_COMMANDS if the tag already exists and TAG_NEW_COMMANDS if it \ does not" ); continue; }; let pair = (name.as_str(), long); assert!( TAG_FLAGS.contains(&pair) || TAG_LIST_FLAGS.contains(&pair), "`worklane {name} --{long}` takes a tag, so it belongs in TAG_FLAGS if one \ tag is the ordinary value and TAG_LIST_FLAGS if the value is the whole list" ); } assert_eq!( seen, 6, "expected ls --tag, tags add, tags set, add --tags, set --tags and append --tags" ); } /// One line, split the way the prompt splits it, and what the cursor's argument names. /// /// The splitter is the prompt's own, so a row below states a line as a reader types it /// rather than as a hand-written argument vector, and the two cannot come apart. fn at_cursor(line: &str) -> Option { let split = crate::split::split_line(line, line.len()); argument_at(&split.args, split.cursor_arg) } /// The fixed values offered at the cursor, or nothing where what goes there is not a /// fixed list. fn values(line: &str) -> Option> { match at_cursor(line) { Some(Argument::Fixed(values)) => Some(values), _ => None, } } /// Every position a ticket is taken in, as the line that reaches it. #[test] fn a_ticket_is_recognised_in_every_position_a_command_takes_one() { for line in [ // The first positional, begun and half typed. "show ", "mv 1b7", "comment ", "check ", // The second, where the first argument is a user or a campaign. "chown alice ", "assign v1 1b7", // The three of `relate`'s flags, and `chown --clear`, which names the ticket // in the flag because there is no user to give. "relate 1b78a24 --blocked-by ", "relate 1b78a24 --regression-of 417", "relate 1b78a24 --relates-to ", "chown --clear ", ] { assert_eq!( at_cursor(line), Some(Argument::Ticket), "`{line}` takes a ticket at the cursor and was not offered one" ); } } /// The three places a campaign is named, and the two a tag is, which are why the lists /// are not one list. #[test] fn a_campaign_and_a_tag_are_recognised_where_each_is_named() { for line in [ "assign ", "campaign show ", "campaign set v1", "ls --campaign ", ] { assert_eq!(at_cursor(line), Some(Argument::Campaign), "`{line}`"); } for line in ["ls --tag ", "append 1b78a24 --tags bu"] { assert_eq!(at_cursor(line), Some(Argument::Tag { declared: false }), "`{line}`"); } // `tags set` changes what a declared tag means and refuses one the file does not // declare, so only the declared ones may be offered there. That is the fish half's // 193f9be, which this deliberately does not inherit. assert_eq!(at_cursor("tags set "), Some(Argument::Tag { declared: true })); } /// The verbs, which are clap's own subcommands at the top level and inside a group. #[test] fn the_verb_position_is_offered_the_subcommands() { let top = values("").expect("the empty line names a verb"); for command in ["add", "ls", "mv", "relate", "campaign", "tags"] { assert!(top.contains(&command.to_string()), "`{command}` is not offered: {top:?}"); } // A group's own verb sits where a top-level command's first argument does, which is // why `campaign show` needs a rule of its own in the fish half as well. In the // order the definition spells them, since that is the order tab steps through. let nested = values("campaign ").expect("a group names a verb"); assert_eq!(nested, ["add", "set", "append", "ls", "show"], "{nested:?}"); // `help` is clap's own and is added when the command is built, which nothing here // does. That suits the board: what `help` prints is a page, and the prompt has a // row. assert!(!top.contains(&"help".to_string()), "{top:?}"); } /// The values clap itself holds, which is every `ValueEnum` in the tool: nothing here /// writes a status or a clearable field down a second time. #[test] fn an_enum_valued_argument_is_offered_the_enums_own_values() { let statuses = values("mv 1b78a24 --status ").expect("--status takes a status"); let listed: Vec = Status::ALL.iter().map(|s| s.as_str().to_string()).collect(); assert_eq!(statuses, listed, "the five statuses are not what `--status` offers"); // The one place a status is positional, which clap emits nothing for and the fish // half lists by hand. assert_eq!(values("ls "), Some(listed)); // And the other two enums a reader types: the fields `set --clear` empties and the // shells `completions` writes for. let fields = values("set 1b78a24 --clear ").expect("--clear takes a field"); assert!(fields.contains(&"acceptance".to_string()), "{fields:?}"); let shells = values("completions ").expect("completions takes a shell"); assert!(shells.contains(&"fish".to_string()), "{shells:?}"); } /// The fish half names an option by its letter too, wherever clap gave it one, so a /// dynamic rule answers both spellings the way the prompt does. #[test] fn a_fish_rule_names_the_option_by_its_letter_as_well() { let script = fish_dynamic(); // `append --tags` is the one flag in these tables with a letter, and it is the // whole reason the rule is rendered rather than written: `-g` offered nothing. assert!( script.contains("-s g -l tags"), "the tags rule does not name its letter:\n{script}" ); // And one without stays as it was, rather than gaining an empty `-s`. assert!(script.contains("-l campaign"), "{script}"); assert!(!script.contains("-s "), "an option with no letter got one:\n{script}"); // Read off the definition, never written here. assert_eq!(fish_option("append", "tags"), "-s g -l tags"); assert_eq!(fish_option("ls", "tag"), "-l tag"); assert_eq!(fish_option("ls", "nosuchflag"), "-l nosuchflag"); } /// A flag spelled short answers exactly what the same flag spelled long answers, on /// every command and every option that has both. /// /// Walked off the clap definition rather than listed, so an option given a letter /// tomorrow is covered the day it is given one. `-s` was the report: `mv --status ` /// offered the five statuses and `mv -s ` offered nothing, because the row read a flag /// by its two hyphens. A boolean's two spellings agree as well, both answering nothing, /// which is the same statement about a value that is not there. #[test] fn a_short_flag_answers_what_its_long_spelling_answers() { let cli = crate::command::Cli::command(); let mut seen = 0; for command in cli.get_subcommands() { let children: Vec<(String, &clap::Command)> = command .get_subcommands() .map(|child| (format!("{} {}", command.get_name(), child.get_name()), child)) .collect(); for (line, holder) in std::iter::once((command.get_name().to_string(), command)).chain(children) { for option in holder.get_arguments() { let (Some(short), Some(long)) = (option.get_short(), option.get_long()) else { continue; }; seen += 1; assert_eq!( at_cursor(&format!("{line} -{short} ")), at_cursor(&format!("{line} --{long} ")), "`-{short}` and `--{long}` answer differently on `{line}`" ); } } } assert!(seen > 20, "only {seen} options had both spellings, which is too few"); } /// The two the report named, spelled out, so the walk above cannot pass by finding /// nothing on either spelling. #[test] fn a_short_flag_reaches_the_values_and_the_board() { let listed: Vec = Status::ALL.iter().map(|s| s.as_str().to_string()).collect(); assert_eq!(values("mv -s "), Some(listed), "`-s` offers no statuses"); assert_eq!(values("mv -s bac"), values("mv --status bac"), "half typed"); // A tag, which comes off the board rather than out of the enum. assert_eq!(at_cursor("append -g "), Some(Argument::Tag { declared: false })); // And a cluster is deliberately not read, because `--title`, `--acceptance` and a // comment body all take a leading hyphen: a value spelled `-fixes the offset` must // not be read as `-s` and answered with statuses. assert_eq!(at_cursor("mv -fs "), None); assert_eq!(at_cursor("comment 1b78a24 -fs "), None); } /// The flag on a nested command is answered the same way, from the enum: nothing here /// knows what a campaign's states are, and the values reach the prompt and fish alike /// the day a fourth one is added to `CampaignState`. #[test] fn campaign_ls_state_is_offered_the_enums_own_values() { let states = values("campaign ls --state ").expect("--state takes a state"); assert_eq!(states, vec!["open", "done", "empty"], "{states:?}"); } /// `relate --clear` takes the kind and then the target, which is the one argument clap /// cannot answer for: possible values on the flag would refuse every target. #[test] fn relate_clear_is_offered_the_relation_kinds_and_no_ticket() { let kinds = values("relate 1b78a24 --clear ").expect("--clear takes a kind"); let listed: Vec = RelationKind::ALL .iter() .map(|kind| kind.flag().to_string()) .collect(); assert_eq!(kinds, listed, "{kinds:?}"); // And the second value is a target the board may no longer hold, which is what the // flag exists for, so nothing is offered there at all. assert_eq!(at_cursor("relate 1b78a24 --clear blocked-by "), None); } /// The positions that take free text, where offering anything would be offering a guess. #[test] fn nothing_is_recognised_where_the_argument_is_free_text() { for line in [ // `chown`'s first argument is a user, checked against nothing. "chown ", // `mv` has no second positional, and a comment body is prose. "mv 1b78a24 ", "comment 1b78a24 the ", // `tags add` declares a word the board does not have yet, so the tags it does // have are exactly the values it refuses. "tags add ", // And both `--tags` that take the whole list, where a single tag offered into // `bug,tui` would be one the field never asked for. "add --tags ", "set 1b78a24 --tags bug,", ] { assert_eq!(at_cursor(line), None, "`{line}` was offered a candidate where none goes"); } } /// **Every rule naming an option has to say which command it belongs to.** A bare /// `complete -c worklane -l tag` tells fish the whole tool takes `--tag`, so /// `worklane init --` offered six options that only `relate` and `ls` have. This /// is what stops the next rule being written the same way. #[test] fn every_rule_naming_an_option_is_scoped_to_a_command() { let script = fish_dynamic(); // Rules are one logical line, continued with a trailing backslash. for rule in script.replace("\\\n", " ").lines() { if !rule.starts_with("complete") || !rule.contains("-l ") { continue; } assert!( rule.contains("__worklane_command_is"), "this rule declares an option for the whole tool: {rule}" ); } } #[test] fn every_listed_command_is_a_real_subcommand() { let cli = command(); let known: Vec<&str> = cli.get_subcommands().map(|c| c.get_name()).collect(); // 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(TICKET_FLAGS.iter().map(|(command, _)| *command)) .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" ); } } /// Three commands carry a `--clear` and each one takes something different: `chown` /// takes the ticket, `relate` takes the kind and then the target, and `set` takes a /// field name clap already offers. So each rule is scoped to its own command, and a /// bare search for `-l clear` cannot tell them apart, which is what this used to do. #[test] fn each_clear_flag_is_completed_for_its_own_command() { // Continuations joined first: a rule is one logical line, and the generated ones // put the flag and its values on either side of a trailing backslash. let script = fish_dynamic().replace("\\\n", " "); let cli = command(); let rule_for = |name: &str| { let scope = format!("__worklane_command_is {name}"); script .lines() .find(|line| { line.starts_with("complete") && line.contains("-l clear") && line.contains(&scope) }) .unwrap_or_else(|| panic!("no --clear rule for {name}:\n{script}")) .to_string() }; let has_clear = |name: &str| { cli.find_subcommand(name) .unwrap_or_else(|| panic!("no such subcommand: {name}")) .get_arguments() .any(|arg| arg.get_long() == Some("clear")) }; // `chown --clear` names the ticket in the flag, so the flag completes tickets. assert!(has_clear("chown"), "`chown` has no --clear for the rule to complete"); assert!(rule_for("chown").contains("worklane ls --ids"), "{}", rule_for("chown")); // `relate --clear` takes the kind first, so it offers the kinds and not a board // listing: tickets there would be candidates the flag refuses. The target, the // second value, is deliberately left uncompleted. assert!(has_clear("relate"), "`relate` has no --clear for the rule to complete"); let relate = rule_for("relate"); for kind in RelationKind::ALL { assert!(relate.contains(kind.flag()), "{kind:?} is not offered: {relate}"); } assert!( !relate.contains("worklane ls --ids"), "tickets offered where the kind goes: {relate}" ); // `set --clear` takes a field name, which clap already offers, and `relate --clear` // takes a kind. Only `chown`'s names a ticket, so only that pair is in the table. assert!( !TICKET_FLAGS.contains(&("set", "clear")), "`set --clear` in TICKET_FLAGS would offer tickets where a field name goes" ); assert!( !TICKET_FLAGS.contains(&("relate", "clear")), "`relate --clear` in TICKET_FLAGS would offer tickets where the kind goes" ); assert!( TICKET_FLAGS.contains(&("chown", "clear")), "`chown --clear` names the ticket in the flag, so it belongs in TICKET_FLAGS" ); } /// Each flag completed as a ticket has to be an option its own command actually takes, /// or the rule completes something nothing accepts. /// /// The command is half of what is checked, which is what the pairs bought: a flat list /// could only be walked against one command, and `--clear` is spelled the same on three. #[test] fn every_ticket_flag_is_a_real_option() { let cli = command(); for (name, flag) in TICKET_FLAGS { let subcommand = cli .find_subcommand(name) .unwrap_or_else(|| panic!("no such subcommand: {name}")); assert!( subcommand .get_arguments() .any(|arg| arg.get_long() == Some(flag)), "`worklane {name}` has no --{flag}" ); } } #[test] fn the_fish_script_asks_worklane_for_its_tickets() { let script = fish_dynamic(); assert!(script.contains("worklane ls --ids")); // Both positions, in one rule. assert!(script.contains("__worklane_first_arg_of show")); assert!(script.contains("__worklane_second_arg_of chown assign")); // Nothing here takes a file, bar the one that does. assert!(script.contains("complete -c worklane -f\n")); assert!(script.contains("__fish_complete_directories")); // Generated from `install::SKILLS`, so every shipped skill is in it. assert!(script.contains("worklane-review")); } /// The two listings the campaign and tag rules read, which are separate commands /// because a campaign has an id and a tag does not. #[test] fn the_fish_script_asks_worklane_for_its_campaigns_and_tags() { let script = fish_dynamic(); assert!(script.contains("worklane campaign ls --ids"), "{script}"); assert!(script.contains("worklane tags"), "{script}"); // The nested position, which neither of the two counting helpers can reach. assert!(script.contains("__worklane_nested_arg_of campaign show"), "{script}"); assert!(script.contains("__worklane_first_arg_of assign"), "{script}"); } /// Every rule that reads the tag listing drops the count, because `worklane tags` prints /// three fields and fish takes everything after the first tab as the description. Left /// whole, a tag would be described as its count, a tab and its annotation. /// /// Pinned per rule rather than once over the script: a rule added later that reads /// `worklane tags` raw is the bug this catches, and it would not show up in a single /// `contains`. #[test] fn every_tag_rule_takes_the_annotation_as_its_description() { let script = fish_dynamic(); let reading: Vec<&str> = script .lines() .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, "expected the ls --tag rule, the append --tags one and the tags set one: {reading:?}" ); for line in reading { assert!(line.contains("(worklane tags | cut -f1,3)"), "{line}"); } } /// The one status positional and the one shell positional, which clap does not emit /// possible values for. Read off the enums, so a fifth status would appear here on /// its own. #[test] fn the_fish_script_lists_the_statuses_and_the_shells() { let script = fish_dynamic(); for status in Status::ALL { assert!( script.contains(status.as_str()), "the ls positional is never offered {}", status.as_str() ); } assert!(script.contains("-a 'backlog committed reviewing done discarded' -d status")); for shell in ["fish", "bash", "zsh", "elvish", "powershell"] { assert!(script.contains(shell), "the shell positional is never offered {shell}"); } } /// The statuses for `mv --status` are clap's, which is half of why `Status` is a /// `ValueEnum`. If clap ever stops emitting them, the fish half has to carry them /// too, and this is what says so. #[test] fn clap_emits_the_statuses_for_the_status_flag() { let mut out = Vec::new(); generate(Shell::Fish, &mut out).expect("generates"); let script = String::from_utf8(out).expect("utf8"); let flag = script .lines() .find(|line| line.contains("using_subcommand mv") && line.contains("-l status")) .expect("mv --status has a rule of its own"); assert!(flag.contains("backlog"), "{flag}"); } #[test] fn generating_fish_produces_both_halves() { let mut out = Vec::new(); generate(Shell::Fish, &mut out).expect("generates"); let script = String::from_utf8(out).expect("utf8"); // clap's half. assert!(script.contains("complete -c worklane")); assert!(script.contains("install-skill")); // Ours. assert!(script.contains("__worklane_first_arg_of")); } #[test] fn other_shells_get_only_the_generated_half() { for shell in [Shell::Bash, Shell::Zsh] { let mut out = Vec::new(); generate(shell, &mut out).expect("generates"); let script = String::from_utf8(out).expect("utf8"); assert!( !script.contains("__worklane_first_arg_of"), "fish-only helpers leaked into {shell}" ); } } }