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
Provenance
- Commit
9b2e682- Tree
8c1147a- Author
Eric Paris <eparis@redhat.com>- Committer
Eric Paris <eparis@redhat.com>- Parent
f576d29
5 files changed+557 added−0 removed
added:bash_completions_test.go+74 added
1+package cobra2+3+import (4+ "bytes"5+ "fmt"6+ "os"7+ "strings"8+ "testing"9+)10+11+var _ = fmt.Println12+var _ = os.Stderr13+14+func 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+}19+20+// World worst custom function, just keep telling you to enter hello!21+const (22+ bash_completion_func = `__custom_func() {23+COMPREPLY=( "hello" )24+}25+`26+)27+28+func TestBashCompletions(t *testing.T) {29+ c := initializeWithRootCmd()30+ cmdEcho.AddCommand(cmdTimes)31+ c.AddCommand(cmdEcho, cmdPrint)32+33+ // custom completion function34+ c.BashCompletionFunction = bash_completion_func35+36+ // required flag37+ c.MarkFlagRequired("introot")38+39+ // valid nounds40+ validArgs := []string{"pods", "nodes", "services", "replicationControllers"}41+ c.ValidArgs = validArgs42+43+ // filename extentions44+ annotations := make([]string, 3)45+ annotations[0] = "json"46+ annotations[1] = "yaml"47+ annotations[2] = "yml"48+49+ annotation := make(map[string][]string)50+ annotation[BashCompFilenameExt] = annotations51+52+ var flagval string53+ c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")54+ flag := c.Flags().Lookup("filename")55+ flag.Annotations = annotation56+57+ out := new(bytes.Buffer)58+ c.GenBashCompletion(out)59+ str := out.String()60+61+ 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")65+66+ // 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
1+package cobra2+3+import (4+ "bytes"5+ "fmt"6+ "os"7+ "strings"8+9+ "github.com/spf13/pflag"10+)11+12+const (13+ BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions"14+ BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"15+)16+17+func preamble(out *bytes.Buffer) {18+ fmt.Fprintf(out, `#!/bin/bash19+20+21+__debug()22+{23+ if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then24+ echo "$*" >> ${BASH_COMP_DEBUG_FILE}25+ fi26+}27+28+__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+}39+40+__contains_word()41+{42+ local w word=$1; shift43+ for w in "$@"; do44+ [[ $w = "$word" ]] && return45+ done46+ return 147+}48+49+__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+ esac66+67+ # 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+ fi74+75+ # we are parsing a flag and don't have a special handler, no completion76+ if [[ ${cur} != "${words[cword]}" ]]; then77+ return78+ fi79+80+ 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") )89+90+ if [[ ${#COMPREPLY[@]} -eq 0 ]]; then91+ declare -F __custom_func >/dev/null && __custom_func92+ fi93+}94+95+__handle_flag()96+{97+ __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"98+99+ # 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+ fi110+111+ # 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+ fi119+120+ # skip the flag itself121+ c=$((c+1))122+123+}124+125+__handle_noun()126+{127+ __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"128+129+ if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then130+ must_have_one_noun=()131+ fi132+133+ nouns+=("${words[c]}")134+ c=$((c+1))135+}136+137+__handle_command()138+{139+ __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"140+141+ 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+}151+152+__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+}168+169+`)170+}171+172+func 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 || return177+178+ 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=()189+190+ __handle_word191+}192+193+`, 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+}197+198+func 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+}205+206+func 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)211+212+ ext := strings.Join(value, "|")213+ ext = "_filedir '@(" + ext + ")'"214+ fmt.Fprintf(out, " flags_completion+=(%q)\n", ext)215+ }216+ }217+}218+219+func 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+}230+231+func 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+}242+243+func writeFlags(cmd *Command, out *bytes.Buffer) {244+ fmt.Fprintf(out, ` flags=()245+ two_word_flags=()246+ flags_with_completion=()247+ flags_completion=()248+249+`)250+ cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {251+ writeFlag(flag, out)252+ if len(flag.Shorthand) > 0 {253+ writeShortFlag(flag, out)254+ }255+ })256+257+ fmt.Fprintf(out, "\n")258+}259+260+func 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)274+275+ if len(flag.Shorthand) > 0 {276+ fmt.Fprintf(out, " must_have_one_flag+=(\"-%s\")\n", flag.Shorthand)277+ }278+ }279+ }280+ })281+}282+283+func 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+}289+290+func 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+}304+305+func (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+}313+314+func (cmd *Command) GenBashCompletionFile(filename string) error {315+ out := new(bytes.Buffer)316+317+ cmd.GenBashCompletion(out)318+319+ outFile, err := os.Create(filename)320+ if err != nil {321+ return err322+ }323+ defer outFile.Close()324+325+ _, 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.Command2+3+Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:4+5+```go6+package main7+8+import (9+ "io/ioutil"10+ "os"11+12+ "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"13+)14+15+func main() {16+ kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)17+ kubectl.GenBashCompletionFile("out.sh")18+}19+```20+21+That 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.22+23+## Creating your own custom functions24+25+Some more actual code that works in kubernetes:26+27+```bash28+const (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+}37+38+__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+}48+49+__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+```61+62+And then I set that in my command definition:63+64+```go65+cmds := &cobra.Command{66+ Use: "kubectl",67+ Short: "kubectl controls the Kubernetes cluster manager",68+ Long: `kubectl controls the Kubernetes cluster manager.69+70+Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,71+ Run: runHelp,72+ BashCompletionFunction: bash_completion_func,73+}74+```75+76+The `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!77+78+## Have the completions code complete your 'nouns'79+80+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:81+82+```go83+validArgs []string = { "pods", "nodes", "services", "replicationControllers" }84+85+cmd := &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+```97+98+Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like99+100+```bash101+# kubectl get [tab][tab]102+nodes pods replicationControllers services103+```104+105+## Mark flags as required106+107+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.108+109+```go110+cmd.MarkFlagRequired("pod")111+cmd.MarkFlagRequired("container")112+```113+114+and you'll get something like115+116+```bash117+# kubectl exec [tab][tab][tab]118+-c --container= -p --pod= 119+```120+121+# Specify valid filename extentions for flags that take a filename122+123+In 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.124+125+```go126+ annotations := make([]string, 3)127+ annotations[0] = "json"128+ annotations[1] = "yaml"129+ annotations[2] = "yml"130+131+ annotation := make(map[string][]string)132+ annotation[cobra.BashCompFilenameExt] = annotations133+134+ flag := &pflag.Flag{"filename", "f", usage, value, value.String(), false, annotation}135+ cmd.Flags().AddFlag(flag)136+```137+138+Now when you run a command with this filename flag you'll get something like139+140+```bash141+# kubectl create -f 142+test/ example/ rpmbuild/143+hello.yml test.json144+```145+146+So 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 lines43 // 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.FlagSet906 unmodified linesmodified:README.md+3 added
346 unmodified lines347 command.SetUsageFunc(f func(*Command) error)348 349 command.SetUsageTemplate(s string)350 351+## Generating bash completions for your command352 353+Cobra 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)354+355 ## Debugging356 357 Cobra provides a ‘DebugFlags’ method on a command which when called will print358 out everything Cobra knows about the flags for each command53 unmodified lines