Skip to content

Commit

Permalink
Custom implement ternary + default
Browse files Browse the repository at this point in the history
Looks like the monkeypatching has some weird golang bug so just directly implement these
  • Loading branch information
michaeljguarino committed Apr 30, 2024
1 parent eb29e2c commit 96cedd4
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 9 deletions.
11 changes: 2 additions & 9 deletions pkg/manifests/template/raw.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
53 changes: 53 additions & 0 deletions pkg/manifests/template/utils.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package template

import (
"reflect"
"strings"

console "github.com/pluralsh/console-client-go"
Expand Down Expand Up @@ -31,3 +32,55 @@ func indent(v string, spaces int) string {
func nindent(v string, spaces int) string {
return "\n" + indent(v, spaces)
}

func coalesce(v ...interface{}) interface{} {
for _, val := range v {
if !empty(val) {
return val
}
}
return nil
}

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
}
}

0 comments on commit 96cedd4

Please sign in to comment.