From d9902780584f405bf842d4ac25db06de63ef1e08 Mon Sep 17 00:00:00 2001 From: Cyrille Nofficial Date: Sun, 1 Dec 2019 22:58:12 +0100 Subject: [PATCH] [cli] Add tooling for cli --- cli/cli.go | 11 +++++++++++ cli/cli_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 cli/cli.go create mode 100644 cli/cli_test.go diff --git a/cli/cli.go b/cli/cli.go new file mode 100644 index 0000000..f6f31e8 --- /dev/null +++ b/cli/cli.go @@ -0,0 +1,11 @@ +package cli + +import "os" + +func SetDefaultValueFromEnv(value *string, key string, defaultValue string) { + if os.Getenv(key) != "" { + *value = os.Getenv(key) + } else { + *value = defaultValue + } +} diff --git a/cli/cli_test.go b/cli/cli_test.go new file mode 100644 index 0000000..98d6add --- /dev/null +++ b/cli/cli_test.go @@ -0,0 +1,30 @@ +package cli + +import ( + "os" + "testing" +) + +func TestSetDefaultValueFromEnv(t *testing.T) { + err := os.Setenv("KEY1", "value1") + if err != nil { + t.Errorf("unable to set env value: %v", err) + } + + cases := []struct{ + key string + defValue string + expected string + }{ + {"MISSING_KEY", "default", "default"}, + {"KEY1", "bad value", "value1"}, + } + + for _, c := range cases { + var value = "" + SetDefaultValueFromEnv(&value, c.key, c.defValue) + if c.expected != value { + t.Errorf("SetDefaultValueFromEnv(*value, %v, %v): %v, wants %v", c.key, c.defValue, value, c.expected) + } + } +}