github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/client/cli/cmd/completion.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/spf13/cobra"
     8  
     9  	"github.com/telepresenceio/telepresence/v2/pkg/errcat"
    10  )
    11  
    12  func addCompletion(rootCmd *cobra.Command) {
    13  	cmd := cobra.Command{
    14  		Use:   "completion",
    15  		Short: "Generate a shell completion script",
    16  		ValidArgs: []string{
    17  			"bash",
    18  			"zsh",
    19  			"powershell",
    20  			"fish",
    21  		},
    22  		ArgAliases: []string{"ps"},
    23  		RunE: func(cmd *cobra.Command, args []string) error {
    24  			var shell string
    25  			if 0 < len(args) {
    26  				shell = args[0]
    27  			}
    28  
    29  			var err error
    30  			switch shell {
    31  			case "zsh":
    32  				err = rootCmd.GenZshCompletionNoDesc(os.Stdout)
    33  			case "bash":
    34  				err = rootCmd.GenBashCompletionV2(os.Stdout, false)
    35  			case "fish":
    36  				err = rootCmd.GenFishCompletion(os.Stdout, false)
    37  			case "ps", "powershell":
    38  				err = rootCmd.GenPowerShellCompletion(os.Stdout)
    39  			case "":
    40  				err = errcat.User.Newf("shell not specified")
    41  			}
    42  
    43  			return err
    44  		},
    45  		Long: fmt.Sprintf(`To load completions:
    46  
    47  Bash:
    48  
    49    $ source <(%[1]s completion bash)
    50  
    51    # To load completions for each session, execute once:
    52    # Linux:
    53    $ %[1]s completion bash > /etc/bash_completion.d/%[1]s
    54    # macOS:
    55    $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
    56  
    57  Zsh:
    58  
    59    # If shell completion is not already enabled in your environment,
    60    # you will need to enable it.  You can execute the following once:
    61  
    62    $ echo "autoload -U compinit; compinit" >> ~/.zshrc
    63  
    64    # To load completions for each session, execute once:
    65    $ %[1]s completion zsh > "${fpath[1]}/_%[1]s"
    66  
    67    # You will need to start a new shell for this setup to take effect.
    68  
    69  fish:
    70  
    71    $ %[1]s completion fish | source
    72  
    73    # To load completions for each session, execute once:
    74    $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
    75  
    76  PowerShell:
    77  
    78    PS> %[1]s completion powershell | Out-String | Invoke-Expression
    79  
    80    # To load completions for every new session, run:
    81    PS> %[1]s completion powershell > %[1]s.ps1
    82    # and source this file from your PowerShell profile.
    83  `, rootCmd.Name()),
    84  	}
    85  
    86  	rootCmd.AddCommand(&cmd)
    87  }