defaults.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package sprig
  2. import (
  3. "encoding/json"
  4. "reflect"
  5. )
  6. // dfault checks whether `given` is set, and returns default if not set.
  7. //
  8. // This returns `d` if `given` appears not to be set, and `given` otherwise.
  9. //
  10. // For numeric types 0 is unset.
  11. // For strings, maps, arrays, and slices, len() = 0 is considered unset.
  12. // For bool, false is unset.
  13. // Structs are never considered unset.
  14. //
  15. // For everything else, including pointers, a nil value is unset.
  16. func dfault(d interface{}, given ...interface{}) interface{} {
  17. if empty(given) || empty(given[0]) {
  18. return d
  19. }
  20. return given[0]
  21. }
  22. // empty returns true if the given value has the zero value for its type.
  23. func empty(given interface{}) bool {
  24. g := reflect.ValueOf(given)
  25. if !g.IsValid() {
  26. return true
  27. }
  28. // Basically adapted from text/template.isTrue
  29. switch g.Kind() {
  30. default:
  31. return g.IsNil()
  32. case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
  33. return g.Len() == 0
  34. case reflect.Bool:
  35. return g.Bool() == false
  36. case reflect.Complex64, reflect.Complex128:
  37. return g.Complex() == 0
  38. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  39. return g.Int() == 0
  40. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  41. return g.Uint() == 0
  42. case reflect.Float32, reflect.Float64:
  43. return g.Float() == 0
  44. case reflect.Struct:
  45. return false
  46. }
  47. }
  48. // coalesce returns the first non-empty value.
  49. func coalesce(v ...interface{}) interface{} {
  50. for _, val := range v {
  51. if !empty(val) {
  52. return val
  53. }
  54. }
  55. return nil
  56. }
  57. // toJson encodes an item into a JSON string
  58. func toJson(v interface{}) string {
  59. output, _ := json.Marshal(v)
  60. return string(output)
  61. }
  62. // toPrettyJson encodes an item into a pretty (indented) JSON string
  63. func toPrettyJson(v interface{}) string {
  64. output, _ := json.MarshalIndent(v, "", " ")
  65. return string(output)
  66. }
  67. // ternary returns the first value if the last value is true, otherwise returns the second value.
  68. func ternary(vt interface{}, vf interface{}, v bool) interface{} {
  69. if v {
  70. return vt
  71. }
  72. return vf
  73. }