diff --git a/cmd/completion.go b/cmd/completion.go new file mode 100644 index 000000000..b238d38a0 --- /dev/null +++ b/cmd/completion.go @@ -0,0 +1,34 @@ +package cmd + +import ( + "github.com/spf13/cobra" +) + +type completionCmd struct { + cmd *cobra.Command +} + +func newCompletionCmd() *completionCmd { + var root = &completionCmd{} + var cmd = &cobra.Command{ + Use: "completion", + Short: "Print shell autocompletion scripts for goreleaser for bash and zsh", + SilenceUsage: true, + ValidArgs: []string{"bash", "zsh"}, + Args: cobra.ExactValidArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + var err error + switch args[0] { + case "bash": + err = cmd.Root().GenBashCompletion(cmd.OutOrStdout()) + case "zsh": + err = cmd.Root().GenZshCompletion(cmd.OutOrStdout()) + } + + return err + }, + } + + root.cmd = cmd + return root +} diff --git a/cmd/completion_test.go b/cmd/completion_test.go new file mode 100644 index 000000000..33dfe11b4 --- /dev/null +++ b/cmd/completion_test.go @@ -0,0 +1,23 @@ +package cmd + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCompletionGeneration(t *testing.T) { + for _, shell := range []string{"bash", "zsh"} { + completionCmd := newCompletionCmd().cmd + stdout := bytes.NewBufferString("") + stderr := bytes.NewBufferString("") + completionCmd.SetOut(stdout) + completionCmd.SetErr(stderr) + completionCmd.SetArgs([]string{shell}) + err := completionCmd.Execute() + require.NoError(t, err, shell+" arg experienced error with goreleaser completion:\n"+stderr.String()) + require.Equal(t, "", stderr.String(), shell+" arg experienced error with goreleaser completion:\n"+stderr.String()) + require.NotEmpty(t, stdout.String(), shell+" arg reported nothing to stdout with goreleaser completion") + } +} diff --git a/cmd/root.go b/cmd/root.go index d258aa716..f7adcb256 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -74,6 +74,7 @@ func newRootCmd(version string, exit func(int)) *rootCmd { newReleaseCmd().cmd, newCheckCmd().cmd, newInitCmd().cmd, + newCompletionCmd().cmd, ) root.cmd = cmd