package cmd import ( "io" "text/template" "go.fifitido.net/cmd/opt" ) func WriteBashCompletions(out io.Writer, rootCmd *Command) error { return bashTpl.Execute(out, map[string]any{ "RootCmd": rootCmd, "GlobalOpts": opt.Globals(), }) } var bashTpl = template.Must(template.New("bash").Funcs(tplFuncs).Parse(` {{- $rootCmd := .RootCmd -}} {{- $progName := $rootCmd.Name -}} {{- $varName := under $rootCmd.Name -}} {{- define "cmd" }} {{ $currIdx := .Index }} {{ $nextIdx := inc .Index }} "{{ .Cmd.Name }}") case ${COMP_WORDS[{{ $currIdx }}]} in {{ range .Cmd.Subcommands -}} {{ template "cmd" (map "Cmd" . "Index" $nextIdx) -}} {{ end }} *) COMPREPLY=($(compgen -W "{{ join .Cmd.Subcommands.Names " " }} {{ join .Cmd.Opts.Names " " }}" -- $curr)) esac ;; {{ end -}} _{{$varName}}_completions() { local curr prev COMPREPLY=() curr=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} case ${COMP_WORDS[1]} in {{ range .RootCmd.Subcommands -}} {{ template "cmd" (map "Cmd" . "Index" 2) -}} {{ end }} *) COMPREPLY=($(compgen -W "{{ join .RootCmd.Subcommands.Names " " }} {{ join .RootCmd.Opts.Names " " }}" -- $curr)) esac } complete -F _{{$varName}}_completions {{$progName}} `))