planner/plan/command/command.go

62 lines
1.1 KiB
Go
Raw Normal View History

2024-10-29 07:22:28 +01:00
package command
2024-10-31 07:26:03 +01:00
import (
2024-11-04 09:49:41 +01:00
"errors"
"fmt"
2024-11-05 07:21:43 +01:00
"strings"
2024-10-31 07:26:03 +01:00
)
2024-10-30 07:25:05 +01:00
2024-11-04 09:49:41 +01:00
type Command interface {
2024-11-11 09:23:30 +01:00
Parse([]string, map[string]string) error
2024-11-10 15:04:14 +01:00
Do() error
2024-10-29 07:22:28 +01:00
}
type CLI struct {
2024-11-04 09:49:41 +01:00
Commands []Command
2024-10-30 07:25:05 +01:00
}
2024-11-04 09:49:41 +01:00
func (cli *CLI) Run(args []string) error {
2024-11-11 09:23:30 +01:00
main, flags, err := ParseFlags(args)
2024-11-10 15:04:14 +01:00
if err != nil {
return err
}
2024-11-04 09:49:41 +01:00
for _, c := range cli.Commands {
2024-11-11 09:23:30 +01:00
err := c.Parse(main, flags)
2024-11-06 07:29:29 +01:00
switch {
case errors.Is(err, ErrWrongCommand):
continue
case err != nil:
2024-11-04 09:49:41 +01:00
return err
2024-11-06 07:29:29 +01:00
default:
2024-11-10 15:04:14 +01:00
return c.Do()
2024-10-31 07:26:03 +01:00
}
}
2024-11-05 07:21:43 +01:00
return fmt.Errorf("could not find matching command")
}
2024-11-11 09:23:30 +01:00
func ParseFlags(args []string) ([]string, map[string]string, error) {
2024-11-05 07:21:43 +01:00
flags := make(map[string]string)
2024-11-06 07:29:29 +01:00
main := make([]string, 0)
var inMain bool
2024-11-05 07:21:43 +01:00
for i := 0; i < len(args); i++ {
if strings.HasPrefix(args[i], "-") {
2024-11-06 07:29:29 +01:00
inMain = false
2024-11-05 07:21:43 +01:00
if i+1 >= len(args) {
2024-11-11 09:23:30 +01:00
return nil, nil, fmt.Errorf("flag wihout value")
2024-11-05 07:21:43 +01:00
}
flags[strings.TrimPrefix(args[i], "-")] = args[i+1]
i++
continue
}
2024-11-06 07:29:29 +01:00
if !inMain && len(main) > 0 {
2024-11-11 09:23:30 +01:00
return nil, nil, fmt.Errorf("two mains")
2024-11-05 07:21:43 +01:00
}
2024-11-06 07:29:29 +01:00
inMain = true
main = append(main, args[i])
2024-11-05 07:21:43 +01:00
}
2024-11-11 09:23:30 +01:00
return main, flags, nil
2024-10-30 07:25:05 +01:00
}