2
0

Добавлена обработка аргументов командной строки типа time.Duration
All checks were successful
test / test (push) Successful in 57s

This commit is contained in:
Алексей Бадяев 2024-10-22 21:46:13 +07:00
parent e06195bc14
commit 207759e9e4
Signed by: alexey
GPG Key ID: 686FBC1363E4AFAE
2 changed files with 24 additions and 0 deletions

10
cli.go
View File

@ -21,6 +21,7 @@ import (
"io"
"reflect"
"strconv"
"time"
"unsafe"
)
@ -247,6 +248,15 @@ func (c *Command) addFlag(value reflect.Value, field reflect.StructField) error
usage, _ := field.Tag.Lookup("usage")
if value.Type().PkgPath() == "time" && value.Type().Name() == "Duration" {
c.FlagSet.DurationVar(
(*time.Duration)(unsafe.Pointer(value.UnsafeAddr())),
name, time.Duration(0), usage,
)
return nil
}
kind := value.Kind()
switch kind {
case reflect.Bool:

View File

@ -20,6 +20,7 @@ import (
"os"
"strconv"
"testing"
"time"
"git.mousesoft.ru/ms/config/test"
"github.com/stretchr/testify/assert"
@ -264,3 +265,16 @@ func TestCommandWithSlices(t *testing.T) {
assert.Equal(200, conf.Values[1])
assert.Equal(300, conf.Values[2])
}
func TestDuration(t *testing.T) {
assert := assert.New(t)
var conf struct {
interval time.Duration `cli:"interval" usage:"interval"`
}
cmd := NewCLI("Config")
assert.NoError(cmd.Init(&conf), "init config command")
args := []string{"--interval", "5s"}
assert.NoError(cmd.Parse(args))
}