github.com/criteo/command-launcher@v0.0.0-20230407142452-fb616f546e98/cmd/completion.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/criteo/command-launcher/cmd/completion" 8 "github.com/criteo/command-launcher/internal/context" 9 "github.com/spf13/cobra" 10 ) 11 12 func AddCompletionCmd(rootCmd *cobra.Command, appCtx context.LauncherContext) { 13 var completionCmd = &cobra.Command{ 14 Use: "completion [bash|zsh|fish|powershell]", 15 Short: "Generate completion script", 16 Long: fmt.Sprintf(`To load completions: 17 18 Bash: 19 20 $ source <(%[1]s completion bash) 21 22 # To load completions for each session, execute once: 23 # Linux: 24 $ %[1]s completion bash > /etc/bash_completion.d/%[1]s 25 # macOS: 26 $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s 27 28 Zsh: 29 30 # If shell completion is not already enabled in your environment, 31 # you will need to enable it. You can execute the following once: 32 33 $ echo "autoload -U compinit; compinit" >> ~/.zshrc 34 35 # To load completions for each session, execute once: 36 $ %[1]s completion zsh > "${fpath[1]}/_%[1]s" 37 38 # You will need to start a new shell for this setup to take effect. 39 40 fish: 41 42 $ %[1]s completion fish | source 43 44 # To load completions for each session, execute once: 45 $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish 46 47 PowerShell: 48 49 PS> %[1]s completion powershell | Out-String | Invoke-Expression 50 51 # To load completions for every new session, run: 52 PS> %[1]s completion powershell > %[1]s.ps1 53 # and source this file from your PowerShell profile. 54 `, appCtx.AppName()), 55 DisableFlagsInUseLine: true, 56 ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, 57 //Args: cobra.ExactValidArgs(1), 58 Run: func(cmd *cobra.Command, args []string) { 59 if len(args) > 0 { 60 switch args[0] { 61 case "bash": 62 // use our own fork of bash completion, it contains a slightly change 63 // to ensure bash performance on windows 64 // NOTE: bash on windows has low performance to process the completion descriptions 65 // we disable the completion description for bash 66 completion.GenBashCompletionV2(os.Stdout, appCtx.AppName(), false) 67 case "zsh": 68 cmd.Root().GenZshCompletion(os.Stdout) 69 case "fish": 70 cmd.Root().GenFishCompletion(os.Stdout, true) 71 case "powershell": 72 cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) 73 } 74 } else { 75 cmd.Help() 76 } 77 }, 78 } 79 80 rootCmd.AddCommand(completionCmd) 81 }