planner/plan/command/command.go

70 lines
1.1 KiB
Go

package command
import (
"errors"
"fmt"
"strings"
)
type ArgSet struct {
Main []string
Flags map[string]string
}
type Command interface {
Parse(args *ArgSet) error
Do() error
}
type CLI struct {
Commands []Command
}
func (cli *CLI) Run(args []string) error {
as, err := ParseFlags(args)
if err != nil {
return err
}
for _, c := range cli.Commands {
err := c.Parse(as)
switch {
case errors.Is(err, ErrWrongCommand):
continue
case err != nil:
return err
default:
return c.Do()
}
}
return fmt.Errorf("could not find matching command")
}
func ParseFlags(args []string) (*ArgSet, error) {
flags := make(map[string]string)
main := make([]string, 0)
var inMain bool
for i := 0; i < len(args); i++ {
if strings.HasPrefix(args[i], "-") {
inMain = false
if i+1 >= len(args) {
return nil, fmt.Errorf("flag wihout value")
}
flags[strings.TrimPrefix(args[i], "-")] = args[i+1]
i++
continue
}
if !inMain && len(main) > 0 {
return nil, fmt.Errorf("two mains")
}
inMain = true
main = append(main, args[i])
}
return &ArgSet{
Main: main,
Flags: flags,
}, nil
}