Skip to content

Lift restriction on the function contains #343

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 1 commit into from
Apr 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ For example, this is a JSON version of an emitted RuntimeContainer struct:

* *`closest $array $value`*: Returns the longest matching substring in `$array` that matches `$value`
* *`coalesce ...`*: Returns the first non-nil argument.
* *`contains $map $key`*: Returns `true` if `$map` contains `$key`. Takes maps from `string` to `string`.
* *`contains $map $key`*: Returns `true` if `$map` contains `$key`. Takes maps from `string` to any type.
* *`dict $key $value ...`*: Creates a map from a list of pairs. Each `$key` value must be a `string`, but the `$value` can be any type (or `nil`). Useful for passing more than one value as a pipeline context to subtemplates.
* *`dir $path`*: Returns an array of filenames in the specified `$path`.
* *`exists $path`*: Returns `true` if `$path` refers to an existing file or directory. Takes a string.
Expand Down
16 changes: 13 additions & 3 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,20 @@ func intersect(l1, l2 []string) []string {
return keys
}

func contains(item map[string]string, key string) bool {
if _, ok := item[key]; ok {
return true
func contains(input interface{}, key interface{}) bool {
if input == nil {
return false
}

val := reflect.ValueOf(input)
if val.Kind() == reflect.Map {
for _, k := range val.MapKeys() {
if k.Interface() == key {
return true
}
}
}

return false
}

Expand Down
20 changes: 19 additions & 1 deletion template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (tests templateTestList) run(t *testing.T, prefix string) {
}
}

func TestContains(t *testing.T) {
func TestContainsString(t *testing.T) {
env := map[string]string{
"PORT": "1234",
}
Expand All @@ -47,6 +47,24 @@ func TestContains(t *testing.T) {
}
}

func TestContainsInteger(t *testing.T) {
env := map[int]int{
42: 1234,
}

if !contains(env, 42) {
t.Fail()
}

if contains(env, "WRONG TYPE") {
t.Fail()
}

if contains(env, 24) {
t.Fail()
}
}

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