Skip to content

Commit 91ed6da

Browse files
authored
Merge pull request #624 from nginx-proxy/cleanup-template-functions
refactor: cleanup template functions
2 parents 6a3e97a + bb71198 commit 91ed6da

File tree

4 files changed

+44
-147
lines changed

4 files changed

+44
-147
lines changed

README.md

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -398,23 +398,13 @@ For example, this is a JSON version of an emitted RuntimeContainer struct:
398398
- _`groupByLabelWithDefault $containers $label $defaultValue`_: Returns the same as `groupBy` but grouping by the given label's value. Containers that do not have the `$label` set are included in the map under the `$defaultValue` key.
399399
- _`include $file`_: Returns content of `$file`, and empty string if file reading error.
400400
- _`intersect $slice1 $slice2`_: Returns the strings that exist in both string slices.
401-
- _`json $value`_: Returns the JSON representation of `$value` as a `string`.
402401
- _`fromYaml $string` / `mustFromYaml $string`_: Similar to [Sprig's `fromJson` / `mustFromJson`](https://github.com/Masterminds/sprig/blob/master/docs/defaults.md#fromjson-mustfromjson), but for YAML.
403402
- _`toYaml $dict` / `mustToYaml $dict`_: Similar to [Sprig's `toJson` / `mustToJson`](https://github.com/Masterminds/sprig/blob/master/docs/defaults.md#tojson-musttojson), but for YAML.
404403
- _`keys $map`_: Returns the keys from `$map`. If `$map` is `nil`, a `nil` is returned. If `$map` is not a `map`, an error will be thrown.
405-
- _`parseBool $string`_: parseBool returns the boolean value represented by the string. It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error. Alias for [`strconv.ParseBool`](http://golang.org/pkg/strconv/#ParseBool)
406-
- _`replace $string $old $new $count`_: Replaces up to `$count` occurences of `$old` with `$new` in `$string`. Alias for [`strings.Replace`](http://golang.org/pkg/strings/#Replace)
407-
- _`sha1 $string`_: Returns the hexadecimal representation of the SHA1 hash of `$string`.
408-
- _`split $string $sep`_: Splits `$string` into a slice of substrings delimited by `$sep`. Alias for [`strings.Split`](http://golang.org/pkg/strings/#Split)
409-
- _`splitN $string $sep $count`_: Splits `$string` into a slice of substrings delimited by `$sep`, with number of substrings returned determined by `$count`. Alias for [`strings.SplitN`](https://golang.org/pkg/strings/#SplitN)
410404
- _`sortStringsAsc $strings`_: Returns a slice of strings `$strings` sorted in ascending order.
411405
- _`sortStringsDesc $strings`_: Returns a slice of strings `$strings` sorted in descending (reverse) order.
412406
- _`sortObjectsByKeysAsc $objects $fieldPath`_: Returns the array `$objects`, sorted in ascending order based on the values of a field path expression `$fieldPath`.
413407
- _`sortObjectsByKeysDesc $objects $fieldPath`_: Returns the array `$objects`, sorted in descending (reverse) order based on the values of a field path expression `$fieldPath`.
414-
- _`trimPrefix $prefix $string`_: If `$prefix` is a prefix of `$string`, return `$string` with `$prefix` trimmed from the beginning. Otherwise, return `$string` unchanged.
415-
- _`trimSuffix $suffix $string`_: If `$suffix` is a suffix of `$string`, return `$string` with `$suffix` trimmed from the end. Otherwise, return `$string` unchanged.
416-
- _`toLower $string`_: Replace capital letters in `$string` to lowercase.
417-
- _`toUpper $string`_: Replace lowercase letters in `$string` to uppercase.
418408
- _`when $condition $trueValue $falseValue`_: Returns the `$trueValue` when the `$condition` is `true` and the `$falseValue` otherwise
419409
- _`where $items $fieldPath $value`_: Filters an array or slice based on the values of a field path expression `$fieldPath`. A field path expression is a dot-delimited list of map keys or struct member names specifying the path from container to a nested value. Returns an array of items having that value.
420410
- _`whereNot $items $fieldPath $value`_: Filters an array or slice based on the values of a field path expression `$fieldPath`. A field path expression is a dot-delimited list of map keys or struct member names specifying the path from container to a nested value. Returns an array of items **not** having that value.
@@ -426,6 +416,30 @@ For example, this is a JSON version of an emitted RuntimeContainer struct:
426416
- _`whereLabelDoesNotExist $containers $label`_: Filters a slice of containers based on the non-existence of the label `$label`.
427417
- _`whereLabelValueMatches $containers $label $pattern`_: Filters a slice of containers based on the existence of the label `$label` with values matching the regular expression `$pattern`.
428418

419+
Sprig functions that have the same name as docker-gen function (but different behaviour) are made available with the `sprig` prefix:
420+
421+
- _`sprigCoalesce ...`_: Alias for Sprig's [`coalesce`](https://masterminds.github.io/sprig/defaults.html).
422+
- _`sprigContains $string $string`_: Alias for Sprig's [`contains`](https://masterminds.github.io/sprig/strings.html).
423+
- _`sprigDir $path`_: Alias for Sprig's [`dir`](https://masterminds.github.io/sprig/paths.html).
424+
- _`sprigReplace $old $new $string`_: Alias for Sprig's [`replace`](https://masterminds.github.io/sprig/strings.html).
425+
- _`sprigSplit $sep $string`_: Alias for Sprig's [`split`](https://masterminds.github.io/sprig/string_slice.html).
426+
- _`sprigSplitn $sep $count $string"`_: Alias for Sprig's [`splitn`](https://masterminds.github.io/sprig/string_slice.html).
427+
428+
Some functions are aliases for Go's [`strings`](https://pkg.go.dev/strings) package functions:
429+
430+
- _`parseBool $string`_: Alias for [`strconv.ParseBool`](http://golang.org/pkg/strconv/#ParseBool). Returns the boolean value represented by `$string`. It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error.
431+
- _`replace $string $old $new $count`_: Alias for [`strings.Replace`](http://golang.org/pkg/strings/#Replace). Replaces up to `$count` occurences of `$old` with `$new` in `$string`.
432+
- _`split $string $sep`_: Alias for [`strings.Split`](http://golang.org/pkg/strings/#Split). Splits `$string` into a slice of substrings delimited by `$sep`.
433+
- _`splitN $string $sep $count`_: Alias for [`strings.SplitN`](https://golang.org/pkg/strings/#SplitN). Splits `$string` into a slice of substrings delimited by `$sep`, with number of substrings returned determined by `$count`.
434+
- _`toLower $string`_: Alias for [`strings.ToLower`](https://pkg.go.dev/strings#ToLower). Replace capital letters in `$string` to lowercase.
435+
- _`toUpper $string`_: Alias for [`strings.ToUpper`](https://pkg.go.dev/strings#ToUpper). Replace lowercase letters in `$string` to uppercase.
436+
437+
Those have been aliased to Sprig functions with the same behaviour as the original docker-gen function:
438+
439+
- _`json $value`_: Alias for Sprig's [`mustToJson`](https://masterminds.github.io/sprig/defaults.html)
440+
- _`parseJson $string`_: Alias for Sprig's [`mustFromJson`](https://masterminds.github.io/sprig/defaults.html).
441+
- _`sha1 $string`_: Alias for Sprig's [`sha1sum`](https://masterminds.github.io/sprig/crypto.html).
442+
429443
---
430444

431445
### Examples

internal/template/functions.go

Lines changed: 0 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
package template
22

33
import (
4-
"bytes"
5-
"crypto/sha1"
6-
"encoding/json"
74
"fmt"
8-
"io"
95
"log"
106
"os"
117
"reflect"
@@ -81,29 +77,6 @@ func contains(input interface{}, key interface{}) bool {
8177
return false
8278
}
8379

84-
func hashSha1(input string) string {
85-
h := sha1.New()
86-
io.WriteString(h, input)
87-
return fmt.Sprintf("%x", h.Sum(nil))
88-
}
89-
90-
func marshalJson(input interface{}) (string, error) {
91-
var buf bytes.Buffer
92-
enc := json.NewEncoder(&buf)
93-
if err := enc.Encode(input); err != nil {
94-
return "", err
95-
}
96-
return strings.TrimSuffix(buf.String(), "\n"), nil
97-
}
98-
99-
func unmarshalJson(input string) (interface{}, error) {
100-
var v interface{}
101-
if err := json.Unmarshal([]byte(input), &v); err != nil {
102-
return nil, err
103-
}
104-
return v, nil
105-
}
106-
10780
// arrayClosest find the longest matching substring in values
10881
// that matches input
10982
func arrayClosest(values []string, input string) string {
@@ -140,26 +113,6 @@ func coalesce(input ...interface{}) interface{} {
140113
return nil
141114
}
142115

143-
// trimPrefix returns a string without the prefix, if present
144-
func trimPrefix(prefix, s string) string {
145-
return strings.TrimPrefix(s, prefix)
146-
}
147-
148-
// trimSuffix returns a string without the suffix, if present
149-
func trimSuffix(suffix, s string) string {
150-
return strings.TrimSuffix(s, suffix)
151-
}
152-
153-
// toLower return the string in lower case
154-
func toLower(s string) string {
155-
return strings.ToLower(s)
156-
}
157-
158-
// toUpper return the string in upper case
159-
func toUpper(s string) string {
160-
return strings.ToUpper(s)
161-
}
162-
163116
// when returns the trueValue when the condition is true and the falseValue otherwise
164117
func when(condition bool, trueValue, falseValue interface{}) interface{} {
165118
if condition {

internal/template/functions_test.go

Lines changed: 0 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
package template
22

33
import (
4-
"bytes"
5-
"encoding/json"
64
"os"
75
"path"
86
"reflect"
97
"testing"
108

11-
"github.com/nginx-proxy/docker-gen/internal/context"
129
"github.com/stretchr/testify/assert"
1310
)
1411

@@ -130,85 +127,6 @@ func TestSplitN(t *testing.T) {
130127
tests.run(t)
131128
}
132129

133-
func TestTrimPrefix(t *testing.T) {
134-
const prefix = "tcp://"
135-
const str = "tcp://127.0.0.1:2375"
136-
const trimmed = "127.0.0.1:2375"
137-
got := trimPrefix(prefix, str)
138-
if got != trimmed {
139-
t.Fatalf("expected trimPrefix(%s,%s) to be %s, got %s", prefix, str, trimmed, got)
140-
}
141-
}
142-
143-
func TestTrimSuffix(t *testing.T) {
144-
const suffix = ".local"
145-
const str = "myhost.local"
146-
const trimmed = "myhost"
147-
got := trimSuffix(suffix, str)
148-
if got != trimmed {
149-
t.Fatalf("expected trimSuffix(%s,%s) to be %s, got %s", suffix, str, trimmed, got)
150-
}
151-
}
152-
153-
func TestToLower(t *testing.T) {
154-
const str = ".RaNd0m StrinG_"
155-
const lowered = ".rand0m string_"
156-
assert.Equal(t, lowered, toLower(str), "Unexpected value from toLower()")
157-
}
158-
159-
func TestToUpper(t *testing.T) {
160-
const str = ".RaNd0m StrinG_"
161-
const uppered = ".RAND0M STRING_"
162-
assert.Equal(t, uppered, toUpper(str), "Unexpected value from toUpper()")
163-
}
164-
165-
func TestSha1(t *testing.T) {
166-
sum := hashSha1("/path")
167-
if sum != "4f26609ad3f5185faaa9edf1e93aa131e2131352" {
168-
t.Fatal("Incorrect SHA1 sum")
169-
}
170-
}
171-
172-
func TestJson(t *testing.T) {
173-
containers := []*context.RuntimeContainer{
174-
{
175-
Env: map[string]string{
176-
"VIRTUAL_HOST": "demo1.localhost",
177-
},
178-
ID: "1",
179-
},
180-
{
181-
Env: map[string]string{
182-
"VIRTUAL_HOST": "demo1.localhost,demo3.localhost",
183-
},
184-
ID: "2",
185-
},
186-
{
187-
Env: map[string]string{
188-
"VIRTUAL_HOST": "demo2.localhost",
189-
},
190-
ID: "3",
191-
},
192-
}
193-
output, err := marshalJson(containers)
194-
if err != nil {
195-
t.Fatal(err)
196-
}
197-
198-
buf := bytes.NewBufferString(output)
199-
dec := json.NewDecoder(buf)
200-
if err != nil {
201-
t.Fatal(err)
202-
}
203-
var decoded []*context.RuntimeContainer
204-
if err := dec.Decode(&decoded); err != nil {
205-
t.Fatal(err)
206-
}
207-
if len(decoded) != len(containers) {
208-
t.Fatalf("Incorrect unmarshaled container count. Expected %d, got %d.", len(containers), len(decoded))
209-
}
210-
}
211-
212130
func TestParseJson(t *testing.T) {
213131
tests := templateTestList{
214132
{`{{parseJson .}}`, `null`, `<no value>`},

internal/template/template.go

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,10 @@ func newTemplate(name string) *template.Template {
5757
}
5858
return buf.String(), nil
5959
}
60-
tmpl.Funcs(sprig.TxtFuncMap()).Funcs(template.FuncMap{
60+
61+
sprigFuncMap := sprig.TxtFuncMap()
62+
63+
tmpl.Funcs(sprigFuncMap).Funcs(template.FuncMap{
6164
"closest": arrayClosest,
6265
"coalesce": coalesce,
6366
"comment": comment,
@@ -71,29 +74,24 @@ func newTemplate(name string) *template.Template {
7174
"groupByMulti": groupByMulti,
7275
"groupByLabel": groupByLabel,
7376
"groupByLabelWithDefault": groupByLabelWithDefault,
74-
"json": marshalJson,
7577
"include": include,
7678
"intersect": intersect,
7779
"keys": keys,
7880
"replace": strings.Replace,
7981
"parseBool": strconv.ParseBool,
80-
"parseJson": unmarshalJson,
8182
"fromYaml": fromYaml,
8283
"toYaml": toYaml,
8384
"mustFromYaml": mustFromYaml,
8485
"mustToYaml": mustToYaml,
8586
"queryEscape": url.QueryEscape,
86-
"sha1": hashSha1,
8787
"split": strings.Split,
8888
"splitN": strings.SplitN,
8989
"sortStringsAsc": sortStringsAsc,
9090
"sortStringsDesc": sortStringsDesc,
9191
"sortObjectsByKeysAsc": sortObjectsByKeysAsc,
9292
"sortObjectsByKeysDesc": sortObjectsByKeysDesc,
93-
"trimPrefix": trimPrefix,
94-
"trimSuffix": trimSuffix,
95-
"toLower": toLower,
96-
"toUpper": toUpper,
93+
"toLower": strings.ToLower,
94+
"toUpper": strings.ToUpper,
9795
"when": when,
9896
"where": where,
9997
"whereNot": whereNot,
@@ -104,7 +102,21 @@ func newTemplate(name string) *template.Template {
104102
"whereLabelExists": whereLabelExists,
105103
"whereLabelDoesNotExist": whereLabelDoesNotExist,
106104
"whereLabelValueMatches": whereLabelValueMatches,
105+
106+
// legacy docker-gen template function aliased to their Sprig clone
107+
"json": sprigFuncMap["mustToJson"],
108+
"parseJson": sprigFuncMap["mustFromJson"],
109+
"sha1": sprigFuncMap["sha1sum"],
110+
111+
// aliases to sprig template functions masked by docker-gen functions with the same name
112+
"sprigCoalesce": sprigFuncMap["coalesce"],
113+
"sprigContains": sprigFuncMap["contains"],
114+
"sprigDir": sprigFuncMap["dir"],
115+
"sprigReplace": sprigFuncMap["replace"],
116+
"sprigSplit": sprigFuncMap["split"],
117+
"sprigSplitn": sprigFuncMap["splitn"],
107118
})
119+
108120
return tmpl
109121
}
110122

0 commit comments

Comments
 (0)