github.com/esnet/gdg@v0.6.1-0.20240412190737-6b6eba9c14d8/cli/support/simple.go (about) 1 package support 2 3 import ( 4 "context" 5 "github.com/bep/simplecobra" 6 "github.com/spf13/cobra" 7 ) 8 9 // SimpleCommand wraps a simple command 10 type SimpleCommand struct { 11 use string 12 NameP string 13 Short string 14 Long string 15 RunFunc func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *RootCommand, args []string) error 16 WithCFunc func(cmd *cobra.Command, r *RootCommand) 17 InitCFunc func(cd *simplecobra.Commandeer, r *RootCommand) error 18 19 CommandsList []simplecobra.Commander 20 21 RootCmd *RootCommand 22 } 23 24 // Commands is a list of subcommands 25 func (c *SimpleCommand) Commands() []simplecobra.Commander { 26 return c.CommandsList 27 } 28 29 // SetName Function allows name to be set 30 func (c *SimpleCommand) SetName(name string) { 31 c.NameP = name 32 } 33 34 // Name returns function Name 35 func (c *SimpleCommand) Name() string { 36 return c.NameP 37 } 38 39 // Run executes cli command 40 func (c *SimpleCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { 41 if c.RunFunc == nil { 42 return nil 43 } 44 return c.RunFunc(ctx, cd, c.RootCmd, args) 45 } 46 47 // Init initializes the SimpleCommand 48 func (c *SimpleCommand) Init(cd *simplecobra.Commandeer) error { 49 c.RootCmd = cd.Root.Command.(*RootCommand) 50 cmd := cd.CobraCommand 51 cmd.Short = c.Short 52 cmd.Long = c.Long 53 if c.use != "" { 54 cmd.Use = c.use 55 } 56 if c.WithCFunc != nil { 57 c.WithCFunc(cmd, c.RootCmd) 58 } 59 return nil 60 } 61 62 // PreRun executed prior to cli command execution 63 func (c *SimpleCommand) PreRun(cd, runner *simplecobra.Commandeer) error { 64 if c.InitCFunc != nil { 65 return c.InitCFunc(cd, c.RootCmd) 66 } 67 return nil 68 }