* `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)
| ... | ... |
@@ -250,3 +250,27 @@ func (env *Env) Map() map[string]string {
|
| 250 | 250 |
} |
| 251 | 251 |
return m |
| 252 | 252 |
} |
| 253 |
+ |
|
| 254 |
+// MultiMap returns a representation of env as a |
|
| 255 |
+// map of string arrays, keyed by string. |
|
| 256 |
+// This is the same structure as http headers for example, |
|
| 257 |
+// which allow each key to have multiple values. |
|
| 258 |
+func (env *Env) MultiMap() map[string][]string {
|
|
| 259 |
+ m := make(map[string][]string) |
|
| 260 |
+ for _, kv := range *env {
|
|
| 261 |
+ parts := strings.SplitN(kv, "=", 2) |
|
| 262 |
+ m[parts[0]] = append(m[parts[0]], parts[1]) |
|
| 263 |
+ } |
|
| 264 |
+ return m |
|
| 265 |
+} |
|
| 266 |
+ |
|
| 267 |
+// InitMultiMap removes all values in env, then initializes |
|
| 268 |
+// new values from the contents of m. |
|
| 269 |
+func (env *Env) InitMultiMap(m map[string][]string) {
|
|
| 270 |
+ (*env) = make([]string, 0, len(m)) |
|
| 271 |
+ for k, vals := range m {
|
|
| 272 |
+ for _, v := range vals {
|
|
| 273 |
+ env.Set(k, v) |
|
| 274 |
+ } |
|
| 275 |
+ } |
|
| 276 |
+} |
| ... | ... |
@@ -123,3 +123,23 @@ func TestEnviron(t *testing.T) {
|
| 123 | 123 |
t.Fatalf("bar not found in the environ")
|
| 124 | 124 |
} |
| 125 | 125 |
} |
| 126 |
+ |
|
| 127 |
+func TestMultiMap(t *testing.T) {
|
|
| 128 |
+ e := &Env{}
|
|
| 129 |
+ e.Set("foo", "bar")
|
|
| 130 |
+ e.Set("bar", "baz")
|
|
| 131 |
+ e.Set("hello", "world")
|
|
| 132 |
+ m := e.MultiMap() |
|
| 133 |
+ e2 := &Env{}
|
|
| 134 |
+ e2.Set("old_key", "something something something")
|
|
| 135 |
+ e2.InitMultiMap(m) |
|
| 136 |
+ if v := e2.Get("old_key"); v != "" {
|
|
| 137 |
+ t.Fatalf("%#v", v)
|
|
| 138 |
+ } |
|
| 139 |
+ if v := e2.Get("bar"); v != "baz" {
|
|
| 140 |
+ t.Fatalf("%#v", v)
|
|
| 141 |
+ } |
|
| 142 |
+ if v := e2.Get("hello"); v != "world" {
|
|
| 143 |
+ t.Fatalf("%#v", v)
|
|
| 144 |
+ } |
|
| 145 |
+} |