Skip to content

Commit

Permalink
add support for complex key with dots, add more tests (olebedev#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
madding authored and olebedev committed May 28, 2019
1 parent 57f8042 commit 364964f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
29 changes: 28 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ func typeMismatch(expected string, got interface{}) error {

// Get returns a child of the given value according to a dotted path.
func Get(cfg interface{}, path string) (interface{}, error) {
parts := strings.Split(path, ".")
parts := splitKeyOnParts(path)
// Normalize path.
for k, v := range parts {
if v == "" {
Expand Down Expand Up @@ -427,6 +427,33 @@ func Get(cfg interface{}, path string) (interface{}, error) {
return cfg, nil
}

func splitKeyOnParts(key string) []string {
parts := []string{}

bracketOpened := false
var buffer bytes.Buffer
for _, char := range key {
if char == 91 || char == 93 { // [ ]
bracketOpened = char == 91
continue
}
if char == 46 && !bracketOpened { // point
parts = append(parts, buffer.String())
buffer.Reset()
continue
}

buffer.WriteRune(char)
}

if buffer.String() != "" {
parts = append(parts, buffer.String())
buffer.Reset()
}

return parts
}

// Set returns an error, in case when it is not possible to
// establish the value obtained in accordance with given dotted path.
func Set(cfg interface{}, path string, value interface{}) error {
Expand Down
21 changes: 21 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,27 @@ list:
expect(t, extended.UString("list.8"), "item8")
}

func TestComplexYamlKeys(t *testing.T) {
cfg, err := ParseYaml(`
root:
field1: value1
field.something.2: value2
"field number 3":
field4: value3
field.something.4:
field5: value5
field.6: value6
`)
expect(t, err, nil)

// result
expect(t, cfg.UString("root.field1"), "value1")
expect(t, cfg.UString("root.[field.something.2]"), "value2")
expect(t, cfg.UString("root.field number 3.field4"), "value3")
expect(t, cfg.UString("root.[field.something.4].field5"), "value5")
expect(t, cfg.UString("root.[field.something.4].[field.6]"), "value6")
}

func testConfig(t *testing.T, cfg *Config) {
Loop:
for _, test := range configTests {
Expand Down

0 comments on commit 364964f

Please sign in to comment.