forked from alexellis/arkade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompletion.go
87 lines (73 loc) · 2.15 KB
/
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
// Copyright (c) arkade author(s) 2020. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package cmd
import (
"fmt"
"io"
"os"
"github.com/spf13/cobra"
)
const completionCmd = `Use "arkade completion SHELL" to generate SHELL completion for:
- bash
- zsh
`
func MakeShellCompletion() *cobra.Command {
completion := &cobra.Command{
Use: "completion SHELL",
Short: "Output shell completion for the given shell (bash or zsh)",
Long: `
Outputs shell completion for the given shell (bash or zsh)
This depends on the bash-completion binary. Example installation instructions:
OS X:
$ brew install bash-completion
$ source $(brew --prefix)/etc/bash_completion
$ arkade completion bash > ~/.arkade-completion # for bash users
$ arkade completion zsh > ~/.arkade-completion # for zsh users
$ source ~/.arkade-completion
Ubuntu:
$ apt-get install bash-completion
$ source /etc/bash-completion
$ source <(arkade completion bash) # for bash users
$ source <(arkade completion zsh) # for zsh users
Additionally, you may want to output the completion to a file and source in your .bashrc
`,
Example: completionCmd,
SilenceUsage: true,
ValidArgs: []string{"bash", "zsh"},
}
completion.RunE = func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
fmt.Print(completionCmd)
return nil
}
if len(args) != 1 {
return fmt.Errorf(completionCmd)
}
switch args[0] {
case "bash":
cmd.Root().GenBashCompletion(os.Stdout)
case "zsh":
runCompletionZsh(cmd, os.Stdout)
case "fish":
cmd.Root().GenFishCompletion(os.Stdout, true)
case "powershell":
cmd.Root().GenPowerShellCompletion(os.Stdout)
default:
return fmt.Errorf("shell completion not supported for shell: %s", args[0])
}
return nil
}
return completion
}
func runCompletionZsh(cmd *cobra.Command, out io.Writer) {
var zshCompdef = "\ncompdef _arkade arkade\n"
rootCmd(cmd).GenZshCompletion(out)
io.WriteString(out, zshCompdef)
}
func rootCmd(cmd *cobra.Command) *cobra.Command {
parent := cmd
for parent.HasParent() {
parent = parent.Parent()
}
return parent
}