123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package app
- import (
- "dy-admin/pkg/comopts"
- "fmt"
- "github.com/fatih/color"
- "github.com/spf13/cobra"
- "os"
- )
- // Command 应用子命令结构
- type Command struct {
- usage string
- desc string
- options comopts.CommandLineOptions
- commands []*Command
- runFunc RunCommandFunc
- }
- type RunCommandFunc func(args []string) error
- type CommandOption func(*Command)
- func WithCommandOptions(opt comopts.CommandLineOptions) CommandOption {
- return func(command *Command) {
- command.options = opt
- }
- }
- func WithCommandRunFunc(run RunCommandFunc) CommandOption {
- return func(c *Command) {
- c.runFunc = run
- }
- }
- func NewCommand(usage, desc string, opts ...CommandOption) *Command {
- c := &Command{
- usage: usage,
- desc: desc,
- }
- for _, o := range opts {
- o(c)
- }
- return c
- }
- // AddCommand 当前命令添加字命令
- func (c *Command) AddCommand(cmd *Command) {
- c.commands = append(c.commands, cmd)
- }
- // AddCommands 当前命令添加字命令
- func (c *Command) AddCommands(cmds ...*Command) {
- c.commands = append(c.commands, cmds...)
- }
- func (c *Command) cobraCommand() *cobra.Command {
- cmd := &cobra.Command{
- Use: c.usage,
- Short: c.desc,
- }
- cmd.SetOut(os.Stdout)
- cmd.Flags().SortFlags = false
- if len(c.commands) > 0 {
- for _, command := range c.commands {
- cmd.AddCommand(command.cobraCommand())
- }
- }
- if c.runFunc != nil {
- cmd.Run = c.runCommand
- }
- if c.options != nil {
- for _, f := range c.options.Flags().FlagSets {
- cmd.Flags().AddFlagSet(f)
- }
- // c.comopts.AddFlags(cmd.Flags())
- }
- addHelpCommandFlag(c.usage, cmd.Flags())
- return cmd
- }
- func (c *Command) runCommand(cmd *cobra.Command, args []string) {
- if c.runFunc != nil {
- if err := c.runFunc(args); err != nil {
- fmt.Printf("%v %v\n", color.RedString("Error:"), err)
- os.Exit(1)
- }
- }
- }
|