Browse Source

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)
Solomon Hykes 11 năm trước cách đây
mục cha
commit
c7978c9809
2 tập tin đã thay đổi với 44 bổ sung0 xóa
  1. 24 0
      engine/env.go
  2. 20 0
      engine/env_test.go

+ 24 - 0
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)
+		}
+	}
+}

+ 20 - 0
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)
+	}
+}