From 207759e9e4ad046101df8d0c3c2a436c116a1cc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9=20=D0=91=D0=B0?= =?UTF-8?q?=D0=B4=D1=8F=D0=B5=D0=B2?= Date: Tue, 22 Oct 2024 21:46:13 +0700 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=B0=D1=80=D0=B3=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4=D0=BD=D0=BE=D0=B9?= =?UTF-8?q?=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=D0=B8=20=D1=82=D0=B8=D0=BF?= =?UTF-8?q?=D0=B0=20time.Duration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cli.go | 10 ++++++++++ cli_test.go | 14 ++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/cli.go b/cli.go index 3eb537d..0f0dd1c 100644 --- a/cli.go +++ b/cli.go @@ -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: diff --git a/cli_test.go b/cli_test.go index 34b8d41..8b25ced 100644 --- a/cli_test.go +++ b/cli_test.go @@ -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)) +}