diff --git a/cli/cli.go b/cli/cli.go index f6f31e8..ebc5e20 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -1,6 +1,10 @@ package cli -import "os" +import ( + "log" + "os" + "strconv" +) func SetDefaultValueFromEnv(value *string, key string, defaultValue string) { if os.Getenv(key) != "" { @@ -9,3 +13,18 @@ func SetDefaultValueFromEnv(value *string, key string, defaultValue string) { *value = defaultValue } } +func SetIntDefaultValueFromEnv(value *int, key string, defaultValue int) error { + var sVal string + if os.Getenv(key) != "" { + sVal = os.Getenv(key) + val, err := strconv.Atoi(sVal) + if err != nil{ + log.Printf("unable to convert string to int: %v", err) + return err + } + *value = val + } else { + *value = defaultValue + } + return nil +} diff --git a/cli/cli_test.go b/cli/cli_test.go index 98d6add..e3c2bdc 100644 --- a/cli/cli_test.go +++ b/cli/cli_test.go @@ -28,3 +28,37 @@ func TestSetDefaultValueFromEnv(t *testing.T) { } } } + +func TestSetIntDefaultValueFromEnv(t *testing.T) { + err := os.Setenv("KEY1", "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 int + expected int + withError bool + }{ + {"MISSING_KEY", 3, 3, false}, + {"KEY1", 5, 12, false}, + {"BAD_VALUE", 5, 0, true}, + } + + for _, c := range cases { + var value = 0 + err := SetIntDefaultValueFromEnv(&value, c.key, c.defValue) + if err != nil { + if !c.withError{ + t.Errorf("SetIntDefaultValueFromEnv(*value, %v, %v): %v", c.key, c.defValue, err) + } + } + if c.withError && err == nil{ + t.Errorf("SetIntDefaultValueFromEnv(*value, %v, %v): %v, wants an error", c.key, c.defValue, value) + } else if c.expected != value { + t.Errorf("SetDefaultValueFromEnv(*value, %v, %v): %v, wants %v", c.key, c.defValue, value, c.expected) + } + } +}