Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion base/config/persistence.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package config
import (
"encoding/json"
"fmt"
"maps"
"os"
"path"
"slices"
"strings"
"sync"

Expand Down Expand Up @@ -114,8 +116,14 @@ func Flatten(config map[string]interface{}) (flattenedConfig map[string]interfac
return flattenedConfig
}

// flattenMap adds all values of subMap to rootMap, joining nested keys with
// "/" and prefixing them with subKey. Keys are processed in sorted order to get
// a deterministic result when the same option is defined both nested and
// flattened, e.g. {"a": {"b": 1}, "a/b": 2}. A flattened key sorts after its
// nested parent and therefore takes precedence.
func flattenMap(rootMap, subMap map[string]interface{}, subKey string) {
for key, entry := range subMap {
for _, key := range slices.Sorted(maps.Keys(subMap)) {
entry := subMap[key]

// get next level key
subbedKey := path.Join(subKey, key)
Expand Down
17 changes: 17 additions & 0 deletions base/config/persistence_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,20 @@ func TestConfigCleaning(t *testing.T) {
t.Errorf("should be empty: %+v", configHier)
}
}

// TestFlattenDuplicateKeys checks that an option defined both nested and
// flattened always resolves to the same value, independent of the random map
// iteration order.
func TestFlattenDuplicateKeys(t *testing.T) {
t.Parallel()

for range 100 {
configFlat, err := JSONToMap([]byte(`{"core": {"devMode": false}, "core/devMode": true}`))
if err != nil {
t.Fatal(err)
}
if value := configFlat["core/devMode"]; value != true {
t.Fatalf("flattened key should take precedence over nested key, got %v", value)
}
}
}