cmd.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package app
  2. import (
  3. "fmt"
  4. "github.com/fatih/color"
  5. "github.com/spf13/cobra"
  6. "os"
  7. )
  8. // Command 应用子命令结构
  9. type Command struct {
  10. usage string
  11. desc string
  12. options CommandLineOptions
  13. commands []*Command
  14. runFunc RunCommandFunc
  15. }
  16. type RunCommandFunc func(args []string) error
  17. type CommandOption func(*Command)
  18. func WithCommandOptions(opt CommandLineOptions) CommandOption {
  19. return func(command *Command) {
  20. command.options = opt
  21. }
  22. }
  23. func WithCommandRunFunc(run RunCommandFunc) CommandOption {
  24. return func(c *Command) {
  25. c.runFunc = run
  26. }
  27. }
  28. func NewCommand(usage, desc string, opts ...CommandOption) *Command {
  29. c := &Command{
  30. usage: usage,
  31. desc: desc,
  32. }
  33. for _, o := range opts {
  34. o(c)
  35. }
  36. return c
  37. }
  38. // AddCommand 当前命令添加字命令
  39. func (c *Command) AddCommand(cmd *Command) {
  40. c.commands = append(c.commands, cmd)
  41. }
  42. // AddCommands 当前命令添加字命令
  43. func (c *Command) AddCommands(cmds ...*Command) {
  44. c.commands = append(c.commands, cmds...)
  45. }
  46. func (c *Command) cobraCommand() *cobra.Command {
  47. cmd := &cobra.Command{
  48. Use: c.usage,
  49. Short: c.desc,
  50. }
  51. cmd.SetOut(os.Stdout)
  52. cmd.Flags().SortFlags = false
  53. if len(c.commands) > 0 {
  54. for _, command := range c.commands {
  55. cmd.AddCommand(command.cobraCommand())
  56. }
  57. }
  58. if c.runFunc != nil {
  59. cmd.Run = c.runCommand
  60. }
  61. if c.options != nil {
  62. for _, f := range c.options.Flags().FlagSets {
  63. cmd.Flags().AddFlagSet(f)
  64. }
  65. // c.comopts.AddFlags(cmd.Flags())
  66. }
  67. addHelpCommandFlag(c.usage, cmd.Flags())
  68. return cmd
  69. }
  70. func (c *Command) runCommand(cmd *cobra.Command, args []string) {
  71. if c.runFunc != nil {
  72. if err := c.runFunc(args); err != nil {
  73. fmt.Printf("%v %v\n", color.RedString("Error:"), err)
  74. os.Exit(1)
  75. }
  76. }
  77. }