From 51c81540c2714ae5f91e50497dd4259ec8deab05 Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Thu, 21 Nov 2024 13:34:42 -0600 Subject: [PATCH] Allows filling structs/maps/slices with the actual type in addition to the json/yaml string --- pkg/config/env.go | 3 ++- pkg/config/env_test.go | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/pkg/config/env.go b/pkg/config/env.go index 37c49df..da03ec8 100644 --- a/pkg/config/env.go +++ b/pkg/config/env.go @@ -209,8 +209,9 @@ func setFieldByPath(v reflect.Value, path []string, value any) error { if err := yaml.Unmarshal(yamlData, fieldValue.Addr().Interface()); err != nil { return fmt.Errorf("failed to unmarshal yaml into field: %w", err) } + // If we successfully replaced by doing yaml parsing into the field, then we should not try anything else + return nil } - return nil } val := reflect.ValueOf(value) diff --git a/pkg/config/env_test.go b/pkg/config/env_test.go index 6dbf673..1de7f73 100644 --- a/pkg/config/env_test.go +++ b/pkg/config/env_test.go @@ -103,16 +103,37 @@ func TestChiaConfig_SetFieldByPath_Lists(t *testing.T) { assert.Equal(t, []string{}, defaultConfig.Seeder.StaticPeers) assert.Equal(t, []config.Peer{}, defaultConfig.FullNode.FullNodePeers) + // Test json encoded version 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) + // Test with the actual type as the data to set + // First reset + defaultConfig.Seeder.StaticPeers = []string{} + assert.Equal(t, []string{}, defaultConfig.Seeder.StaticPeers) + err = defaultConfig.SetFieldByPath([]string{"seeder", "static_peers"}, []string{"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) + + defaultConfig.FullNode.FullNodePeers = []config.Peer{} + assert.Equal(t, []config.Peer{}, defaultConfig.FullNode.FullNodePeers) + err = defaultConfig.SetFieldByPath([]string{"full_node", "full_node_peers"}, []config.Peer{ + {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) {