Skip to content

Commit cdd4951

Browse files
authored
Merge pull request cli#39 from github/completion
Add `completion` script
2 parents da334e2 + 4f03370 commit cdd4951

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

command/completion.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package command
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/spf13/cobra"
7+
)
8+
9+
func init() {
10+
RootCmd.AddCommand(completionCmd)
11+
completionCmd.Flags().StringP("shell", "s", "bash", "The type of shell")
12+
}
13+
14+
var completionCmd = &cobra.Command{
15+
Use: "completion",
16+
Hidden: true,
17+
Short: "Generates completion scripts",
18+
Long: `To enable completion in your shell, run:
19+
20+
eval "$(gh completion)"
21+
22+
You can add that to your '~/.bash_profile' to enable completion whenever you
23+
start a new shell.
24+
25+
When installing with Homebrew, see https://docs.brew.sh/Shell-Completion
26+
`,
27+
RunE: func(cmd *cobra.Command, args []string) error {
28+
shellType, err := cmd.Flags().GetString("shell")
29+
if err != nil {
30+
return err
31+
}
32+
33+
switch shellType {
34+
case "bash":
35+
RootCmd.GenBashCompletion(cmd.OutOrStdout())
36+
case "zsh":
37+
RootCmd.GenZshCompletion(cmd.OutOrStdout())
38+
default:
39+
return fmt.Errorf("unsupported shell type: %s", shellType)
40+
}
41+
return nil
42+
},
43+
}

command/completion_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package command
2+
3+
import (
4+
"bytes"
5+
"strings"
6+
"testing"
7+
)
8+
9+
func TestCompletion_bash(t *testing.T) {
10+
out := bytes.Buffer{}
11+
completionCmd.SetOut(&out)
12+
13+
RootCmd.SetArgs([]string{"completion"})
14+
_, err := RootCmd.ExecuteC()
15+
if err != nil {
16+
t.Fatal(err)
17+
}
18+
19+
outStr := out.String()
20+
if !strings.Contains(outStr, "complete -o default -F __start_gh gh") {
21+
t.Errorf("problem in bash completion:\n%s", outStr)
22+
}
23+
}
24+
25+
func TestCompletion_zsh(t *testing.T) {
26+
out := bytes.Buffer{}
27+
completionCmd.SetOut(&out)
28+
29+
RootCmd.SetArgs([]string{"completion", "-s", "zsh"})
30+
_, err := RootCmd.ExecuteC()
31+
if err != nil {
32+
t.Fatal(err)
33+
}
34+
35+
outStr := out.String()
36+
if !strings.Contains(outStr, "#compdef _gh gh") {
37+
t.Errorf("problem in zsh completion:\n%s", outStr)
38+
}
39+
}
40+
41+
func TestCompletion_unsupported(t *testing.T) {
42+
out := bytes.Buffer{}
43+
completionCmd.SetOut(&out)
44+
45+
RootCmd.SetArgs([]string{"completion", "-s", "fish"})
46+
_, err := RootCmd.ExecuteC()
47+
if err == nil || err.Error() != "unsupported shell type: fish" {
48+
t.Fatal(err)
49+
}
50+
}

0 commit comments

Comments
 (0)