-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcompletion.go
More file actions
67 lines (54 loc) · 1.79 KB
/
completion.go
File metadata and controls
67 lines (54 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package cli
import (
"bytes"
"os"
"text/template"
"github.com/jessevdk/go-flags"
)
// CompletionCommand defines the default completion command. Most of the time, it
// should not be used directly, since it will be added by default to the App.
type CompletionCommand struct {
PlainCommand `name:"completion" short-description:"print bash completion script"`
Name string
}
// InitCompletionCommand returns an additional AddCommand function that fills
// the CompletionCommand long description
func InitCompletionCommand(appname string) func(*flags.Command) {
return func(c *flags.Command) {
t := template.Must(template.New("desc").Parse(
`Print a bash completion script for {{.Name}}.
You can place it on /etc/bash_completion.d/{{.Name}}, or add it to your .bashrc running:
echo "source <({{.Name}} completion)" >> ~/.bashrc
`))
var tpl bytes.Buffer
t.Execute(&tpl, struct{ Name string }{appname})
c.LongDescription = tpl.String()
}
}
// Execute runs the install command.
func (c CompletionCommand) Execute(args []string) error {
t := template.Must(template.New("completion").Parse(
`# Save this file to /etc/bash_completion.d/{{.Name}}
#
# or add the following line to your .bashrc file:
# source <({{.Name}} completion)
# running:
# echo "source <({{.Name}} completion)" >> ~/.bashrc
_completion-{{.Name}}() {
# All arguments except the first one
args=("${COMP_WORDS[@]:1:$COMP_CWORD}")
# Only split on newlines
local IFS=$'\n'
# Call completion (note that the first element of COMP_WORDS is
# the executable itself)
COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} "${args[@]}"))
return 0
}
complete -F _completion-{{.Name}} {{.Name}}
`))
err := t.Execute(os.Stdout, struct{ Name string }{c.Name})
if err != nil {
return err
}
return nil
}