1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00

Engine: Env.MultiMap, Env.InitMultiMap: import/export to other formats

* `Env.MultiMap` returns the contents of an Env as `map[string][]string`
* `Env.InitMultiMap` initializes the contents of an Env from a `map[string][]string`

This makes it easier to import and export an Env to other formats
(specifically `beam/data` messages)

Docker-DCO-1.1-Signed-off-by: Solomon Hykes <solomon@docker.com> (github: shykes)
This commit is contained in:
Solomon Hykes 2014-05-09 17:06:32 -07:00
parent 2af030ab57
commit c7978c9809
2 changed files with 44 additions and 0 deletions

View file

@ -250,3 +250,27 @@ func (env *Env) Map() map[string]string {
}
return m
}
// MultiMap returns a representation of env as a
// map of string arrays, keyed by string.
// This is the same structure as http headers for example,
// which allow each key to have multiple values.
func (env *Env) MultiMap() map[string][]string {
m := make(map[string][]string)
for _, kv := range *env {
parts := strings.SplitN(kv, "=", 2)
m[parts[0]] = append(m[parts[0]], parts[1])
}
return m
}
// InitMultiMap removes all values in env, then initializes
// new values from the contents of m.
func (env *Env) InitMultiMap(m map[string][]string) {
(*env) = make([]string, 0, len(m))
for k, vals := range m {
for _, v := range vals {
env.Set(k, v)
}
}
}

View file

@ -123,3 +123,23 @@ func TestEnviron(t *testing.T) {
t.Fatalf("bar not found in the environ")
}
}
func TestMultiMap(t *testing.T) {
e := &Env{}
e.Set("foo", "bar")
e.Set("bar", "baz")
e.Set("hello", "world")
m := e.MultiMap()
e2 := &Env{}
e2.Set("old_key", "something something something")
e2.InitMultiMap(m)
if v := e2.Get("old_key"); v != "" {
t.Fatalf("%#v", v)
}
if v := e2.Get("bar"); v != "baz" {
t.Fatalf("%#v", v)
}
if v := e2.Get("hello"); v != "world" {
t.Fatalf("%#v", v)
}
}