From a983d3e9743eabd69fb9967be8b6f0be1feccf39 Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Thu, 21 Nov 2024 11:07:06 -0600 Subject: [PATCH] Support setting entire slices when filling config values --- pkg/config/env.go | 2 +- pkg/config/env_test.go | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/pkg/config/env.go b/pkg/config/env.go index 5732084..37c49df 100644 --- a/pkg/config/env.go +++ b/pkg/config/env.go @@ -203,7 +203,7 @@ func setFieldByPath(v reflect.Value, path []string, value any) error { // Handle YAML (and therefore JSON) parsing for passing in entire structs/maps // This is particularly useful if you want to pass in a whole blob of network constants at once - if fieldValue.Kind() == reflect.Struct || fieldValue.Kind() == reflect.Map { + if fieldValue.Kind() == reflect.Struct || fieldValue.Kind() == reflect.Map || fieldValue.Kind() == reflect.Slice { if strValue, ok := value.(string); ok { yamlData := []byte(strValue) if err := yaml.Unmarshal(yamlData, fieldValue.Addr().Interface()); err != nil { diff --git a/pkg/config/env_test.go b/pkg/config/env_test.go index 49e5cd7..6dbf673 100644 --- a/pkg/config/env_test.go +++ b/pkg/config/env_test.go @@ -94,6 +94,27 @@ func TestChiaConfig_SetFieldByPath_FullObjects(t *testing.T) { assert.Equal(t, "9eb3cec765fb3b3508f82e090374d5913d24806e739da31bcc4ab1767d9f1ca9", defaultConfig.NetworkOverrides.Constants["yamlnet"].GenesisChallenge) } +// TestChiaConfig_SetFieldByPath_FullObjects Tests that we can pass in and correctly parse a whole section of config +// as json or yaml and that it gets set properly +func TestChiaConfig_SetFieldByPath_Lists(t *testing.T) { + defaultConfig, err := config.LoadDefaultConfig() + assert.NoError(t, err) + // Make assertions about the default state, to ensure the assumed initial values are correct + assert.Equal(t, []string{}, defaultConfig.Seeder.StaticPeers) + assert.Equal(t, []config.Peer{}, defaultConfig.FullNode.FullNodePeers) + + err = defaultConfig.SetFieldByPath([]string{"seeder", "static_peers"}, `["node-test.chia.net","node-test-2.chia.net"]`) + assert.NoError(t, err) + assert.Equal(t, []string{"node-test.chia.net", "node-test-2.chia.net"}, defaultConfig.Seeder.StaticPeers) + + err = defaultConfig.SetFieldByPath([]string{"full_node", "full_node_peers"}, `[{"host":"testnode.example.com","port":1234},{"host":"testnode2.example.com","port":5678}]`) + assert.NoError(t, err) + assert.Equal(t, []config.Peer{ + {Host: "testnode.example.com", Port: 1234}, + {Host: "testnode2.example.com", Port: 5678}, + }, defaultConfig.FullNode.FullNodePeers) +} + func TestChiaConfig_FillValuesFromEnvironment(t *testing.T) { defaultConfig, err := config.LoadDefaultConfig() assert.NoError(t, err)