Skip to content

Commit

Permalink
Disallow multiple definitions of a key.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaholaz committed May 13, 2024
1 parent 0483f5e commit 9599b2a
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,9 @@ override your defaults. This is simply done by:
itkconfig.LoadConfig("filename.conf", cfg)
```

Non-slice keys can only be defined once per config file. Multiple
definitions will produce an error.

## Authors

* Trygve Aaberge ([trygveaa@samfundet.no](mailto:trygveaa@samfundet.no))
Expand Down
4 changes: 4 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ func LoadConfig(filename string, config interface{}) error {

field.Set(reflect.Append(field, v))
default:
if lastUpdate[*key] != 0 {
return syntaxError(fmt.Sprintf("key '%s' was defined multiple times, initially on line %d (did you mean to define a slice?)", *key, lastUpdate[*key]))
}

v, err := parseField(*key, *value, field.Type())
if err != nil {
return syntaxError(err.Error())
Expand Down
14 changes: 14 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -462,3 +462,17 @@ Could not parse config with multiple quotes correctly.
got: %#v`, want, config)
}
}

func TestMultipleDefinitions(t *testing.T) {
type Config struct {
Foo string
}

config := Config{
Foo: "",
}
err := LoadConfig("test_configs/multipledefinitions.cfg", &config)
if err == nil {
t.Fatalf("Should not be allowed to redefine a key.")
}
}
2 changes: 2 additions & 0 deletions test_configs/multipledefinitions.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Foo = "bar"
Foo = "baz"

0 comments on commit 9599b2a

Please sign in to comment.