2
0

Добавлена возможность захвата параметров CLI.
All checks were successful
test / test (push) Successful in 58s

This commit is contained in:
Алексей Бадяев 2024-10-22 23:04:50 +07:00
parent 207759e9e4
commit 9c66b33f45
Signed by: alexey
GPG Key ID: 686FBC1363E4AFAE
2 changed files with 40 additions and 4 deletions

37
cli.go
View File

@ -21,6 +21,7 @@ import (
"io"
"reflect"
"strconv"
"strings"
"time"
"unsafe"
)
@ -190,8 +191,8 @@ func NewCliWith(
// Init analyzes the given structure interface, extracts cli definitions from
// its tag and installs command flagset by flag APIs. The interface must be a
// structure pointer, otherwise will return an error
func (c *Command) Init(i interface{}) error {
ptrRef := reflect.ValueOf(i)
func (c *Command) Init(in interface{}) error {
ptrRef := reflect.ValueOf(in)
if ptrRef.IsNil() || ptrRef.Kind() != reflect.Ptr {
return fmt.Errorf("%w: %s",
@ -207,6 +208,38 @@ func (c *Command) Init(i interface{}) error {
return c.parseValue(valueOfStruct)
}
// Capture filter config args and return rest args
func (c *Command) Capture(args []string) []string {
var (
result []string
expectValue bool
)
for _, arg := range args {
if !strings.HasPrefix(arg, "-") {
if expectValue {
c.Args = append(c.Args, arg)
expectValue = false
} else {
result = append(result, arg)
}
continue
}
name := strings.TrimPrefix(strings.TrimPrefix(arg, "-"), "-")
if c.FlagSet.Lookup(name) != nil {
c.Args = append(c.Args, arg)
expectValue = true
} else {
result = append(result, arg)
}
}
return result
}
// parseValue parses a reflect.Value object and extracts cli definitions
func (c *Command) parseValue(value reflect.Value) error {
var err error

View File

@ -275,6 +275,9 @@ func TestDuration(t *testing.T) {
cmd := NewCLI("Config")
assert.NoError(cmd.Init(&conf), "init config command")
args := []string{"--interval", "5s"}
assert.NoError(cmd.Parse(args))
args := []string{"-v", "--interval", "5s", "help"}
assert.ElementsMatch([]string{"-v", "help"}, cmd.Capture(args))
assert.ElementsMatch([]string{"--interval", "5s"}, cmd.Args)
assert.NoError(cmd.Parse(cmd.Args))
}