Debian Codegraph @

functions.go

raw ◀ ▶
1 Debian patch touch this file
1 package sprig
2
3 import (
4 "errors"
5 "html/template"
6 "math/rand"
7 "os"
8 "path"
9 "path/filepath"
10 "reflect"
11 "strconv"
12 "strings"
13 ttemplate "text/template"
14 "time"
15
16 util "github.com/Masterminds/goutils"
17 "github.com/huandu/xstrings"
18 "github.com/shopspring/decimal"
19 )
20
21 // FuncMap produces the function map.
22 //
23 // Use this to pass the functions into the template engine:
24 //
25 // tpl := template.New("foo").Funcs(sprig.FuncMap()))
26 //
27 func FuncMap() template.FuncMap {
28 return HtmlFuncMap()
29 }
30
31 // HermeticTxtFuncMap returns a 'text/template'.FuncMap with only repeatable functions.
32 func HermeticTxtFuncMap() ttemplate.FuncMap {
33 r := TxtFuncMap()
34 for _, name := range nonhermeticFunctions {
35 delete(r, name)
36 }
37 return r
38 }
39
40 // HermeticHtmlFuncMap returns an 'html/template'.Funcmap with only repeatable functions.
41 func HermeticHtmlFuncMap() template.FuncMap {
42 r := HtmlFuncMap()
43 for _, name := range nonhermeticFunctions {
44 delete(r, name)
45 }
46 return r
47 }
48
49 // TxtFuncMap returns a 'text/template'.FuncMap
50 func TxtFuncMap() ttemplate.FuncMap {
51 return ttemplate.FuncMap(GenericFuncMap())
52 }
53
54 // HtmlFuncMap returns an 'html/template'.Funcmap
55 func HtmlFuncMap() template.FuncMap {
56 return template.FuncMap(GenericFuncMap())
57 }
58
59 // GenericFuncMap returns a copy of the basic function map as a map[string]interface{}.
60 func GenericFuncMap() map[string]interface{} {
61 gfm := make(map[string]interface{}, len(genericMap))
62 for k, v := range genericMap {
63 gfm[k] = v
64 }
65 return gfm
66 }
67
68 // These functions are not guaranteed to evaluate to the same result for given input, because they
69 // refer to the environment or global state.
70 var nonhermeticFunctions = []string{
71 // Date functions
72 "date",
73 "date_in_zone",
74 "date_modify",
75 "now",
76 "htmlDate",
77 "htmlDateInZone",
78 "dateInZone",
79 "dateModify",
80
81 // Strings
82 "randAlphaNum",
83 "randAlpha",
84 "randAscii",
85 "randNumeric",
86 "randBytes",
87 "uuidv4",
88
89 // OS
90 "env",
91 "expandenv",
92
93 // Network
94 "getHostByName",
95 }
96
97 var genericMap = map[string]interface{}{
98 "hello": func() string { return "Hello!" },
99
100 // Date functions
101 "ago": dateAgo,
102 "date": date,
103 "date_in_zone": dateInZone,
104 "date_modify": dateModify,
105 "dateInZone": dateInZone,
106 "dateModify": dateModify,
107 "duration": duration,
108 "durationRound": durationRound,
109 "htmlDate": htmlDate,
110 "htmlDateInZone": htmlDateInZone,
111 "must_date_modify": mustDateModify,
112 "mustDateModify": mustDateModify,
113 "mustToDate": mustToDate,
114 "now": time.Now,
115 "toDate": toDate,
116 "unixEpoch": unixEpoch,
117
118 // Strings
119 "abbrev": abbrev,
120 "abbrevboth": abbrevboth,
121 "trunc": trunc,
122 "trim": strings.TrimSpace,
123 "upper": strings.ToUpper,
124 "lower": strings.ToLower,
125 "title": strings.Title,
126 "untitle": untitle,
127 "substr": substring,
128 // Switch order so that "foo" | repeat 5
129 "repeat": func(count int, str string) string { return strings.Repeat(str, count) },
130 // Deprecated: Use trimAll.
131 "trimall": func(a, b string) string { return strings.Trim(b, a) },
132 // Switch order so that "$foo" | trimall "$"
133 "trimAll": func(a, b string) string { return strings.Trim(b, a) },
134 "trimSuffix": func(a, b string) string { return strings.TrimSuffix(b, a) },
135 "trimPrefix": func(a, b string) string { return strings.TrimPrefix(b, a) },
136 "nospace": util.DeleteWhiteSpace,
137 "initials": initials,
138 "randAlphaNum": randAlphaNumeric,
139 "randAlpha": randAlpha,
140 "randAscii": randAscii,
141 "randNumeric": randNumeric,
142 "swapcase": util.SwapCase,
143 "shuffle": xstrings.Shuffle,
144 "snakecase": xstrings.ToSnakeCase,
•145 // camelcase used to call xstrings.ToCamelCase, but that function had a breaking change in version
146 // 1.5 that moved it from upper camel case to lower camel case. This is a breaking change for sprig.
147 // A new xstrings.ToPascalCase function was added that provided upper camel case.
148 "camelcase": xstrings.ToPascalCase,
149 "kebabcase": xstrings.ToKebabCase,
150 "wrap": func(l int, s string) string { return util.Wrap(s, l) },
151 "wrapWith": func(l int, sep, str string) string { return util.WrapCustom(str, l, sep, true) },
152 // Switch order so that "foobar" | contains "foo"
153 "contains": func(substr string, str string) bool { return strings.Contains(str, substr) },
154 "hasPrefix": func(substr string, str string) bool { return strings.HasPrefix(str, substr) },
155 "hasSuffix": func(substr string, str string) bool { return strings.HasSuffix(str, substr) },
156 "quote": quote,
157 "squote": squote,
158 "cat": cat,
159 "indent": indent,
160 "nindent": nindent,
161 "replace": replace,
162 "plural": plural,
163 "sha1sum": sha1sum,
164 "sha256sum": sha256sum,
165 "adler32sum": adler32sum,
166 "toString": strval,
167
168 // Wrap Atoi to stop errors.
169 "atoi": func(a string) int { i, _ := strconv.Atoi(a); return i },
170 "int64": toInt64,
171 "int": toInt,
172 "float64": toFloat64,
173 "seq": seq,
174 "toDecimal": toDecimal,
175
176 //"gt": func(a, b int) bool {return a > b},
177 //"gte": func(a, b int) bool {return a >= b},
178 //"lt": func(a, b int) bool {return a < b},
179 //"lte": func(a, b int) bool {return a <= b},
180
181 // split "/" foo/bar returns map[int]string{0: foo, 1: bar}
182 "split": split,
183 "splitList": func(sep, orig string) []string { return strings.Split(orig, sep) },
184 // splitn "/" foo/bar/fuu returns map[int]string{0: foo, 1: bar/fuu}
185 "splitn": splitn,
186 "toStrings": strslice,
187
188 "until": until,
189 "untilStep": untilStep,
190
191 // VERY basic arithmetic.
192 "add1": func(i interface{}) int64 { return toInt64(i) + 1 },
193 "add": func(i ...interface{}) int64 {
194 var a int64 = 0
195 for _, b := range i {
196 a += toInt64(b)
197 }
198 return a
199 },
200 "sub": func(a, b interface{}) int64 { return toInt64(a) - toInt64(b) },
201 "div": func(a, b interface{}) int64 { return toInt64(a) / toInt64(b) },
202 "mod": func(a, b interface{}) int64 { return toInt64(a) % toInt64(b) },
203 "mul": func(a interface{}, v ...interface{}) int64 {
204 val := toInt64(a)
205 for _, b := range v {
206 val = val * toInt64(b)
207 }
208 return val
209 },
210 "randInt": func(min, max int) int { return rand.Intn(max-min) + min },
211 "add1f": func(i interface{}) float64 {
212 return execDecimalOp(i, []interface{}{1}, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Add(d2) })
213 },
214 "addf": func(i ...interface{}) float64 {
215 a := interface{}(float64(0))
216 return execDecimalOp(a, i, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Add(d2) })
217 },
218 "subf": func(a interface{}, v ...interface{}) float64 {
219 return execDecimalOp(a, v, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Sub(d2) })
220 },
221 "divf": func(a interface{}, v ...interface{}) float64 {
222 return execDecimalOp(a, v, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Div(d2) })
223 },
224 "mulf": func(a interface{}, v ...interface{}) float64 {
225 return execDecimalOp(a, v, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Mul(d2) })
226 },
227 "biggest": max,
228 "max": max,
229 "min": min,
230 "maxf": maxf,
231 "minf": minf,
232 "ceil": ceil,
233 "floor": floor,
234 "round": round,
235
236 // string slices. Note that we reverse the order b/c that's better
237 // for template processing.
238 "join": join,
239 "sortAlpha": sortAlpha,
240
241 // Defaults
242 "default": dfault,
243 "empty": empty,
244 "coalesce": coalesce,
245 "all": all,
246 "any": any,
247 "compact": compact,
248 "mustCompact": mustCompact,
249 "fromJson": fromJson,
250 "toJson": toJson,
251 "toPrettyJson": toPrettyJson,
252 "toRawJson": toRawJson,
253 "mustFromJson": mustFromJson,
254 "mustToJson": mustToJson,
255 "mustToPrettyJson": mustToPrettyJson,
256 "mustToRawJson": mustToRawJson,
257 "ternary": ternary,
258 "deepCopy": deepCopy,
259 "mustDeepCopy": mustDeepCopy,
260
261 // Reflection
262 "typeOf": typeOf,
263 "typeIs": typeIs,
264 "typeIsLike": typeIsLike,
265 "kindOf": kindOf,
266 "kindIs": kindIs,
267 "deepEqual": reflect.DeepEqual,
268
269 // OS:
270 "env": os.Getenv,
271 "expandenv": os.ExpandEnv,
272
273 // Network:
274 "getHostByName": getHostByName,
275
276 // Paths:
277 "base": path.Base,
278 "dir": path.Dir,
279 "clean": path.Clean,
280 "ext": path.Ext,
281 "isAbs": path.IsAbs,
282
283 // Filepaths:
284 "osBase": filepath.Base,
285 "osClean": filepath.Clean,
286 "osDir": filepath.Dir,
287 "osExt": filepath.Ext,
288 "osIsAbs": filepath.IsAbs,
289
290 // Encoding:
291 "b64enc": base64encode,
292 "b64dec": base64decode,
293 "b32enc": base32encode,
294 "b32dec": base32decode,
295
296 // Data Structures:
297 "tuple": list, // FIXME: with the addition of append/prepend these are no longer immutable.
298 "list": list,
299 "dict": dict,
300 "get": get,
301 "set": set,
302 "unset": unset,
303 "hasKey": hasKey,
304 "pluck": pluck,
305 "keys": keys,
306 "pick": pick,
307 "omit": omit,
308 "merge": merge,
309 "mergeOverwrite": mergeOverwrite,
310 "mustMerge": mustMerge,
311 "mustMergeOverwrite": mustMergeOverwrite,
312 "values": values,
313
314 "append": push, "push": push,
315 "mustAppend": mustPush, "mustPush": mustPush,
316 "prepend": prepend,
317 "mustPrepend": mustPrepend,
318 "first": first,
319 "mustFirst": mustFirst,
320 "rest": rest,
321 "mustRest": mustRest,
322 "last": last,
323 "mustLast": mustLast,
324 "initial": initial,
325 "mustInitial": mustInitial,
326 "reverse": reverse,
327 "mustReverse": mustReverse,
328 "uniq": uniq,
329 "mustUniq": mustUniq,
330 "without": without,
331 "mustWithout": mustWithout,
332 "has": has,
333 "mustHas": mustHas,
334 "slice": slice,
335 "mustSlice": mustSlice,
336 "concat": concat,
337 "dig": dig,
338 "chunk": chunk,
339 "mustChunk": mustChunk,
340
341 // Crypto:
342 "bcrypt": bcrypt,
343 "htpasswd": htpasswd,
344 "genPrivateKey": generatePrivateKey,
345 "derivePassword": derivePassword,
346 "buildCustomCert": buildCustomCertificate,
347 "genCA": generateCertificateAuthority,
348 "genCAWithKey": generateCertificateAuthorityWithPEMKey,
349 "genSelfSignedCert": generateSelfSignedCertificate,
350 "genSelfSignedCertWithKey": generateSelfSignedCertificateWithPEMKey,
351 "genSignedCert": generateSignedCertificate,
352 "genSignedCertWithKey": generateSignedCertificateWithPEMKey,
353 "encryptAES": encryptAES,
354 "decryptAES": decryptAES,
355 "randBytes": randBytes,
356
357 // UUIDs:
358 "uuidv4": uuidv4,
359
360 // SemVer:
361 "semver": semver,
362 "semverCompare": semverCompare,
363
364 // Flow Control:
365 "fail": func(msg string) (string, error) { return "", errors.New(msg) },
366
367 // Regex
368 "regexMatch": regexMatch,
369 "mustRegexMatch": mustRegexMatch,
370 "regexFindAll": regexFindAll,
371 "mustRegexFindAll": mustRegexFindAll,
372 "regexFind": regexFind,
373 "mustRegexFind": mustRegexFind,
374 "regexReplaceAll": regexReplaceAll,
375 "mustRegexReplaceAll": mustRegexReplaceAll,
376 "regexReplaceAllLiteral": regexReplaceAllLiteral,
377 "mustRegexReplaceAllLiteral": mustRegexReplaceAllLiteral,
378 "regexSplit": regexSplit,
379 "mustRegexSplit": mustRegexSplit,
380 "regexQuoteMeta": regexQuoteMeta,
381
382 // URLs:
383 "urlParse": urlParse,
384 "urlJoin": urlJoin,
385 }