completion.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package main
  2. import (
  3. "os"
  4. "github.com/spf13/cobra"
  5. )
  6. func NewCompletionCmd() *cobra.Command {
  7. var completionCmd = &cobra.Command{
  8. Use: "completion [bash|zsh|powershell|fish]",
  9. Short: "Generate completion script",
  10. Long: `To load completions:
  11. ### Bash:
  12. ` + "```shell" + `
  13. $ source <(cscli completion bash)
  14. # To load completions for each session, execute once:
  15. # Linux:
  16. $ cscli completion bash | sudo tee /etc/bash_completion.d/cscli
  17. $ source ~/.bashrc
  18. # macOS:
  19. $ cscli completion bash | sudo tee /usr/local/etc/bash_completion.d/cscli
  20. # Troubleshoot:
  21. If you have this error (bash: _get_comp_words_by_ref: command not found), it seems that you need "bash-completion" dependency :
  22. * Install bash-completion package
  23. $ source /etc/profile
  24. $ source <(cscli completion bash)
  25. ` + "```" + `
  26. ### Zsh:
  27. ` + "```shell" + `
  28. # If shell completion is not already enabled in your environment,
  29. # you will need to enable it. You can execute the following once:
  30. $ echo "autoload -U compinit; compinit" >> ~/.zshrc
  31. # To load completions for each session, execute once:
  32. $ cscli completion zsh > "${fpath[1]}/_cscli"
  33. # You will need to start a new shell for this setup to take effect.
  34. ### fish:
  35. ` + "```shell" + `
  36. $ cscli completion fish | source
  37. # To load completions for each session, execute once:
  38. $ cscli completion fish > ~/.config/fish/completions/cscli.fish
  39. ` + "```" + `
  40. ### PowerShell:
  41. ` + "```powershell" + `
  42. PS> cscli completion powershell | Out-String | Invoke-Expression
  43. # To load completions for every new session, run:
  44. PS> cscli completion powershell > cscli.ps1
  45. # and source this file from your PowerShell profile.
  46. ` + "```",
  47. DisableFlagsInUseLine: true,
  48. DisableAutoGenTag: true,
  49. ValidArgs: []string{"bash", "zsh", "powershell", "fish"},
  50. Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
  51. Run: func(cmd *cobra.Command, args []string) {
  52. switch args[0] {
  53. case "bash":
  54. cmd.Root().GenBashCompletion(os.Stdout)
  55. case "zsh":
  56. cmd.Root().GenZshCompletion(os.Stdout)
  57. case "powershell":
  58. cmd.Root().GenPowerShellCompletion(os.Stdout)
  59. case "fish":
  60. cmd.Root().GenFishCompletion(os.Stdout, true)
  61. }
  62. },
  63. }
  64. return completionCmd
  65. }