59 lines
1013 B
Go
59 lines
1013 B
Go
package command
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
ErrInvalidArg = errors.New("invalid argument")
|
|
)
|
|
|
|
type Command interface {
|
|
Do(args []string) (bool, error)
|
|
}
|
|
|
|
type CLI struct {
|
|
Commands []Command
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|