Skip to content

Commit 0bc11e7

Browse files
committed
Add dict function
1 parent e955802 commit 0bc11e7

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

template.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"bytes"
5+
"errors"
56
"io"
67
"io/ioutil"
78
"log"
@@ -56,6 +57,21 @@ func contains(item map[string]string, key string) bool {
5657
return false
5758
}
5859

60+
func dict(values ...interface{}) (map[string]interface{}, error) {
61+
if len(values)%2 != 0 {
62+
return nil, errors.New("invalid dict call")
63+
}
64+
dict := make(map[string]interface{}, len(values)/2)
65+
for i := 0; i < len(values); i+=2 {
66+
key, ok := values[i].(string)
67+
if !ok {
68+
return nil, errors.New("dict keys must be strings")
69+
}
70+
dict[key] = values[i+1]
71+
}
72+
return dict, nil
73+
}
74+
5975
func generateFile(config Config, containers Context) bool {
6076
templatePath := config.Template
6177
tmpl, err := template.New(filepath.Base(templatePath)).Funcs(template.FuncMap{
@@ -65,6 +81,7 @@ func generateFile(config Config, containers Context) bool {
6581
"groupByMulti": groupByMulti,
6682
"split": strings.Split,
6783
"replace": strings.Replace,
84+
"dict": dict,
6885
}).ParseFiles(templatePath)
6986
if err != nil {
7087
log.Fatalf("unable to parse template: %s", err)

template_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,36 @@ func TestGroupByMulti(t *testing.T) {
9999
t.Fatalf("expected 2 got %s", groups["demo3.localhost"][0].ID)
100100
}
101101
}
102+
103+
func TestDict(t *testing.T) {
104+
containers := []*RuntimeContainer{
105+
&RuntimeContainer{
106+
Env: map[string]string{
107+
"VIRTUAL_HOST": "demo1.localhost",
108+
},
109+
ID: "1",
110+
},
111+
&RuntimeContainer{
112+
Env: map[string]string{
113+
"VIRTUAL_HOST": "demo1.localhost,demo3.localhost",
114+
},
115+
ID: "2",
116+
},
117+
&RuntimeContainer{
118+
Env: map[string]string{
119+
"VIRTUAL_HOST": "demo2.localhost",
120+
},
121+
ID: "3",
122+
},
123+
}
124+
d, err := dict("/", containers)
125+
if err != nil {
126+
t.Fatal(err)
127+
}
128+
if d["/"] == nil {
129+
t.Fatalf("did not find containers in dict: %s", d)
130+
}
131+
if d["MISSING"] != nil {
132+
t.Fail()
133+
}
134+
}

0 commit comments

Comments
 (0)