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:
Phillip T. George 2018-09-06 13:38:39 -05:00 committed by Martin Atkins
parent 8cb6e5b959
commit 65a6292f01
5 changed files with 59 additions and 4 deletions

View File

@ -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))

View File

@ -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

View File

@ -0,0 +1 @@
boolean = true

View File

@ -0,0 +1 @@
boolean = 1

View File

@ -0,0 +1 @@
boolean = "trUe"