From 5c24ed7d2fcacabfaa979181aed956d8001a5ffb Mon Sep 17 00:00:00 2001 From: Dipankar Das <65275144+dipankardas011@users.noreply.github.com> Date: Mon, 5 May 2025 21:32:38 +0530 Subject: [PATCH] feat(completion): add shell completion support Introduce shell completion support for bash, zsh, and fish shells. This includes a new `completion` command that generates the necessary scripts for each shell. Signed-off-by: Dipankar Das <65275144+dipankardas011@users.noreply.github.com> --- cmd/completion.go | 54 +++++++++++++++++++++++++++++++++++++++++++++++ cmd/handler.go | 1 + 2 files changed, 55 insertions(+) create mode 100644 cmd/completion.go diff --git a/cmd/completion.go b/cmd/completion.go new file mode 100644 index 0000000..025110a --- /dev/null +++ b/cmd/completion.go @@ -0,0 +1,54 @@ +package cmd + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" +) + +func (k *KsctlCommand) ShellCompletion() *cobra.Command { + cmd := &cobra.Command{ + Use: "completion [bash|zsh|fish]", + Short: "Generate shell completion scripts", + Long: `To load completions: + +Bash: + + $ source <(ksctl completion bash) + + # To load completions for each session, execute once: + # Linux: + $ ksctl completion bash > /etc/bash_completion.d/ksctl + # macOS: + $ ksctl completion bash > /usr/local/etc/bash_completion.d/ksctl + +Zsh: + + $ echo "autoload -U compinit; compinit" >> ~/.zshrc + $ ksctl completion zsh > "${fpath[1]}/_ksctl" + +Fish: + + $ ksctl completion fish | source + + # To load completions for each session, execute once: + $ ksctl completion fish > ~/.config/fish/completions/ksctl.fish +`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + switch args[0] { + case "bash": + return cmd.Root().GenBashCompletion(os.Stdout) + case "zsh": + return cmd.Root().GenZshCompletion(os.Stdout) + case "fish": + return cmd.Root().GenFishCompletion(os.Stdout, true) + default: + return fmt.Errorf("unsupported shell: %s", args[0]) + } + }, + } + + return cmd +} diff --git a/cmd/handler.go b/cmd/handler.go index d7f4ea5..1794729 100644 --- a/cmd/handler.go +++ b/cmd/handler.go @@ -26,6 +26,7 @@ func (k *KsctlCommand) CommandMapping() error { c, k.Version(), k.SelfUpdate(), + k.ShellCompletion(), cr, ) cli.RegisterCommand(