From 922d29ff884e5f67dfc34abf80a706960671404a Mon Sep 17 00:00:00 2001 From: Alex Vanin Date: Tue, 1 Jun 2021 14:04:00 +0300 Subject: [PATCH] [#493] cmd/node: Support duration type casting in config Signed-off-by: Alex Vanin --- cmd/neofs-node/config/cast.go | 21 +++++++++++++++++++++ cmd/neofs-node/config/cast_test.go | 17 +++++++++++++++++ cmd/neofs-node/config/test/config.json | 4 ++++ cmd/neofs-node/config/test/config.yaml | 4 ++++ 4 files changed, 46 insertions(+) diff --git a/cmd/neofs-node/config/cast.go b/cmd/neofs-node/config/cast.go index 458ac09d..566d8221 100644 --- a/cmd/neofs-node/config/cast.go +++ b/cmd/neofs-node/config/cast.go @@ -1,6 +1,8 @@ package config import ( + "time" + "github.com/spf13/cast" ) @@ -47,3 +49,22 @@ func String(c *Config, name string) string { func StringSafe(c *Config, name string) string { return cast.ToString(c.Value(name)) } + +// Duration reads configuration value +// from c by name and casts it to time.Duration. +// +// Panics if value can not be casted. +func Duration(c *Config, name string) time.Duration { + x, err := cast.ToDurationE(c.Value(name)) + panicOnErr(err) + + return x +} + +// DurationSafe reads configuration value +// from c by name and casts it to time.Duration. +// +// Returns 0 if value can not be casted. +func DurationSafe(c *Config, name string) time.Duration { + return cast.ToDuration(c.Value(name)) +} diff --git a/cmd/neofs-node/config/cast_test.go b/cmd/neofs-node/config/cast_test.go index a2bb2f19..ac5e699f 100644 --- a/cmd/neofs-node/config/cast_test.go +++ b/cmd/neofs-node/config/cast_test.go @@ -2,6 +2,7 @@ package config_test import ( "testing" + "time" "github.com/nspcc-dev/neofs-node/cmd/neofs-node/config" configtest "github.com/nspcc-dev/neofs-node/cmd/neofs-node/config/test" @@ -45,3 +46,19 @@ func TestString(t *testing.T) { require.Empty(t, val) }) } + +func TestDuration(t *testing.T) { + configtest.ForEachFileType("test/config", func(c *config.Config) { + c = c.Sub("duration") + + val := config.Duration(c, "correct") + require.Equal(t, 15*time.Minute, val) + + require.Panics(t, func() { + config.Duration(c, "incorrect") + }) + + val = config.DurationSafe(c, "incorrect") + require.Equal(t, time.Duration(0), val) + }) +} diff --git a/cmd/neofs-node/config/test/config.json b/cmd/neofs-node/config/test/config.json index 14be797f..1523ff79 100644 --- a/cmd/neofs-node/config/test/config.json +++ b/cmd/neofs-node/config/test/config.json @@ -14,5 +14,9 @@ "string": { "correct": "some string", "incorrect": [] + }, + "duration": { + "correct": "15m", + "incorrect": "some string" } } diff --git a/cmd/neofs-node/config/test/config.yaml b/cmd/neofs-node/config/test/config.yaml index 6d601ad1..39d2f1af 100644 --- a/cmd/neofs-node/config/test/config.yaml +++ b/cmd/neofs-node/config/test/config.yaml @@ -16,3 +16,7 @@ string: correct: some string incorrect: [] + +duration: + correct: 15m + incorrect: some string \ No newline at end of file