From e40134f6e50ef9f81fac84e3c57a04a9b2e70a93 Mon Sep 17 00:00:00 2001 From: Bruno Almeida Date: Mon, 11 Mar 2024 09:32:49 +0000 Subject: [PATCH] Create omitted function --- pkg/engine/funcs.go | 8 ++++++++ pkg/engine/funcs_test.go | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/pkg/engine/funcs.go b/pkg/engine/funcs.go index 431f82f63..234566d74 100644 --- a/pkg/engine/funcs.go +++ b/pkg/engine/funcs.go @@ -68,6 +68,8 @@ func funcMap() template.FuncMap { "fromJson": fromJSON, "fromJsonArray": fromJSONArray, + "omitted": omitted, + // Duration helpers "mustToDuration": mustToDuration, "durationSeconds": durationSeconds, @@ -269,6 +271,12 @@ func fromJSONArray(str string) []any { return a } +func omitted(a, b interface{}) interface{} { + if b == nil { + return a + } + return b + // ----------------------------------------------------------------------------- // Duration helpers (numeric and time.Duration returns) // ----------------------------------------------------------------------------- diff --git a/pkg/engine/funcs_test.go b/pkg/engine/funcs_test.go index cf6a8d5c9..a17fc7e34 100644 --- a/pkg/engine/funcs_test.go +++ b/pkg/engine/funcs_test.go @@ -125,6 +125,14 @@ keyInElement1 = "valueInElement1"`, tpl: `{{ fromYamlArray . }}`, expect: `[error unmarshaling JSON: while decoding JSON: json: cannot unmarshal object into Go value of type []interface {}]`, vars: `hello: world`, + }, { + tpl: `{{ .hello | omitted 'yes' }}`, + expect: `false`, + vars: map[string]bool{"hello": false}, + }, { + tpl: `{{ .value | omitted 'yes' }}`, + expect: `yes`, + vars: map[string]bool{"hello": false}, }, { // This should never result in a network lookup. Regression for #7955 tpl: `{{ lookup "v1" "Namespace" "" "unlikelynamespace99999999" }}`,