Merge pull request #257 from sttts/sttts-noun-aliases
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add noun aliases
authored by Eric Paris · committed by Eric Paris · parents 2ccf9e9, 1a0a490 · Browse files · 4 files·+64 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+64 added−8 removed
- other:+64 added−8 removed
Provenance
- Commit
60267ae- Tree
131cbf9- Author
Eric Paris <eparis@redhat.com>- Committer
Eric Paris <eparis@redhat.com>- Parent 1
2ccf9e9- Parent 2
1a0a490
4 files changed+64 added−8 removed
modified:bash_completions_test.go+10 added-2 removed
41 unmodified lines42 // required flag43 c.MarkFlagRequired("introot")44 45 // valid nouns46- validArgs := []string{"pods", "nodes", "services", "replicationControllers"}46+ validArgs := []string{"pod", "node", "service", "replicationcontroller"}47 c.ValidArgs = validArgs48 49+ // noun aliases50+ argAliases := []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"}51+ c.ArgAliases = argAliases52+53 // filename54 var flagval string55 c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")56 c.MarkFlagFilename("filename", "json", "yaml", "yml")34 unmodified lines91 check(t, str, `must_have_one_flag+=("--persistent-filename=")`)92 // check for custom completion function93 check(t, str, `COMPREPLY=( "hello" )`)94 // check for required nouns91- check(t, str, `must_have_one_noun+=("pods")`)95+ check(t, str, `must_have_one_noun+=("pod")`)96+ // check for noun aliases97+ check(t, str, `noun_aliases+=("pods")`)98+ check(t, str, `noun_aliases+=("rc")`)99+ checkOmit(t, str, `must_have_one_noun+=("pods")`)100 // check for filename extension flags101 check(t, str, `flags_completion+=("_filedir")`)102 // check for filename extension flags103 check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)7 unmodified linesmodified:bash_completions.go+23 added-3 removed
121 unmodified lines122 completions=("${commands[@]}")123 fi124 COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )125 126+ if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then127+ COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") )128+ fi129+130 if [[ ${#COMPREPLY[@]} -eq 0 ]]; then131 declare -F __custom_func >/dev/null && __custom_func132 fi133 58 unmodified lines192 __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"193 194 if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then195 must_have_one_noun=()192- elif __contains_word "${words[c]%s}" "${must_have_one_noun[@]}"; then196+ elif __contains_word "${words[c]}" "${noun_aliases[@]}"; then197 must_have_one_noun=()198 fi199 200 nouns+=("${words[c]}")262 unmodified lines463 })464 return visitErr465 }466 463-func writeRequiredNoun(cmd *Command, w io.Writer) error {467+func writeRequiredNouns(cmd *Command, w io.Writer) error {468 if _, err := fmt.Fprintf(w, " must_have_one_noun=()\n"); err != nil {469 return err470 }471 sort.Sort(sort.StringSlice(cmd.ValidArgs))4 unmodified lines476 }477 return nil478 }479 480+func writeArgAliases(cmd *Command, w io.Writer) error {481+ if _, err := fmt.Fprintf(w, " noun_aliases=()\n"); err != nil {482+ return err483+ }484+ sort.Sort(sort.StringSlice(cmd.ArgAliases))485+ for _, value := range cmd.ArgAliases {486+ if _, err := fmt.Fprintf(w, " noun_aliases+=(%q)\n", value); err != nil {487+ return err488+ }489+ }490+ return nil491+}492+493 func gen(cmd *Command, w io.Writer) error {494 for _, c := range cmd.Commands() {495 if !c.IsAvailableCommand() || c == cmd.helpCommand {496 continue19 unmodified lines516 }517 if err := writeRequiredFlag(cmd, w); err != nil {518 return err519 }503- if err := writeRequiredNoun(cmd, w); err != nil {520+ if err := writeRequiredNouns(cmd, w); err != nil {521 return err522 }523+ if err := writeArgAliases(cmd, w); err != nil {524+ return err525+ }526 if _, err := fmt.Fprintf(w, "}\n\n"); err != nil {527 return err528 }529 return nil71 unmodified linesmodified:bash_completions.md+27 added-2 removed
78 unmodified lines7980818283838485868710 unmodified lines989910010110210210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213373 unmodified lines78 unmodified lines
In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:
```govalidArgs []string = { "pods", "nodes", "services", "replicationControllers" }validArgs []string = { "pod", "node", "service", "replicationcontroller" }
cmd := &cobra.Command{ Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", Short: "Display one or many resources",10 unmodified linesNotice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like
```bash# kubectl get [tab][tab]nodes pods replicationControllers servicesnode pod replicationcontroller service```
## Plural form and shortcuts for nouns
If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
```go`argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
cmd := &cobra.Command{ ... ValidArgs: validArgs, ArgAliases: argAliases}```
The aliases are not shown to the user on tab completion, but they are accepted as valid nouns bythe completion aglorithm if entered manually, e.g. in:
```bash# kubectl get rc [tab][tab]backend frontend database ```
Note that without declaring `rc` as an alias, the completion algorithm would show the list of nounsin this example again instead of the replication controllers.
## Mark flags as required
Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy.
73 unmodified linesmodified:command.go+4 added-1 removed
43 unmodified lines44 // The long message shown in the 'help <this-command>' output.45 Long string46 // Examples of how to use the command47 Example string48- // List of all valid non-flag arguments, used for bash completions *TODO* actually validate these48+ // List of all valid non-flag arguments that are accepted in bash completions49 ValidArgs []string50+ // List of aliases for ValidArgs. These are not suggested to the user in the bash51+ // completion, but accepted if entered manually.52+ ArgAliases []string53 // Custom functions used by the bash autocompletion generator54 BashCompletionFunction string55 // Is this command deprecated and should print this string when used?56 Deprecated string1137 unmodified lines