cobra.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/moby/term"
  5. "github.com/spf13/cobra"
  6. )
  7. // SetupRootCommand sets default usage, help, and error handling for the
  8. // root command.
  9. func SetupRootCommand(rootCmd *cobra.Command) {
  10. cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages)
  11. rootCmd.SetUsageTemplate(usageTemplate)
  12. rootCmd.SetHelpTemplate(helpTemplate)
  13. rootCmd.SetFlagErrorFunc(FlagErrorFunc)
  14. rootCmd.SetVersionTemplate("Docker version {{.Version}}\n")
  15. rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
  16. rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help")
  17. }
  18. // FlagErrorFunc prints an error message which matches the format of the
  19. // docker/docker/cli error messages
  20. func FlagErrorFunc(cmd *cobra.Command, err error) error {
  21. if err == nil {
  22. return nil
  23. }
  24. usage := ""
  25. if cmd.HasSubCommands() {
  26. usage = "\n\n" + cmd.UsageString()
  27. }
  28. return StatusError{
  29. Status: fmt.Sprintf("%s\nSee '%s --help'.%s", err, cmd.CommandPath(), usage),
  30. StatusCode: 125,
  31. }
  32. }
  33. func wrappedFlagUsages(cmd *cobra.Command) string {
  34. width := 80
  35. if ws, err := term.GetWinsize(0); err == nil {
  36. width = int(ws.Width)
  37. }
  38. return cmd.Flags().FlagUsagesWrapped(width - 1)
  39. }
  40. const usageTemplate = `Usage: {{.UseLine}}
  41. {{ .Short | trim }}
  42. {{- if gt .Aliases 0}}
  43. Aliases:
  44. {{.NameAndAliases}}
  45. {{- end}}
  46. {{- if .HasExample}}
  47. Examples:
  48. {{ .Example }}
  49. {{- end}}
  50. {{- if .HasAvailableFlags}}
  51. Options:
  52. {{ wrappedFlagUsages . | trimRightSpace}}
  53. {{- end}}
  54. `
  55. const helpTemplate = `
  56. {{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`