Skip to content

Commit

Permalink
Add "keys" function
Browse files Browse the repository at this point in the history
  • Loading branch information
md5 committed Dec 2, 2014
1 parent ad05c05 commit e9a18ea
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
20 changes: 20 additions & 0 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,25 @@ func hasSuffix(suffix, s string) bool {
return strings.HasSuffix(s, suffix)
}

func keys(input interface{}) (interface{}, error) {
if input == nil {
return nil, nil
}

val := reflect.ValueOf(input)
if val.Kind() != reflect.Map {
return nil, fmt.Errorf("Cannot call keys on a non-map value: %v", input)
}

vk := val.MapKeys()
k := make([]interface{}, val.Len())
for i, _ := range k {
k[i] = vk[i].Interface()
}

return k, nil
}

func contains(item map[string]string, key string) bool {
if _, ok := item[key]; ok {
return true
Expand Down Expand Up @@ -195,6 +214,7 @@ func generateFile(config Config, containers Context) bool {
"hasPrefix": hasPrefix,
"hasSuffix": hasSuffix,
"json": marshalJson,
"keys": keys,
"last": arrayLast,
"replace": strings.Replace,
"sha1": hashSha1,
Expand Down
54 changes: 54 additions & 0 deletions template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"bytes"
"encoding/json"
"reflect"
"testing"
)

Expand All @@ -20,6 +21,59 @@ func TestContains(t *testing.T) {
}
}

func TestKeys(t *testing.T) {
expected := "VIRTUAL_HOST"
env := map[string]string{
expected: "demo.local",
}

k, err := keys(env)
if err != nil {
t.Fatalf("Error fetching keys: %v", err)
}
vk := reflect.ValueOf(k)
if vk.Kind() == reflect.Invalid {
t.Fatalf("Got invalid kind for keys: %v", vk)
}

if len(env) != vk.Len() {
t.Fatalf("Incorrect key count; expected %s, got %s", len(env), vk.Len())
}

got := vk.Index(0).Interface()
if expected != got {
t.Fatalf("Incorrect key found; expected %s, got %s", expected, got)
}
}

func TestKeysEmpty(t *testing.T) {
input := map[string]int{}

k, err := keys(input)
if err != nil {
t.Fatalf("Error fetching keys: %v", err)
}
vk := reflect.ValueOf(k)
if vk.Kind() == reflect.Invalid {
t.Fatalf("Got invalid kind for keys: %v", vk)
}

if len(input) != vk.Len() {
t.Fatalf("Incorrect key count; expected %s, got %s", len(input), vk.Len())
}
}

func TestKeysNil(t *testing.T) {
k, err := keys(nil)
if err != nil {
t.Fatalf("Error fetching keys: %v", err)
}
vk := reflect.ValueOf(k)
if vk.Kind() != reflect.Invalid {
t.Fatalf("Got invalid kind for keys: %v", vk)
}
}

func TestGroupByExistingKey(t *testing.T) {
containers := []*RuntimeContainer{
&RuntimeContainer{
Expand Down

0 comments on commit e9a18ea

Please sign in to comment.