Skip to content
Myr

Add bash autocompletion generator

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Given a (potentially annotated) cobra command you can generate a bash completion script.

authored by Eric Paris · committed by Eric Paris · parent f576d29 · Browse files · 5 files+557 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+557 added−0 removed

  • other:+557 added−0 removed

5 files+557 added−0 removed

added:bash_completions_test.go+74 added
1package cobra23import (4 "bytes"5 "fmt"6 "os"7 "strings"8 "testing"9)1011var _ = fmt.Println12var _ = os.Stderr1314func check(t *testing.T, found, expected string) {15 if !strings.Contains(found, expected) {16 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)17 }18}1920// World worst custom function, just keep telling you to enter hello!21const (22 bash_completion_func = `__custom_func() {23COMPREPLY=( "hello" )24}25`26)2728func TestBashCompletions(t *testing.T) {29 c := initializeWithRootCmd()30 cmdEcho.AddCommand(cmdTimes)31 c.AddCommand(cmdEcho, cmdPrint)3233 // custom completion function34 c.BashCompletionFunction = bash_completion_func3536 // required flag37 c.MarkFlagRequired("introot")3839 // valid nounds40 validArgs := []string{"pods", "nodes", "services", "replicationControllers"}41 c.ValidArgs = validArgs4243 // filename extentions44 annotations := make([]string, 3)45 annotations[0] = "json"46 annotations[1] = "yaml"47 annotations[2] = "yml"4849 annotation := make(map[string][]string)50 annotation[BashCompFilenameExt] = annotations5152 var flagval string53 c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")54 flag := c.Flags().Lookup("filename")55 flag.Annotations = annotation5657 out := new(bytes.Buffer)58 c.GenBashCompletion(out)59 str := out.String()6061 check(t, str, "_cobra-test")62 check(t, str, "_cobra-test_echo")63 check(t, str, "_cobra-test_echo_times")64 check(t, str, "_cobra-test_print")6566 // check for required flags67 check(t, str, `must_have_one_flag+=("--introot=")`)68 // check for custom completion function69 check(t, str, `COMPREPLY=( "hello" )`)70 // check for required nouns71 check(t, str, `must_have_one_noun+=("pods")`)72 // check for filename extention flags73 check(t, str, `flags_completion+=("_filedir '@(json|yaml|yml)'")`)74}
added:bash_completions.go+330 added
1package cobra23import (4 "bytes"5 "fmt"6 "os"7 "strings"89 "github.com/spf13/pflag"10)1112const (13 BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions"14 BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"15)1617func preamble(out *bytes.Buffer) {18 fmt.Fprintf(out, `#!/bin/bash192021__debug()22{23 if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then24 echo "$*" >> ${BASH_COMP_DEBUG_FILE}25 fi26}2728__index_of_word()29{30 local w word=$131 shift32 index=033 for w in "$@"; do34 [[ $w = "$word" ]] && return35 index=$((index+1))36 done37 index=-138}3940__contains_word()41{42 local w word=$1; shift43 for w in "$@"; do44 [[ $w = "$word" ]] && return45 done46 return 147}4849__handle_reply()50{51 __debug "${FUNCNAME}"52 case $cur in53 -*)54 compopt -o nospace55 local allflags56 if [ ${#must_have_one_flag[@]} -ne 0 ]; then57 allflags=("${must_have_one_flag[@]}")58 else59 allflags=("${flags[*]} ${two_word_flags[*]}")60 fi61 COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )62 [[ $COMPREPLY == *= ]] || compopt +o nospace63 return 0;64 ;;65 esac6667 # check if we are handling a flag with special work handling68 local index69 __index_of_word "${prev}" "${flags_with_completion[@]}"70 if [[ ${index} -ge 0 ]]; then71 ${flags_completion[${index}]}72 return73 fi7475 # we are parsing a flag and don't have a special handler, no completion76 if [[ ${cur} != "${words[cword]}" ]]; then77 return78 fi7980 local completions81 if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then82 completions=("${must_have_one_flag[@]}")83 elif [[ ${#must_have_one_noun[@]} -ne 0 ]]; then84 completions=("${must_have_one_noun[@]}")85 else86 completions=("${commands[@]}")87 fi88 COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )8990 if [[ ${#COMPREPLY[@]} -eq 0 ]]; then91 declare -F __custom_func >/dev/null && __custom_func92 fi93}9495__handle_flag()96{97 __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"9899 # if a command required a flag, and we found it, unset must_have_one_flag()100 local flagname=${words[c]}101 # if the word contained an =102 if [[ ${words[c]} == *"="* ]]; then103 flagname=${flagname%%=*} # strip everything after the =104 flagname="${flagname}=" # but put the = back105 fi106 __debug "${FUNCNAME}: looking for ${flagname}"107 if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then108 must_have_one_flag=()109 fi110111 # skip the argument to a two word flag112 if __contains_word "${words[c]}" "${two_word_flags[@]}"; then113 c=$((c+1))114 # if we are looking for a flags value, don't show commands115 if [[ $c -eq $cword ]]; then116 commands=()117 fi118 fi119120 # skip the flag itself121 c=$((c+1))122123}124125__handle_noun()126{127 __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"128129 if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then130 must_have_one_noun=()131 fi132133 nouns+=("${words[c]}")134 c=$((c+1))135}136137__handle_command()138{139 __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"140141 local next_command142 if [[ -n ${last_command} ]]; then143 next_command="_${last_command}_${words[c]}"144 else145 next_command="_${words[c]}"146 fi147 c=$((c+1))148 __debug "${FUNCNAME}: looking for ${next_command}"149 declare -F $next_command >/dev/null && $next_command150}151152__handle_word()153{154 if [[ $c -ge $cword ]]; then155 __handle_reply156 return157 fi158 __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"159 if [[ "${words[c]}" == -* ]]; then160 __handle_flag161 elif __contains_word "${words[c]}" "${commands[@]}"; then162 __handle_command163 else164 __handle_noun165 fi166 __handle_word167}168169`)170}171172func postscript(out *bytes.Buffer, name string) {173 fmt.Fprintf(out, "__start_%s()\n", name)174 fmt.Fprintf(out, `{175 local cur prev words cword split176 _init_completion -s || return177178 local completions_func179 local c=0180 local flags=()181 local two_word_flags=()182 local flags_with_completion=()183 local flags_completion=()184 local commands=("%s")185 local must_have_one_flag=()186 local must_have_one_noun=()187 local last_command188 local nouns=()189190 __handle_word191}192193`, name)194 fmt.Fprintf(out, "complete -F __start_%s %s\n", name, name)195 fmt.Fprintf(out, "# ex: ts=4 sw=4 et filetype=sh\n")196}197198func writeCommands(cmd *Command, out *bytes.Buffer) {199 fmt.Fprintf(out, " commands=()\n")200 for _, c := range cmd.Commands() {201 fmt.Fprintf(out, " commands+=(%q)\n", c.Name())202 }203 fmt.Fprintf(out, "\n")204}205206func writeFlagHandler(name string, annotations map[string][]string, out *bytes.Buffer) {207 for key, value := range annotations {208 switch key {209 case BashCompFilenameExt:210 fmt.Fprintf(out, " flags_with_completion+=(%q)\n", name)211212 ext := strings.Join(value, "|")213 ext = "_filedir '@(" + ext + ")'"214 fmt.Fprintf(out, " flags_completion+=(%q)\n", ext)215 }216 }217}218219func writeShortFlag(flag *pflag.Flag, out *bytes.Buffer) {220 b := (flag.Value.Type() == "bool")221 name := flag.Shorthand222 format := " "223 if !b {224 format += "two_word_"225 }226 format += "flags+=(\"-%s\")\n"227 fmt.Fprintf(out, format, name)228 writeFlagHandler("-"+name, flag.Annotations, out)229}230231func writeFlag(flag *pflag.Flag, out *bytes.Buffer) {232 b := (flag.Value.Type() == "bool")233 name := flag.Name234 format := " flags+=(\"--%s"235 if !b {236 format += "="237 }238 format += "\")\n"239 fmt.Fprintf(out, format, name)240 writeFlagHandler("--"+name, flag.Annotations, out)241}242243func writeFlags(cmd *Command, out *bytes.Buffer) {244 fmt.Fprintf(out, ` flags=()245 two_word_flags=()246 flags_with_completion=()247 flags_completion=()248249`)250 cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {251 writeFlag(flag, out)252 if len(flag.Shorthand) > 0 {253 writeShortFlag(flag, out)254 }255 })256257 fmt.Fprintf(out, "\n")258}259260func writeRequiredFlag(cmd *Command, out *bytes.Buffer) {261 fmt.Fprintf(out, " must_have_one_flag=()\n")262 flags := cmd.NonInheritedFlags()263 flags.VisitAll(func(flag *pflag.Flag) {264 for key, _ := range flag.Annotations {265 switch key {266 case BashCompOneRequiredFlag:267 format := " must_have_one_flag+=(\"--%s"268 b := (flag.Value.Type() == "bool")269 if !b {270 format += "="271 }272 format += "\")\n"273 fmt.Fprintf(out, format, flag.Name)274275 if len(flag.Shorthand) > 0 {276 fmt.Fprintf(out, " must_have_one_flag+=(\"-%s\")\n", flag.Shorthand)277 }278 }279 }280 })281}282283func writeRequiredNoun(cmd *Command, out *bytes.Buffer) {284 fmt.Fprintf(out, " must_have_one_noun=()\n")285 for _, value := range cmd.ValidArgs {286 fmt.Fprintf(out, " must_have_one_noun+=(%q)\n", value)287 }288}289290func gen(cmd *Command, out *bytes.Buffer) {291 for _, c := range cmd.Commands() {292 gen(c, out)293 }294 commandName := cmd.CommandPath()295 commandName = strings.Replace(commandName, " ", "_", -1)296 fmt.Fprintf(out, "_%s()\n{\n", commandName)297 fmt.Fprintf(out, " last_command=%q\n", commandName)298 writeCommands(cmd, out)299 writeFlags(cmd, out)300 writeRequiredFlag(cmd, out)301 writeRequiredNoun(cmd, out)302 fmt.Fprintf(out, "}\n\n")303}304305func (cmd *Command) GenBashCompletion(out *bytes.Buffer) {306 preamble(out)307 if len(cmd.BashCompletionFunction) > 0 {308 fmt.Fprintf(out, "%s\n", cmd.BashCompletionFunction)309 }310 gen(cmd, out)311 postscript(out, cmd.Name())312}313314func (cmd *Command) GenBashCompletionFile(filename string) error {315 out := new(bytes.Buffer)316317 cmd.GenBashCompletion(out)318319 outFile, err := os.Create(filename)320 if err != nil {321 return err322 }323 defer outFile.Close()324325 _, err = outFile.Write(out.Bytes())326 if err != nil {327 return err328 }329 return nil330}
added:bash_completions.md+146 added
1# Generating Bash Completions For Your Own cobra.Command23Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:45```go6package main78import (9 "io/ioutil"10 "os"1112 "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"13)1415func main() {16 kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)17 kubectl.GenBashCompletionFile("out.sh")18}19```2021That will get you completions of subcommands and flags. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.2223## Creating your own custom functions2425Some more actual code that works in kubernetes:2627```bash28const (29 bash_completion_func = `__kubectl_parse_get()30{31 local kubectl_output out32 if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then33 out=($(echo "${kubectl_output}" | awk '{print $1}'))34 COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )35 fi36}3738__kubectl_get_resource()39{40 if [[ ${#nouns[@]} -eq 0 ]]; then41 return 142 fi43 __kubectl_parse_get ${nouns[${#nouns[@]} -1]}44 if [[ $? -eq 0 ]]; then45 return 046 fi47}4849__custom_func() {50 case ${last_command} in51 kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)52 __kubectl_get_resource53 return54 ;;55 *)56 ;;57 esac58}59`)60```6162And then I set that in my command definition:6364```go65cmds := &cobra.Command{66 Use: "kubectl",67 Short: "kubectl controls the Kubernetes cluster manager",68 Long: `kubectl controls the Kubernetes cluster manager.6970Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,71 Run: runHelp,72 BashCompletionFunction: bash_completion_func,73}74```7576The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__custom_func()` to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!7778## Have the completions code complete your 'nouns'7980In 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:8182```go83validArgs []string = { "pods", "nodes", "services", "replicationControllers" }8485cmd := &cobra.Command{86 Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",87 Short: "Display one or many resources",88 Long: get_long,89 Example: get_example,90 Run: func(cmd *cobra.Command, args []string) {91 err := RunGet(f, out, cmd, args)92 util.CheckErr(err)93 },94 ValidArgs: validArgs,95}96```9798Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like99100```bash101# kubectl get [tab][tab]102nodes pods replicationControllers services103```104105## Mark flags as required106107Most 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.108109```go110cmd.MarkFlagRequired("pod")111cmd.MarkFlagRequired("container")112```113114and you'll get something like115116```bash117# kubectl exec [tab][tab][tab]118-c --container= -p --pod= 119```120121# Specify valid filename extentions for flags that take a filename122123In this example we use --filename= and expect to get a json or yaml file as the argument. To make this easier we annotate the --filename flag with valid filename extensions.124125```go126 annotations := make([]string, 3)127 annotations[0] = "json"128 annotations[1] = "yaml"129 annotations[2] = "yml"130131 annotation := make(map[string][]string)132 annotation[cobra.BashCompFilenameExt] = annotations133134 flag := &pflag.Flag{"filename", "f", usage, value, value.String(), false, annotation}135 cmd.Flags().AddFlag(flag)136```137138Now when you run a command with this filename flag you'll get something like139140```bash141# kubectl create -f 142test/ example/ rpmbuild/143hello.yml test.json144```145146So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.
modified:command.go+4 added
42 unmodified lines
43 // The long message shown in the 'help <this-command>' output.44 Long string45 // Examples of how to use the command46 Example string47 // List of all valid non-flag arguments, used for bash completions *TODO* actually validate these48 ValidArgs []string49 // Custom functions used by the bash autocompletion generator50 BashCompletionFunction string51 // Full set of flags52 flags *flag.FlagSet53 // Set of flags childrens of this command will inherit54 pflags *flag.FlagSet
906 unmodified lines
modified:README.md+3 added
346 unmodified lines
347 command.SetUsageFunc(f func(*Command) error)348349 command.SetUsageTemplate(s string)350351## Generating bash completions for your command352353Cobra can generate a bash completions file. If you add more information to your command these completions can be amazingly powerful and flexible. Read more about [Bash Completions](bash_completions.md)354355## Debugging356357Cobra provides a ‘DebugFlags’ method on a command which when called will print358out everything Cobra knows about the flags for each command
53 unmodified lines