From de8dcff803e68bd2fea7ecf949aace7c665c7025 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Thu, 11 Jun 2020 18:27:01 +1000 Subject: [PATCH] Added shell completions --- cmd/root.go | 1 + cmd/shell_completion.go | 46 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 cmd/shell_completion.go diff --git a/cmd/root.go b/cmd/root.go index 95aae99b..d590a387 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -54,6 +54,7 @@ func New() *cobra.Command { createDeleteCmd(), createNewCmd(), createMergeCmd(), + createBashCompletionCmd(rootCmd), ) return rootCmd } diff --git a/cmd/shell_completion.go b/cmd/shell_completion.go new file mode 100644 index 00000000..565e1eaf --- /dev/null +++ b/cmd/shell_completion.go @@ -0,0 +1,46 @@ +package cmd + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" +) + +var shellVariant = "bash" + +func createBashCompletionCmd(rootCmd *cobra.Command) *cobra.Command { + var completionCmd = &cobra.Command{ + Use: "shell-completion", + Short: "Generates shell completion scripts", + Long: `Example usage (for bash): to load completion run + + . <(yq bash-completion) + + To configure your bash shell to load completions for each session add to your bashrc + + # ~/.bashrc or ~/.profile + . <(yq bash-completion) + `, + RunE: func(cmd *cobra.Command, args []string) error { + switch shellVariant { + case "bash", "": + rootCmd.GenBashCompletion(os.Stdout) + return nil + case "zsh": + rootCmd.GenZshCompletion(os.Stdout) + return nil + case "fish": + rootCmd.GenFishCompletion(os.Stdout, true) + return nil + case "powershell": + rootCmd.GenPowerShellCompletion(os.Stdout) + return nil + default: + return fmt.Errorf("Unknown variant %v", shellVariant) + } + }, + } + completionCmd.PersistentFlags().StringVarP(&shellVariant, "variation", "V", "", "shell variation: bash (default), zsh, fish, powershell") + return completionCmd +}