From c7978c98097b92b659e2ea1763cd134b0695407e Mon Sep 17 00:00:00 2001 From: Solomon Hykes Date: Fri, 9 May 2014 17:06:32 -0700 Subject: [PATCH] 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 (github: shykes) --- engine/env.go | 24 ++++++++++++++++++++++++ engine/env_test.go | 20 ++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/engine/env.go b/engine/env.go index 94d8c3d8a7..f63f29e10f 100644 --- a/engine/env.go +++ b/engine/env.go @@ -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) + } + } +} diff --git a/engine/env_test.go b/engine/env_test.go index 0c66cea04e..39669d6780 100644 --- a/engine/env_test.go +++ b/engine/env_test.go @@ -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) + } +}