From cbe3e0a27121293a3402ab12bb4da01c68d086a0 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Fri, 21 May 2021 15:50:24 +0300 Subject: [PATCH] [#493] node/config: Implement string caster Signed-off-by: Leonard Lyubich --- cmd/neofs-node/config/cast.go | 19 +++++++++++++++++++ cmd/neofs-node/config/cast_test.go | 16 ++++++++++++++++ cmd/neofs-node/config/test/config.json | 4 ++++ cmd/neofs-node/config/test/config.yaml | 7 ++++++- 4 files changed, 45 insertions(+), 1 deletion(-) diff --git a/cmd/neofs-node/config/cast.go b/cmd/neofs-node/config/cast.go index dbd39b55c..458ac09d1 100644 --- a/cmd/neofs-node/config/cast.go +++ b/cmd/neofs-node/config/cast.go @@ -28,3 +28,22 @@ func StringSlice(c *Config, name string) []string { func StringSliceSafe(c *Config, name string) []string { return cast.ToStringSlice(c.Value(name)) } + +// String reads configuration value +// from c by name and casts it to string. +// +// Panics if value can not be casted. +func String(c *Config, name string) string { + x, err := cast.ToStringE(c.Value(name)) + panicOnErr(err) + + return x +} + +// StringSafe reads configuration value +// from c by name and casts it to string. +// +// Returns "" if value can not be casted. +func StringSafe(c *Config, name string) string { + return cast.ToString(c.Value(name)) +} diff --git a/cmd/neofs-node/config/cast_test.go b/cmd/neofs-node/config/cast_test.go index 9eefd50c1..9d7b96cd2 100644 --- a/cmd/neofs-node/config/cast_test.go +++ b/cmd/neofs-node/config/cast_test.go @@ -28,3 +28,19 @@ func TestStringSlice(t *testing.T) { require.Nil(t, val) }) } + +func TestString(t *testing.T) { + forEachFileType("test/config", func(c *config.Config) { + c = c.Sub("string") + + val := config.String(c, "correct") + require.Equal(t, "some string", val) + + require.Panics(t, func() { + config.String(c, "incorrect") + }) + + val = config.StringSafe(c, "incorrect") + require.Empty(t, val) + }) +} diff --git a/cmd/neofs-node/config/test/config.json b/cmd/neofs-node/config/test/config.json index f10856acc..14be797fb 100644 --- a/cmd/neofs-node/config/test/config.json +++ b/cmd/neofs-node/config/test/config.json @@ -10,5 +10,9 @@ "string2" ], "incorrect": null + }, + "string": { + "correct": "some string", + "incorrect": [] } } diff --git a/cmd/neofs-node/config/test/config.yaml b/cmd/neofs-node/config/test/config.yaml index e383eae81..6d601ad18 100644 --- a/cmd/neofs-node/config/test/config.yaml +++ b/cmd/neofs-node/config/test/config.yaml @@ -10,4 +10,9 @@ string_slice: - string1 - string2 - incorrect: \ No newline at end of file + incorrect: + +string: + correct: some string + + incorrect: []