Skip to content

Commit

Permalink
Extract splitKeyValueSlice and test
Browse files Browse the repository at this point in the history
  • Loading branch information
jwilder committed Feb 28, 2015
1 parent fd74286 commit c14bed8
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 18 deletions.
11 changes: 1 addition & 10 deletions docker-gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,16 +98,7 @@ type ConfigFile struct {
type Context []*RuntimeContainer

func (c *Context) Env() map[string]string {

env := make(map[string]string)
for _, entry := range os.Environ() {
parts := strings.SplitN(entry, "=", 2)
if len(parts) != 2 {
parts = append(parts, "")
}
env[parts[0]] = parts[1]
}
return env
return splitKeyValueSlice(os.Environ())
}

func (c *ConfigFile) filterWatches() ConfigFile {
Expand Down
9 changes: 1 addition & 8 deletions docker_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,14 +147,7 @@ func getContainers(client *docker.Client) ([]*RuntimeContainer, error) {
}
}

for _, entry := range container.Config.Env {
parts := strings.SplitN(entry, "=", 2)
if len(parts) != 2 {
parts = append(parts, "")
}
runtimeContainer.Env[parts[0]] = parts[1]
}

runtimeContainer.Env = splitKeyValueSlice(container.Config.Env)
containers = append(containers, runtimeContainer)
}
return containers, nil
Expand Down
17 changes: 17 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"os"
"strings"
)

func getEndpoint() (string, error) {
Expand All @@ -21,3 +22,19 @@ func getEndpoint() (string, error) {

return defaultEndpoint, nil
}

// splitKeyValueSlice takes a string slice where values are of the form
// KEY, KEY=, KEY=VALUE or KEY=NESTED_KEY=VALUE2, and returns a map[string]string where items
// are split at their first `=`.
func splitKeyValueSlice(in []string) map[string]string {
env := make(map[string]string)
for _, entry := range in {
parts := strings.SplitN(entry, "=", 2)
if len(parts) != 2 {
parts = append(parts, "")
}
env[parts[0]] = parts[1]
}
return env

}
20 changes: 20 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,23 @@ func TestUnixBadFormat(t *testing.T) {
t.Fatal("endpoint should have failed")
}
}

func TestSplitKeyValueSlice(t *testing.T) {
tests := []struct {
input []string
expected string
}{
{[]string{"K"}, ""},
{[]string{"K="}, ""},
{[]string{"K=V3"}, "V3"},
{[]string{"K=V4=V5"}, "V4=V5"},
}

for _, i := range tests {
v := splitKeyValueSlice(i.input)
if v["K"] != i.expected {
t.Fatalf("expected K='%s'. got '%s'", i.expected, v["K"])
}

}
}

0 comments on commit c14bed8

Please sign in to comment.