Skip to content
This repository has been archived by the owner on Apr 18, 2024. It is now read-only.

Commit

Permalink
Merge pull request #37 from tobernguyen/fix-when-not-going-through-te…
Browse files Browse the repository at this point in the history
…mplate-engine

fix: "when" not going through template engine
  • Loading branch information
moshloop authored Apr 21, 2021
2 parents 95002bb + 3e60c7e commit b6de52c
Showing 1 changed file with 12 additions and 19 deletions.
31 changes: 12 additions & 19 deletions k8s/template_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"text/template"

Expand Down Expand Up @@ -438,7 +439,17 @@ func (tm *TemplateManager) conditional(rawItem []byte, target map[string]interfa
return true, nil
}

return tm.GetBool(target, conditional.When)
tpl, err := template.New("").Funcs(tm.FuncMap).Parse(conditional.When)
if err != nil {
return false, fmt.Errorf("invalid template %s: %v", conditional.When, err)
}

var buf bytes.Buffer
if err := tpl.Execute(&buf, target); err != nil {
return false, fmt.Errorf("error executing template %s: %v", conditional.When, err)
}

return strconv.ParseBool(buf.String())
}

func (tm *TemplateManager) getNamespaces(ctx context.Context, copyToNamespaces templatev1.CopyToNamespaces) ([]string, error) {
Expand Down Expand Up @@ -510,24 +521,6 @@ func (tm *TemplateManager) JSONPath(object interface{}, jsonpath string) (*ForEa
return nil, errors.Errorf("field %s is not map or array", jsonpath)
}

func (tm *TemplateManager) GetBool(object interface{}, jsonpath string) (bool, error) {
jsonpath = strings.TrimPrefix(jsonpath, "{{")
jsonpath = strings.TrimSuffix(jsonpath, "}}")
jsonpath = strings.TrimPrefix(jsonpath, ".")
jsonObject, err := json.Marshal(object)
if err != nil {
return false, errors.Wrap(err, "failed to marshal json")
}

value := gjson.Get(string(jsonObject), jsonpath)

if !value.Exists() {
return false, errors.Wrapf(err, "failed to find path %s", jsonpath)
}

return value.Bool(), nil
}

func labelSelectorToString(l metav1.LabelSelector) (string, error) {
labelMap, err := metav1.LabelSelectorAsMap(&l)
if err != nil {
Expand Down

0 comments on commit b6de52c

Please sign in to comment.