Skip to content

Commit e9a18ea

Browse files
committed
Add "keys" function
1 parent ad05c05 commit e9a18ea

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

template.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,25 @@ func hasSuffix(suffix, s string) bool {
7575
return strings.HasSuffix(s, suffix)
7676
}
7777

78+
func keys(input interface{}) (interface{}, error) {
79+
if input == nil {
80+
return nil, nil
81+
}
82+
83+
val := reflect.ValueOf(input)
84+
if val.Kind() != reflect.Map {
85+
return nil, fmt.Errorf("Cannot call keys on a non-map value: %v", input)
86+
}
87+
88+
vk := val.MapKeys()
89+
k := make([]interface{}, val.Len())
90+
for i, _ := range k {
91+
k[i] = vk[i].Interface()
92+
}
93+
94+
return k, nil
95+
}
96+
7897
func contains(item map[string]string, key string) bool {
7998
if _, ok := item[key]; ok {
8099
return true
@@ -195,6 +214,7 @@ func generateFile(config Config, containers Context) bool {
195214
"hasPrefix": hasPrefix,
196215
"hasSuffix": hasSuffix,
197216
"json": marshalJson,
217+
"keys": keys,
198218
"last": arrayLast,
199219
"replace": strings.Replace,
200220
"sha1": hashSha1,

template_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"bytes"
55
"encoding/json"
6+
"reflect"
67
"testing"
78
)
89

@@ -20,6 +21,59 @@ func TestContains(t *testing.T) {
2021
}
2122
}
2223

24+
func TestKeys(t *testing.T) {
25+
expected := "VIRTUAL_HOST"
26+
env := map[string]string{
27+
expected: "demo.local",
28+
}
29+
30+
k, err := keys(env)
31+
if err != nil {
32+
t.Fatalf("Error fetching keys: %v", err)
33+
}
34+
vk := reflect.ValueOf(k)
35+
if vk.Kind() == reflect.Invalid {
36+
t.Fatalf("Got invalid kind for keys: %v", vk)
37+
}
38+
39+
if len(env) != vk.Len() {
40+
t.Fatalf("Incorrect key count; expected %s, got %s", len(env), vk.Len())
41+
}
42+
43+
got := vk.Index(0).Interface()
44+
if expected != got {
45+
t.Fatalf("Incorrect key found; expected %s, got %s", expected, got)
46+
}
47+
}
48+
49+
func TestKeysEmpty(t *testing.T) {
50+
input := map[string]int{}
51+
52+
k, err := keys(input)
53+
if err != nil {
54+
t.Fatalf("Error fetching keys: %v", err)
55+
}
56+
vk := reflect.ValueOf(k)
57+
if vk.Kind() == reflect.Invalid {
58+
t.Fatalf("Got invalid kind for keys: %v", vk)
59+
}
60+
61+
if len(input) != vk.Len() {
62+
t.Fatalf("Incorrect key count; expected %s, got %s", len(input), vk.Len())
63+
}
64+
}
65+
66+
func TestKeysNil(t *testing.T) {
67+
k, err := keys(nil)
68+
if err != nil {
69+
t.Fatalf("Error fetching keys: %v", err)
70+
}
71+
vk := reflect.ValueOf(k)
72+
if vk.Kind() != reflect.Invalid {
73+
t.Fatalf("Got invalid kind for keys: %v", vk)
74+
}
75+
}
76+
2377
func TestGroupByExistingKey(t *testing.T) {
2478
containers := []*RuntimeContainer{
2579
&RuntimeContainer{

0 commit comments

Comments
 (0)