67 lines
1.2 KiB
Go
67 lines
1.2 KiB
Go
|
package cmd
|
||
|
|
||
|
import "go.fifitido.net/cmd/flags"
|
||
|
|
||
|
type Command struct {
|
||
|
Name string
|
||
|
ShortDescription string
|
||
|
LongDescription string
|
||
|
Aliases []string
|
||
|
Arguments []*Argument
|
||
|
Flags []flags.Flag
|
||
|
Subcommands []*Command
|
||
|
Run func(args []string)
|
||
|
RunE func(args []string) error
|
||
|
isRoot bool
|
||
|
}
|
||
|
|
||
|
func NewRoot(options ...Option) *Command {
|
||
|
cmd := &Command{isRoot: true}
|
||
|
cmd.ApplyOptions(options...)
|
||
|
return cmd
|
||
|
}
|
||
|
|
||
|
func New(name string, options ...Option) *Command {
|
||
|
cmd := &Command{Name: name}
|
||
|
cmd.ApplyOptions(options...)
|
||
|
return cmd
|
||
|
}
|
||
|
|
||
|
func (c *Command) ApplyOptions(options ...Option) {
|
||
|
for _, option := range options {
|
||
|
option(c)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (c *Command) Execute(args []string) {
|
||
|
if len(args) == 0 {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
for _, subcommand := range c.Subcommands {
|
||
|
if subcommand.Name == args[0] {
|
||
|
subcommand.Execute(args[1:])
|
||
|
return
|
||
|
}
|
||
|
|
||
|
for _, alias := range subcommand.Aliases {
|
||
|
if alias == args[0] {
|
||
|
subcommand.Execute(args[1:])
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if c.Run != nil {
|
||
|
c.Run(args)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if c.RunE != nil {
|
||
|
if err := c.RunE(args); err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
return
|
||
|
}
|
||
|
}
|