From 2943ca172646340c4581219df0d402787e7deb58 Mon Sep 17 00:00:00 2001 From: michaeljguarino Date: Tue, 30 Apr 2024 16:50:33 -0400 Subject: [PATCH] fix: Custom implement ternary + default (#177) * Custom implement ternary + default Looks like the monkeypatching has some weird golang bug so just directly implement these * fix lint --- pkg/manifests/template/raw.go | 11 ++------- pkg/manifests/template/utils.go | 44 +++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/pkg/manifests/template/raw.go b/pkg/manifests/template/raw.go index df67ccc4..c1e8ffcf 100644 --- a/pkg/manifests/template/raw.go +++ b/pkg/manifests/template/raw.go @@ -42,15 +42,8 @@ func init() { liquidEngine.RegisterFilter("nindent", nindent) liquidEngine.RegisterFilter("replace", strings.ReplaceAll) - liquidEngine.RegisterFilter("default", func(a, b interface{}) interface{} { - fun := fncs["default"].(func(interface{}, interface{}) interface{}) - return fun(b, a) - }) - - liquidEngine.RegisterFilter("ternary", func(a, b, c interface{}) interface{} { - fun := fncs["ternary"].(func(interface{}, interface{}, interface{}) interface{}) - return fun(c, a, b) - }) + liquidEngine.RegisterFilter("default", dfault) + liquidEngine.RegisterFilter("ternary", ternary) } type raw struct { diff --git a/pkg/manifests/template/utils.go b/pkg/manifests/template/utils.go index 2f46ea69..6850cdda 100644 --- a/pkg/manifests/template/utils.go +++ b/pkg/manifests/template/utils.go @@ -1,6 +1,7 @@ package template import ( + "reflect" "strings" console "github.com/pluralsh/console-client-go" @@ -31,3 +32,46 @@ func indent(v string, spaces int) string { func nindent(v string, spaces int) string { return "\n" + indent(v, spaces) } + +func ternary(v bool, vt interface{}, vf interface{}) interface{} { + if v { + return vt + } + + return vf +} + +func dfault(v1, v2 interface{}) interface{} { + if empty(v1) { + return v2 + } + + return v1 +} + +func empty(given interface{}) bool { + g := reflect.ValueOf(given) + if !g.IsValid() { + return true + } + + // Basically adapted from text/template.isTrue + switch g.Kind() { + default: + return g.IsNil() + case reflect.Array, reflect.Slice, reflect.Map, reflect.String: + return g.Len() == 0 + case reflect.Bool: + return !g.Bool() + case reflect.Complex64, reflect.Complex128: + return g.Complex() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return g.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return g.Uint() == 0 + case reflect.Float32, reflect.Float64: + return g.Float() == 0 + case reflect.Struct: + return false + } +}