-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbash.go
66 lines (53 loc) · 1.63 KB
/
bash.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
package completion
import (
"io"
"path/filepath"
home "github.com/mitchellh/go-homedir"
)
type bash struct {
goos string
programName string
}
var _ Shell = &bash{}
func Bash(goos string, programName string) Shell {
return &bash{goos: goos, programName: programName}
}
// Name implements Shell.
func (b *bash) Name() string {
return "bash"
}
// InstallPath implements Shell.
func (b *bash) InstallPath() (string, error) {
homeDir, err := home.Dir()
if err != nil {
return "", err
}
if b.goos == "darwin" {
return filepath.Join(homeDir, ".bash_profile"), nil
}
return filepath.Join(homeDir, ".bashrc"), nil
}
// WriteCompletion implements Shell.
func (b *bash) WriteCompletion(w io.Writer) error {
return configTemplateWriter(w, bashCompletionTemplate, b.programName)
}
// ProgramName implements Shell.
func (b *bash) ProgramName() string {
return b.programName
}
const bashCompletionTemplate = `
_generate_{{.Name}}_completions() {
# Capture the line excluding the command, and everything after the current word
local args=("${COMP_WORDS[@]:1:COMP_CWORD}")
# Set COMPLETION_MODE and call the command with the arguments, capturing the output
local completions=$(COMPLETION_MODE=1 "{{.Name}}" "${args[@]}")
# Use the command's output to generate completions for the current word
COMPREPLY=($(compgen -W "$completions" -- "${COMP_WORDS[COMP_CWORD]}"))
# Ensure no files are shown, even if there are no matches
if [ ${#COMPREPLY[@]} -eq 0 ]; then
COMPREPLY=()
fi
}
# Setup Bash to use the function for completions for '{{.Name}}'
complete -F _generate_{{.Name}}_completions {{.Name}}
`