Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add completion subcommand #75

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
Expand Down Expand Up @@ -350,6 +351,38 @@ already exist.
RunE: updateRun,
}

var completionCmd = &cobra.Command{
Use: "completion SHELL",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("requires 1 arg, found %d", len(args))
}
return cobra.OnlyValidArgs(cmd, args)
},
ValidArgs: []string{"bash", "zsh"},
Short: "Outputs shell completion for the given shell (bash or zsh)",
Long: strings.Trim(
`Outputs shell completion for the given shell (bash or zsh)

This depends on the bash-completion package:

# OS X:
brew install bash-completion

# Ubuntu:
apt-get install bash-completion

Zsh users may also put the file somewhere on their $fpath,
e.g. /usr/local/share/zsh/site-functions
`, "\n"),
Example: strings.Trim(`
# Enable completion in your current shell
source <(berglas completion bash) # for bash users
source <(berglas completion zsh) # for zsh users
`, "\n"),
Run: completionRun,
}

func main() {
rootCmd.SetVersionTemplate(`{{printf "%s\n" .Version}}`)

Expand Down Expand Up @@ -419,6 +452,8 @@ func main() {
updateCmd.Flags().StringVarP(&key, "key", "k", "",
"KMS key to use for re-encryption")

rootCmd.AddCommand(completionCmd)

if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(stderr, "%s\n", err)
if terr, ok := err.(*exitError); ok {
Expand Down Expand Up @@ -855,6 +890,17 @@ func updateRun(_ *cobra.Command, args []string) error {
return nil
}

func completionRun(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
rootCmd.GenBashCompletion(os.Stdout)
case "zsh":
rootCmd.GenZshCompletion(os.Stdout)
// enable the `source <(berglas completion SHELL)` pattern for zsh
io.WriteString(os.Stdout, "compdef _berglas berglas\n")
}
}

// exitError is a typed error to return.
type exitError struct {
err error
Expand Down