cmd/httptap/cmd/completion.go

package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

func newCompletionCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "completion [bash|zsh|fish|powershell]",
		Short: "Output a shell completion script",
		Long: `Emit a shell completion script.

Source it from your shell init file, e.g.:

  # zsh
  httptap completion zsh > "${fpath[1]}/_httptap"

  # bash (Linux)
  httptap completion bash > /etc/bash_completion.d/httptap

  # fish
  httptap completion fish > ~/.config/fish/completions/httptap.fish`,
		DisableFlagsInUseLine: true,
		ValidArgs:             []string{"bash", "zsh", "fish", "powershell"},
		Args:                  cobra.ExactValidArgs(1),
		RunE: func(c *cobra.Command, args []string) error {
			root := c.Root()
			switch args[0] {
			case "bash":
				return root.GenBashCompletionV2(os.Stdout, true)
			case "zsh":
				return root.GenZshCompletion(os.Stdout)
			case "fish":
				return root.GenFishCompletion(os.Stdout, true)
			case "powershell":
				return root.GenPowerShellCompletionWithDesc(os.Stdout)
			default:
				return fmt.Errorf("unsupported shell %q", args[0])
			}
		},
	}
	return cmd
}

// CompletionHint is a bit of text shown by the help banner when the user
// has not yet installed completions. It is shared with the doctor check.
func CompletionHint() string {
	return "run `httptap completion <shell>` to install tab completion"
}