planner/plan/command/command.go

59 lines
1013 B
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
var (
ErrInvalidArg = errors.New("invalid argument")
2024-10-30 07:25:05 +01:00
)
2024-11-04 09:49:41 +01:00
type Command interface {
Do(args []string) (bool, 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 {
for _, c := range cli.Commands {
worked, err := c.Do(args)
if err != nil {
return err
}
if worked {
return nil
2024-10-31 07:26:03 +01:00
}
}
2024-11-05 07:21:43 +01:00
return fmt.Errorf("could not find matching command")
}
func ParseArgs(args []string) (string, map[string]string, error) {
flags := make(map[string]string)
rem := make([]string, 0)
var inRem bool
for i := 0; i < len(args); i++ {
if strings.HasPrefix(args[i], "-") {
inRem = false
if i+1 >= len(args) {
return "", nil, fmt.Errorf("flag wihout value")
}
flags[strings.TrimPrefix(args[i], "-")] = args[i+1]
i++
continue
}
if !inRem && len(rem) > 0 {
return "", nil, fmt.Errorf("two rems")
}
inRem = true
rem = append(rem, args[i])
}
return strings.Join(rem, " "), flags, nil
2024-10-30 07:25:05 +01:00
}