Allow strings "true", "false", "1" and "0" to be used where booleans are expected
There is precedent for allowing strings containing digits where numbers are expected, and so this extends that to also allow for boolean values to be given as strings. This applies only to callers going through the decoder API. Direct access via the AST will reflect exactly what was given in the input configuration.
This commit is contained in:
parent
8cb6e5b959
commit
65a6292f01
15
decoder.go
15
decoder.go
@ -117,10 +117,17 @@ func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error
|
||||
func (d *decoder) decodeBool(name string, node ast.Node, result reflect.Value) error {
|
||||
switch n := node.(type) {
|
||||
case *ast.LiteralType:
|
||||
if n.Token.Type == token.BOOL {
|
||||
v, err := strconv.ParseBool(n.Token.Text)
|
||||
if err != nil {
|
||||
return err
|
||||
switch n.Token.Type {
|
||||
case token.BOOL, token.STRING, token.NUMBER:
|
||||
var v bool
|
||||
s := strings.ToLower(strings.Replace(n.Token.Text, "\"", "", -1))
|
||||
switch s {
|
||||
case "1", "true":
|
||||
v = true
|
||||
case "0", "false":
|
||||
v = false
|
||||
default:
|
||||
return fmt.Errorf("decodeBool: Unknown value for boolean: %s", n.Token.Text)
|
||||
}
|
||||
|
||||
result.Set(reflect.ValueOf(v))
|
||||
|
@ -794,6 +794,51 @@ func TestDecode_interfaceNonPointer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecode_boolString(t *testing.T) {
|
||||
var value struct {
|
||||
Boolean bool
|
||||
}
|
||||
|
||||
err := Decode(&value, testReadFile(t, "basic_bool_string.hcl"))
|
||||
if err != nil {
|
||||
t.Fatalf("err: %s", err)
|
||||
}
|
||||
|
||||
if value.Boolean != true {
|
||||
t.Fatalf("bad: %#v", value.Boolean)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecode_boolInt(t *testing.T) {
|
||||
var value struct {
|
||||
Boolean bool
|
||||
}
|
||||
|
||||
err := Decode(&value, testReadFile(t, "basic_bool_int.hcl"))
|
||||
if err != nil {
|
||||
t.Fatalf("err: %s", err)
|
||||
}
|
||||
|
||||
if value.Boolean != true {
|
||||
t.Fatalf("bad: %#v", value.Boolean)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecode_bool(t *testing.T) {
|
||||
var value struct {
|
||||
Boolean bool
|
||||
}
|
||||
|
||||
err := Decode(&value, testReadFile(t, "basic_bool.hcl"))
|
||||
if err != nil {
|
||||
t.Fatalf("err: %s", err)
|
||||
}
|
||||
|
||||
if value.Boolean != true {
|
||||
t.Fatalf("bad: %#v", value.Boolean)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecode_intString(t *testing.T) {
|
||||
var value struct {
|
||||
Count int
|
||||
|
1
test-fixtures/basic_bool.hcl
Normal file
1
test-fixtures/basic_bool.hcl
Normal file
@ -0,0 +1 @@
|
||||
boolean = true
|
1
test-fixtures/basic_bool_int.hcl
Normal file
1
test-fixtures/basic_bool_int.hcl
Normal file
@ -0,0 +1 @@
|
||||
boolean = 1
|
1
test-fixtures/basic_bool_string.hcl
Normal file
1
test-fixtures/basic_bool_string.hcl
Normal file
@ -0,0 +1 @@
|
||||
boolean = "trUe"
|
Loading…
Reference in New Issue
Block a user