From 3b45305a2b365023e342cba1d7e5a7e3c92ae5cd Mon Sep 17 00:00:00 2001 From: Alex Dadgar Date: Wed, 25 Nov 2015 12:25:21 -0800 Subject: [PATCH 1/2] Accept string or bool --- jobspec/parse.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/jobspec/parse.go b/jobspec/parse.go index 58dbd6c9c5d7..a8edb26c559b 100644 --- a/jobspec/parse.go +++ b/jobspec/parse.go @@ -318,9 +318,17 @@ func parseConstraints(result *[]*structs.Constraint, list *ast.ObjectList) error } if value, ok := m[structs.ConstraintDistinctHosts]; ok { - enabled, err := strconv.ParseBool(value.(string)) - if err != nil { - return err + var enabled bool + var err error + switch value.(type) { + case string: + if enabled, err = strconv.ParseBool(value.(string)); err != nil { + return err + } + case bool: + enabled = value.(bool) + default: + return fmt.Errorf("distinct_hosts should be set to true or false; got %v", value) } // If it is not enabled, skip the constraint. From 3049507dd3eb4230871a7113f911e90934d38c4d Mon Sep 17 00:00:00 2001 From: Alex Dadgar Date: Wed, 25 Nov 2015 12:33:56 -0800 Subject: [PATCH 2/2] Extract bool conversion to method --- jobspec/parse.go | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/jobspec/parse.go b/jobspec/parse.go index a8edb26c559b..716ff9611f9d 100644 --- a/jobspec/parse.go +++ b/jobspec/parse.go @@ -318,17 +318,9 @@ func parseConstraints(result *[]*structs.Constraint, list *ast.ObjectList) error } if value, ok := m[structs.ConstraintDistinctHosts]; ok { - var enabled bool - var err error - switch value.(type) { - case string: - if enabled, err = strconv.ParseBool(value.(string)); err != nil { - return err - } - case bool: - enabled = value.(bool) - default: - return fmt.Errorf("distinct_hosts should be set to true or false; got %v", value) + enabled, err := parseBool(value) + if err != nil { + return fmt.Errorf("distinct_hosts should be set to true or false; %v", err) } // If it is not enabled, skip the constraint. @@ -354,6 +346,23 @@ func parseConstraints(result *[]*structs.Constraint, list *ast.ObjectList) error return nil } +// parseBool takes an interface value and tries to convert it to a boolean and +// returns an error if the type can't be converted. +func parseBool(value interface{}) (bool, error) { + var enabled bool + var err error + switch value.(type) { + case string: + enabled, err = strconv.ParseBool(value.(string)) + case bool: + enabled = value.(bool) + default: + err = fmt.Errorf("%v couldn't be converted to boolean value", value) + } + + return enabled, err +} + func parseTasks(jobName string, taskGroupName string, result *[]*structs.Task, list *ast.ObjectList) error { list = list.Children() if len(list.Items) == 0 {