...
1 package cmd
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7
8 "github.com/spf13/cobra"
9 )
10
11
12
13 func newCmdCompletion() *cobra.Command {
14 example := ` # bash <= 3.2:
15 # To load shell completion into your current shell session
16 source /dev/stdin <<< "$(linkerd completion bash)"
17
18 # bash >= 4.0:
19 source <(linkerd completion bash)
20
21 # To load shell completion for every shell session
22 # bash <= 3.2 on osx:
23 brew install bash-completion # ensure you have bash-completion 1.3+
24 linkerd completion bash > $(brew --prefix)/etc/bash_completion.d/linkerd
25
26 # bash >= 4.0 on osx:
27 brew install bash-completion@2
28 linkerd completion bash > $(brew --prefix)/etc/bash_completion.d/linkerd
29
30 # bash >= 4.0 on linux:
31 linkerd completion bash > /etc/bash_completion.d/linkerd
32
33 # You will need to start a new shell for this setup to take effect.
34
35 # zsh:
36 # If shell completion is not already enabled in your environment you will need
37 # to enable it. You can execute the following once:
38
39 echo "autoload -U compinit && compinit" >> ~/.zshrc
40
41 # create a linkerd 'plugins' folder and add it to your $fpath
42 mkdir $ZSH/plugins/linkerd && echo "fpath=($ZSH/plugins/linkerd $fpath)" >> ~/.zshrc
43
44 # To load completions for each session, execute once:
45 linkerd completion zsh > "${fpath[1]}/_linkerd" && exec $SHELL
46
47 # You will need to start a new shell for this setup to take effect.
48
49 # fish:
50 linkerd completion fish | source
51
52 # To load fish shell completions for each session, execute once:
53 linkerd completion fish > ~/.config/fish/completions/linkerd.fish`
54
55 cmd := &cobra.Command{
56 Use: "completion [bash|zsh|fish]",
57 Short: "Output shell completion code for the specified shell (bash, zsh or fish)",
58 Long: "Output shell completion code for the specified shell (bash, zsh or fish).",
59 Example: example,
60 Args: cobra.ExactArgs(1),
61 ValidArgs: []string{"bash", "zsh", "fish"},
62 RunE: func(cmd *cobra.Command, args []string) error {
63 out, err := getCompletion(args[0], cmd.Parent())
64 if err != nil {
65 return err
66 }
67
68 fmt.Print(out)
69 return nil
70 },
71 }
72
73 return cmd
74 }
75
76
77 func getCompletion(sh string, parent *cobra.Command) (string, error) {
78 var err error
79 var buf bytes.Buffer
80
81 switch sh {
82 case "bash":
83 err = parent.GenBashCompletion(&buf)
84 case "zsh":
85 err = parent.GenZshCompletion(&buf)
86 case "fish":
87 err = parent.GenFishCompletion(&buf, true)
88
89 default:
90 err = errors.New("unsupported shell type (must be bash, zsh or fish): " + sh)
91 }
92
93 if err != nil {
94 return "", err
95 }
96
97 return buf.String(), nil
98 }
99
View as plain text