functions.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package sprig
  2. import (
  3. "errors"
  4. "math/rand"
  5. "path"
  6. "path/filepath"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. ttemplate "text/template"
  11. "time"
  12. util "github.com/Masterminds/goutils"
  13. "github.com/huandu/xstrings"
  14. "github.com/shopspring/decimal"
  15. )
  16. // TxtFuncMap returns a 'text/template'.FuncMap
  17. func TxtFuncMap() ttemplate.FuncMap {
  18. return ttemplate.FuncMap(GenericFuncMap())
  19. }
  20. // GenericFuncMap returns a copy of the basic function map as a map[string]interface{}.
  21. func GenericFuncMap() map[string]interface{} {
  22. gfm := make(map[string]interface{}, len(genericMap))
  23. for k, v := range genericMap {
  24. gfm[k] = v
  25. }
  26. return gfm
  27. }
  28. var genericMap = map[string]interface{}{
  29. "hello": func() string { return "Hello!" },
  30. // Date functions
  31. "ago": dateAgo,
  32. "date": date,
  33. "date_in_zone": dateInZone,
  34. "date_modify": dateModify,
  35. "dateInZone": dateInZone,
  36. "dateModify": dateModify,
  37. "duration": duration,
  38. "durationRound": durationRound,
  39. "htmlDate": htmlDate,
  40. "htmlDateInZone": htmlDateInZone,
  41. "must_date_modify": mustDateModify,
  42. "mustDateModify": mustDateModify,
  43. "mustToDate": mustToDate,
  44. "now": time.Now,
  45. "toDate": toDate,
  46. "unixEpoch": unixEpoch,
  47. // Strings
  48. "abbrev": abbrev,
  49. "abbrevboth": abbrevboth,
  50. "trunc": trunc,
  51. "trim": strings.TrimSpace,
  52. "upper": strings.ToUpper,
  53. "lower": strings.ToLower,
  54. "title": strings.Title,
  55. "untitle": untitle,
  56. "substr": substring,
  57. "repeat": func(count int, str string) string { return strings.Repeat(str, count) },
  58. "trimall": func(a, b string) string { return strings.Trim(b, a) },
  59. "trimAll": func(a, b string) string { return strings.Trim(b, a) },
  60. "trimSuffix": func(a, b string) string { return strings.TrimSuffix(b, a) },
  61. "trimPrefix": func(a, b string) string { return strings.TrimPrefix(b, a) },
  62. "nospace": util.DeleteWhiteSpace,
  63. "initials": initials,
  64. "randAlphaNum": randAlphaNumeric,
  65. "randAlpha": randAlpha,
  66. "randAscii": randAscii,
  67. "randNumeric": randNumeric,
  68. "swapcase": util.SwapCase,
  69. "shuffle": xstrings.Shuffle,
  70. "snakecase": xstrings.ToSnakeCase,
  71. "camelcase": xstrings.ToPascalCase,
  72. "kebabcase": xstrings.ToKebabCase,
  73. "wrap": func(l int, s string) string { return util.Wrap(s, l) },
  74. "wrapWith": func(l int, sep, str string) string { return util.WrapCustom(str, l, sep, true) },
  75. "contains": func(substr string, str string) bool { return strings.Contains(str, substr) },
  76. "hasPrefix": func(substr string, str string) bool { return strings.HasPrefix(str, substr) },
  77. "hasSuffix": func(substr string, str string) bool { return strings.HasSuffix(str, substr) },
  78. "quote": quote,
  79. "squote": squote,
  80. "cat": cat,
  81. "indent": indent,
  82. "nindent": nindent,
  83. "replace": replace,
  84. "plural": plural,
  85. "sha1sum": sha1sum,
  86. "sha256sum": sha256sum,
  87. "sha512sum": sha512sum,
  88. "adler32sum": adler32sum,
  89. "toString": strval,
  90. "atoi": func(a string) int { i, _ := strconv.Atoi(a); return i },
  91. "int64": toInt64,
  92. "int": toInt,
  93. "float64": toFloat64,
  94. "seq": seq,
  95. "toDecimal": toDecimal,
  96. "split": split,
  97. "splitList": func(sep, orig string) []string { return strings.Split(orig, sep) },
  98. "splitn": splitn,
  99. "toStrings": strslice,
  100. "until": until,
  101. "untilStep": untilStep,
  102. "add1": func(i interface{}) int64 { return toInt64(i) + 1 },
  103. "add": func(i ...interface{}) int64 {
  104. var a int64 = 0
  105. for _, b := range i {
  106. a += toInt64(b)
  107. }
  108. return a
  109. },
  110. "sub": func(a, b interface{}) int64 { return toInt64(a) - toInt64(b) },
  111. "div": func(a, b interface{}) int64 { return toInt64(a) / toInt64(b) },
  112. "mod": func(a, b interface{}) int64 { return toInt64(a) % toInt64(b) },
  113. "mul": func(a interface{}, v ...interface{}) int64 {
  114. val := toInt64(a)
  115. for _, b := range v {
  116. val = val * toInt64(b)
  117. }
  118. return val
  119. },
  120. "randInt": func(min, max int) int { return rand.Intn(max-min) + min },
  121. "add1f": func(i interface{}) float64 {
  122. return execDecimalOp(i, []interface{}{1}, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Add(d2) })
  123. },
  124. "addf": func(i ...interface{}) float64 {
  125. a := interface{}(float64(0))
  126. return execDecimalOp(a, i, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Add(d2) })
  127. },
  128. "subf": func(a interface{}, v ...interface{}) float64 {
  129. return execDecimalOp(a, v, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Sub(d2) })
  130. },
  131. "divf": func(a interface{}, v ...interface{}) float64 {
  132. return execDecimalOp(a, v, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Div(d2) })
  133. },
  134. "mulf": func(a interface{}, v ...interface{}) float64 {
  135. return execDecimalOp(a, v, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Mul(d2) })
  136. },
  137. "biggest": max,
  138. "max": max,
  139. "min": min,
  140. "maxf": maxf,
  141. "minf": minf,
  142. "ceil": ceil,
  143. "floor": floor,
  144. "round": round,
  145. "join": join,
  146. "sortAlpha": sortAlpha,
  147. // Defaults
  148. "default": dfault,
  149. "empty": empty,
  150. "coalesce": coalesce,
  151. "all": all,
  152. "any": any,
  153. "compact": compact,
  154. "mustCompact": mustCompact,
  155. "fromJson": fromJson,
  156. "toJson": toJson,
  157. "toPrettyJson": toPrettyJson,
  158. "toRawJson": toRawJson,
  159. "mustFromJson": mustFromJson,
  160. "mustToJson": mustToJson,
  161. "mustToPrettyJson": mustToPrettyJson,
  162. "mustToRawJson": mustToRawJson,
  163. "ternary": ternary,
  164. "deepCopy": deepCopy,
  165. "mustDeepCopy": mustDeepCopy,
  166. // Reflection
  167. "typeOf": typeOf,
  168. "typeIs": typeIs,
  169. "typeIsLike": typeIsLike,
  170. "kindOf": kindOf,
  171. "kindIs": kindIs,
  172. "deepEqual": reflect.DeepEqual,
  173. // Paths:
  174. "base": path.Base,
  175. "dir": path.Dir,
  176. "clean": path.Clean,
  177. "ext": path.Ext,
  178. "isAbs": path.IsAbs,
  179. // Filepaths:
  180. "osBase": filepath.Base,
  181. "osClean": filepath.Clean,
  182. "osDir": filepath.Dir,
  183. "osExt": filepath.Ext,
  184. "osIsAbs": filepath.IsAbs,
  185. // Encoding:
  186. "b64enc": base64encode,
  187. "b64dec": base64decode,
  188. "b32enc": base32encode,
  189. "b32dec": base32decode,
  190. // Data Structures:
  191. "tuple": list,
  192. "list": list,
  193. "dict": dict,
  194. "get": get,
  195. "set": set,
  196. "unset": unset,
  197. "hasKey": hasKey,
  198. "pluck": pluck,
  199. "keys": keys,
  200. "pick": pick,
  201. "omit": omit,
  202. "merge": merge,
  203. "mergeOverwrite": mergeOverwrite,
  204. "mustMerge": mustMerge,
  205. "mustMergeOverwrite": mustMergeOverwrite,
  206. "values": values,
  207. "append": push, "push": push,
  208. "mustAppend": mustPush, "mustPush": mustPush,
  209. "prepend": prepend,
  210. "mustPrepend": mustPrepend,
  211. "first": first,
  212. "mustFirst": mustFirst,
  213. "rest": rest,
  214. "mustRest": mustRest,
  215. "last": last,
  216. "mustLast": mustLast,
  217. "initial": initial,
  218. "mustInitial": mustInitial,
  219. "reverse": reverse,
  220. "mustReverse": mustReverse,
  221. "uniq": uniq,
  222. "mustUniq": mustUniq,
  223. "without": without,
  224. "mustWithout": mustWithout,
  225. "has": has,
  226. "mustHas": mustHas,
  227. "slice": slice,
  228. "mustSlice": mustSlice,
  229. "concat": concat,
  230. "dig": dig,
  231. "chunk": chunk,
  232. "mustChunk": mustChunk,
  233. // Crypto:
  234. "bcrypt": bcrypt,
  235. "htpasswd": htpasswd,
  236. "genPrivateKey": generatePrivateKey,
  237. "derivePassword": derivePassword,
  238. "buildCustomCert": buildCustomCertificate,
  239. "genCA": generateCertificateAuthority,
  240. "genCAWithKey": generateCertificateAuthorityWithPEMKey,
  241. "genSelfSignedCert": generateSelfSignedCertificate,
  242. "genSelfSignedCertWithKey": generateSelfSignedCertificateWithPEMKey,
  243. "genSignedCert": generateSignedCertificate,
  244. "genSignedCertWithKey": generateSignedCertificateWithPEMKey,
  245. "encryptAES": encryptAES,
  246. "decryptAES": decryptAES,
  247. "randBytes": randBytes,
  248. // UUIDs:
  249. "uuidv4": uuidv4,
  250. // SemVer:
  251. "semver": semver,
  252. "semverCompare": semverCompare,
  253. // Flow Control:
  254. "fail": func(msg string) (string, error) { return "", errors.New(msg) },
  255. // Regex
  256. "regexMatch": regexMatch,
  257. "mustRegexMatch": mustRegexMatch,
  258. "regexFindAll": regexFindAll,
  259. "mustRegexFindAll": mustRegexFindAll,
  260. "regexFind": regexFind,
  261. "mustRegexFind": mustRegexFind,
  262. "regexReplaceAll": regexReplaceAll,
  263. "mustRegexReplaceAll": mustRegexReplaceAll,
  264. "regexReplaceAllLiteral": regexReplaceAllLiteral,
  265. "mustRegexReplaceAllLiteral": mustRegexReplaceAllLiteral,
  266. "regexSplit": regexSplit,
  267. "mustRegexSplit": mustRegexSplit,
  268. "regexQuoteMeta": regexQuoteMeta,
  269. // URLs:
  270. "urlParse": urlParse,
  271. "urlJoin": urlJoin,
  272. }