cmd/command.go

100 lines
1.6 KiB
Go
Raw Normal View History

package cmd
2023-11-10 13:17:01 -05:00
import (
"fmt"
2023-11-10 13:17:01 -05:00
"os"
"path/filepath"
2023-11-11 19:28:58 -05:00
"go.fifitido.net/cmd/opts"
2023-11-10 13:17:01 -05:00
)
type Command struct {
name string
shortDescription string
longDescription string
2023-11-10 13:17:01 -05:00
aliases []string
arguments []*Argument
2023-11-11 19:28:58 -05:00
opts opts.Set
subcommands Set
2023-11-10 13:17:01 -05:00
parent *Command
run func(args []string)
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)
}
}
2023-11-11 19:17:46 -05:00
func (c *Command) Root() *Command {
if c.isRoot {
return c
}
return c.parent.Root()
}
2023-11-10 13:17:01 -05:00
func (c *Command) CommandPath() string {
if c.parent == nil {
return filepath.Base(os.Args[0])
}
return c.parent.CommandPath() + " " + c.name
2023-11-10 13:17:01 -05:00
}
func (c *Command) CanRun() bool {
return c.run != nil
}
func (c *Command) Run(args []string) {
c.run(args)
}
func (c *Command) Execute(args []string) {
2023-11-10 00:58:09 -05:00
if c.isRoot {
args = args[1:]
}
2023-11-11 21:29:56 -05:00
parser := opts.NewParser(args, c.opts, false)
restArgs, err := parser.Parse()
2023-11-11 20:49:38 -05:00
if err != nil {
2023-11-11 21:29:56 -05:00
fmt.Println(err.Error())
2023-11-11 20:49:38 -05:00
c.ShowHelp()
2023-11-11 21:29:56 -05:00
os.Exit(1)
2023-11-11 20:49:38 -05:00
}
if len(restArgs) > 0 {
sc, ok := c.subcommands.Get(restArgs[0])
if ok {
2023-11-11 20:49:38 -05:00
sc.Execute(restArgs[1:])
return
}
2023-11-11 20:49:38 -05:00
}
2023-11-10 13:17:01 -05:00
2023-11-11 20:49:38 -05:00
helpOpt, ok := opts.Globals().GetBool("help")
if ok && helpOpt.Value() {
c.ShowHelp()
return
}
2023-11-10 13:17:01 -05:00
if c.CanRun() {
2023-11-11 20:49:38 -05:00
c.Run(restArgs)
return
}
2023-11-10 13:17:01 -05:00
c.ShowHelp()
}