Merge pull request #459 from ChrisHines/parse-env

Handle additional edge cases when parsing environment variables.
This commit is contained in:
Alex Dadgar 2015-11-18 18:41:36 -08:00
commit ceeabe63f7
2 changed files with 23 additions and 11 deletions

View file

@ -44,17 +44,22 @@ func NewTaskEnivornment() TaskEnvironment {
return make(map[string]string) return make(map[string]string)
} }
// Parses a list of strings with NAME=value pairs and returns a TaskEnvironment. // ParseFromList parses a list of strings with NAME=value pairs and returns a
// TaskEnvironment.
func ParseFromList(envVars []string) (TaskEnvironment, error) { func ParseFromList(envVars []string) (TaskEnvironment, error) {
t := NewTaskEnivornment() t := NewTaskEnivornment()
for _, pair := range envVars { for _, pair := range envVars {
parts := strings.Split(pair, "=") // Start the search from the second byte to skip a possible leading
if len(parts) != 2 { // "=". Cmd.exe on Windows creates some special environment variables
// that start with an "=" and they can be properly retrieved by OS
// functions so we should handle them properly here.
idx := strings.Index(pair[1:], "=")
if idx == -1 {
return nil, fmt.Errorf("Couldn't parse environment variable: %v", pair) return nil, fmt.Errorf("Couldn't parse environment variable: %v", pair)
} }
idx++ // adjust for slice offset above
t[parts[0]] = parts[1] t[pair[:idx]] = pair[idx+1:]
} }
return t, nil return t, nil

View file

@ -22,26 +22,33 @@ func TestEnvironment_AsList(t *testing.T) {
} }
func TestEnvironment_ParseFromList(t *testing.T) { func TestEnvironment_ParseFromList(t *testing.T) {
input := []string{"foo=bar", "BAZ=baM"} input := []string{
"foo=bar",
"BAZ=baM",
"bar=emb=edded", // This can be done in multiple OSes.
"=ExitCode=00000000", // A Windows cmd.exe annoyance
}
env, err := ParseFromList(input) env, err := ParseFromList(input)
if err != nil { if err != nil {
t.Fatalf("ParseFromList(%#v) failed: %v", input, err) t.Fatalf("ParseFromList(%#v) failed: %v", input, err)
} }
exp := map[string]string{ exp := map[string]string{
"foo": "bar", "foo": "bar",
"BAZ": "baM", "BAZ": "baM",
"bar": "emb=edded",
"=ExitCode": "00000000",
} }
if len(env) != len(exp) { if len(env) != len(exp) {
t.Fatalf("ParseFromList(%#v) has length %v; want %v", input, len(env), len(exp)) t.Errorf("ParseFromList(%#v) has length %v; want %v", input, len(env), len(exp))
} }
for k, v := range exp { for k, v := range exp {
if actV, ok := env[k]; !ok { if actV, ok := env[k]; !ok {
t.Fatalf("ParseFromList(%#v) doesn't contain expected %v", input, k) t.Errorf("ParseFromList(%#v) doesn't contain expected %v", input, k)
} else if actV != v { } else if actV != v {
t.Fatalf("ParseFromList(%#v) has incorrect value for %v; got %v; want %v", input, k, actV, v) t.Errorf("ParseFromList(%#v) has incorrect value for %v; got %v; want %v", input, k, actV, v)
} }
} }
} }