-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompletion_bash.go
More file actions
71 lines (56 loc) · 1.64 KB
/
completion_bash.go
File metadata and controls
71 lines (56 loc) · 1.64 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
68
69
70
71
package cli
import (
"context"
"fmt"
)
// BashCompletion implements bash shell completion
type BashCompletion struct{}
func (b *BashCompletion) GetCompletions(cmd *Command, args []string) []string {
return getCompletionWords(cmd)
}
func (b *BashCompletion) Register(cmd *Command) {
bashCmd := Cmd("__bashcomplete").
Description("Bash completion helper").
Hidden().
Action(func(ctx context.Context, bashCommand *Command) error {
targetCmd := bashCommand.GetParent()
// For completion, we don't need args since we complete the parent
words := b.GetCompletions(targetCmd, nil)
for _, word := range words {
fmt.Println(word)
}
return nil
})
cmd.AddCommand(bashCmd)
// Recursively register for all subcommands
for _, subcmd := range cmd.GetCommands() {
if !subcmd.IsHidden() {
b.Register(subcmd)
}
}
}
func (b *BashCompletion) GenerateScript(cmd *Command) string {
cmdName := cmd.GetName()
script := fmt.Sprintf(`# Bash completion script for %s
# Source this file to enable bash completion:
# source <(%s __bashcomplete)
_%s_completion() {
local cur prev words cword
_init_completion || return
# Get the full command path
local cmd_path="${COMP_WORDS[0]}"
for ((i=1; i < COMP_CWORD; i++)); do
local word="${COMP_WORDS[i]}"
if [[ "$word" != -* ]]; then
cmd_path="$cmd_path $word"
fi
done
# Get completions from the command
local completions=$($cmd_path __bashcomplete 2>/dev/null)
# Generate reply
COMPREPLY=($(compgen -W "$completions" -- "$cur"))
}
complete -F _%s_completion %s
`, cmdName, cmdName, cmdName, cmdName, cmdName)
return script
}