From e35d6f13814eb3178ff47f5a587515f72f5fbc48 Mon Sep 17 00:00:00 2001 From: Cyrille Nofficial Date: Fri, 27 Dec 2019 15:22:43 +0100 Subject: [PATCH] [cli] Add utility method to init float64 args --- cli/cli.go | 24 ++++++++++++++++++++++++ cli/cli_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/cli/cli.go b/cli/cli.go index 9ff38fe..d0113cc 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -33,6 +33,21 @@ func SetIntDefaultValueFromEnv(value *int, key string, defaultValue int) error { } return nil } +func SetFloat64DefaultValueFromEnv(value *float64, key string, defaultValue float64) error { + var sVal string + if os.Getenv(key) != "" { + sVal = os.Getenv(key) + val, err := strconv.ParseFloat(sVal, 64) + if err != nil { + log.Printf("unable to convert string to float: %v", err) + return err + } + *value = val + } else { + *value = defaultValue + } + return nil +} type Part interface { Start() error @@ -71,6 +86,15 @@ func InitIntFlag(key string, defValue int) int { return value } +func InitFloat64Flag(key string, defValue float64) float64 { + var value float64 + err := SetFloat64DefaultValueFromEnv(&value, key, defValue) + if err != nil { + log.Panicf("invalid value: %v", err) + } + return value +} + func Connect(uri, username, password, clientId string) (MQTT.Client, error) { //create a ClientOptions struct setting the broker address, clientid, turn //off trace output and set the default message handler diff --git a/cli/cli_test.go b/cli/cli_test.go index c0a1ff5..5ba891b 100644 --- a/cli/cli_test.go +++ b/cli/cli_test.go @@ -62,3 +62,39 @@ func TestSetIntDefaultValueFromEnv(t *testing.T) { } } } + +func TestSetFloat64DefaultValueFromEnv(t *testing.T) { + err := os.Setenv("KEY1", "12.2") + err = os.Setenv("KEY2", "12") + err = os.Setenv("BAD_VALUE", "bad value") + if err != nil { + t.Errorf("unable to set env value: %v", err) + } + + cases := []struct { + key string + defValue float64 + expected float64 + withError bool + }{ + {"MISSING_KEY", 3.3, 3.3, false}, + {"KEY1", 5, 12.2, false}, + {"KEY2", 5, 12., false}, + {"BAD_VALUE", 5, 0, true}, + } + + for _, c := range cases { + var value = 0. + err := SetFloat64DefaultValueFromEnv(&value, c.key, c.defValue) + if err != nil { + if !c.withError { + t.Errorf("SetFloat64DefaultValueFromEnv(*value, %v, %v): %v", c.key, c.defValue, err) + } + } + if c.withError && err == nil { + t.Errorf("SetFloat64DefaultValueFromEnv(*value, %v, %v): %v, wants an error", c.key, c.defValue, value) + } else if c.expected != value { + t.Errorf("SetFloat64DefaultValueFromEnv(*value, %v, %v): %v, wants %v", c.key, c.defValue, value, c.expected) + } + } +}