Skip to content

Commit

Permalink
Merge pull request #5 from blendle/required
Browse files Browse the repository at this point in the history
add "required" template function
  • Loading branch information
JeanMertz authored Sep 22, 2017
2 parents 0df26bf + e140a0c commit f5da900
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
12 changes: 12 additions & 0 deletions epp/epp.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package epp

import (
"bytes"
"fmt"
"text/template"

"github.com/Masterminds/sprig"
Expand All @@ -20,6 +21,17 @@ func Parse(input []byte) ([]byte, error) {
}
return buf.String(), nil
},

"required": func(warn string, val interface{}) (interface{}, error) {
if val == nil {
return val, fmt.Errorf(warn)
} else if _, ok := val.(string); ok {
if val == "" {
return val, fmt.Errorf(warn)
}
}
return val, nil
},
}

tpl, err := t.Funcs(sprig.TxtFuncMap()).Funcs(funcMap).Parse(string(input))
Expand Down
29 changes: 29 additions & 0 deletions epp/epp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package epp
import (
"fmt"
"os"
"strings"
"testing"
)

Expand Down Expand Up @@ -65,3 +66,31 @@ hello WORLD`
t.Errorf("bad expansion: expected '%s', got '%s'", expected, res)
}
}

func TestRequired(t *testing.T) {
tpl := []byte(`{{ required "undefined" "hello" }}`)
expected := `hello`

res, err := Parse(tpl)

if err != nil {
t.Errorf("unexpected error '%s'", err)
}

if string(res) != expected {
t.Errorf("bad expansion: expected '%s', got '%s'", expected, res)
}
}

func TestRequired_Undefined(t *testing.T) {
tpl := []byte(`{{ required "undefined" .Undefined }}`)
_, err := Parse(tpl)

if err == nil {
t.Fatalf("expected error, got nil")
}

if !strings.Contains(err.Error(), "error calling required: undefined") {
t.Fatalf("unexpected error: %v", err)
}
}

0 comments on commit f5da900

Please sign in to comment.