veyron/lib/exec: adding functions for setting and getting environment
variable values
Change-Id: I59c63bef6de5b28cd11c1de2648a9436d5dc2b86
diff --git a/lib/exec/util.go b/lib/exec/util.go
new file mode 100644
index 0000000..f19342c
--- /dev/null
+++ b/lib/exec/util.go
@@ -0,0 +1,30 @@
+package exec
+
+import (
+ "errors"
+ "strings"
+)
+
+// SetEnv updates / adds the value assignment for the given variable
+// in the given slice of environment variable assigments.
+func SetEnv(env []string, name, value string) []string {
+ newValue := name + "=" + value
+ for i, v := range env {
+ if strings.HasPrefix(v, name+"=") {
+ env[i] = newValue
+ return env
+ }
+ }
+ return append(env, newValue)
+}
+
+// GetEnv retrieves the value of the given variable from the given
+// slice of environment variable assignments.
+func GetEnv(env []string, name string) (string, error) {
+ for _, v := range env {
+ if strings.HasPrefix(v, name+"=") {
+ return strings.TrimPrefix(v, name+"="), nil
+ }
+ }
+ return "", errors.New("not found")
+}
diff --git a/lib/exec/util_test.go b/lib/exec/util_test.go
new file mode 100644
index 0000000..0f6e14b
--- /dev/null
+++ b/lib/exec/util_test.go
@@ -0,0 +1,34 @@
+package exec
+
+import (
+ "testing"
+)
+
+func TestEnv(t *testing.T) {
+ env := make([]string, 0)
+ env = SetEnv(env, "NAME", "VALUE1")
+ if expected, got := 1, len(env); expected != got {
+ t.Fatalf("Unexpected length of environment variable slice: expected %d, got %d", expected, got)
+ }
+ if expected, got := "NAME=VALUE1", env[0]; expected != got {
+ t.Fatalf("Unexpected element in the environment variable slice: expected %d, got %d", expected, got)
+ }
+ env = SetEnv(env, "NAME", "VALUE2")
+ if expected, got := 1, len(env); expected != got {
+ t.Fatalf("Unexpected length of environment variable slice: expected %d, got %d", expected, got)
+ }
+ if expected, got := "NAME=VALUE2", env[0]; expected != got {
+ t.Fatalf("Unexpected element in the environment variable slice: expected %d, got %d", expected, got)
+ }
+ value, err := GetEnv(env, "NAME")
+ if err != nil {
+ t.Fatalf("Unexpected error when looking up environment variable value: %v", err)
+ }
+ if expected, got := "VALUE2", value; expected != got {
+ t.Fatalf("Unexpected value of an environment variable: expected %d, got %d", expected, got)
+ }
+ value, err = GetEnv(env, "NONAME")
+ if err == nil {
+ t.Fatalf("Expected error when looking up environment variable value, got none", value)
+ }
+}