1
0
Fork 0
mirror of https://github.com/Luzifer/rconfig.git synced 2024-11-08 16:00:10 +00:00

Support time.Duration config parameters

This commit is contained in:
Knut Ahlers 2016-06-28 12:31:23 +02:00
parent 26776536e6
commit 02c6b11d62
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E
2 changed files with 65 additions and 0 deletions

View file

@ -10,6 +10,7 @@ import (
"reflect" "reflect"
"strconv" "strconv"
"strings" "strings"
"time"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -100,6 +101,29 @@ func execTags(in interface{}, fs *pflag.FlagSet) error {
value = envDefault(typeField.Tag.Get("env"), value) value = envDefault(typeField.Tag.Get("env"), value)
parts := strings.Split(typeField.Tag.Get("flag"), ",") parts := strings.Split(typeField.Tag.Get("flag"), ",")
switch typeField.Type {
case reflect.TypeOf(time.Duration(0)):
v, err := time.ParseDuration(value)
if err != nil {
if value == "" {
v = time.Duration(0)
} else {
return err
}
}
if typeField.Tag.Get("flag") != "" {
if len(parts) == 1 {
fs.DurationVar(valField.Addr().Interface().(*time.Duration), parts[0], v, typeField.Tag.Get("description"))
} else {
fs.DurationVarP(valField.Addr().Interface().(*time.Duration), parts[0], parts[1], v, typeField.Tag.Get("description"))
}
} else {
valField.Set(reflect.ValueOf(v))
}
continue
}
switch typeField.Type.Kind() { switch typeField.Type.Kind() {
case reflect.String: case reflect.String:
if typeField.Tag.Get("flag") != "" { if typeField.Tag.Get("flag") != "" {

41
duration_test.go Normal file
View file

@ -0,0 +1,41 @@
package rconfig
import (
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Duration", func() {
type t struct {
Test time.Duration `flag:"duration"`
TestS time.Duration `flag:"other-duration,o"`
TestDef time.Duration `default:"30h"`
}
var (
err error
args []string
cfg t
)
BeforeEach(func() {
cfg = t{}
args = []string{
"--duration=23s", "-o", "45m",
}
})
JustBeforeEach(func() {
err = parse(&cfg, args)
})
It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
It("should have the expected values", func() {
Expect(cfg.Test).To(Equal(23 * time.Second))
Expect(cfg.TestS).To(Equal(45 * time.Minute))
Expect(cfg.TestDef).To(Equal(30 * time.Hour))
})
})