/
cmd_completion.go
98 lines (79 loc) · 2.29 KB
/
cmd_completion.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// cmd_completion.go: Helpers for completion
package subcommands
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// CommandList is a structure which implements the built-in "commands" subcommand
type CommandList struct {
// We embed the NoFlags option, because we accept no
// command-line flags.
NoFlags
}
// Execute the command.
func (c *CommandList) Execute(args []string) int {
//
// Examine each known sub-command
//
for _, c := range known {
//
// Get the name of the subcommand.
//
name, _ := c.Info()
fmt.Printf("%s\n", name)
}
return 0
}
// Info returns the name of this subcommand, along with a one-line synopsis.
func (c *CommandList) Info() (string, string) {
return "commands", "Show all available sub-commands."
}
// BashCompletion is a structure which implements the built-in
// "bash-completion" subcommand.
type BashCompletion struct {
// We embed the NoFlags option, because we accept no
// command-line flags.
NoFlags
}
// Execute the command.
func (bc *BashCompletion) Execute(args []string) int {
tmpl := `
_subcommands_#Command#()
{
local cur
local prev=$3
COMPREPLY=()
# Variable to hold the current word
cur="${COMP_WORDS[COMP_CWORD]}"
# The first argument is one of the available sub-commands.
if [ $COMP_CWORD = 1 ]; then
local subs=$(#Command# commands)
COMPREPLY=($(compgen -W "${subs}" $cur))
else
# If we see a dash complete from the available flags,
# otherwise a file/directory.
if [[ "$cur" =~ ^-.* ]]; then
local flags="$(#Command# help ${COMP_WORDS[1]} | awk '{print $1}' | grep -- -)"
COMPREPLY=($(compgen -W "${flags}" -- "$cur"))
else
if [[ "$prev" == "help" ]]; then
local subs=$(#Command# commands)
COMPREPLY=($(compgen -W "${subs}" $cur))
else
COMPREPLY=($(compgen -f -- ${cur}))
fi
fi
fi
}
complete -F _subcommands_#Command# #Command#
`
output := strings.ReplaceAll(tmpl, "#Command#", filepath.Base(os.Args[0]))
fmt.Printf("%s\n", output)
return 0
}
// Info returns the name of this subcommand, along with a one-line synopsis.
func (bc *BashCompletion) Info() (string, string) {
return "bash-completion", "Generate and output a bash completion-script."
}