-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathfunctions.go
More file actions
804 lines (677 loc) · 18.7 KB
/
functions.go
File metadata and controls
804 lines (677 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
package diecast
import (
"bytes"
"encoding/base32"
"encoding/csv"
"encoding/json"
"fmt"
"html/template"
"io"
"math"
"net/http"
"os"
"path"
"regexp"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
humanize "github.com/dustin/go-humanize"
"github.com/ghetzel/go-stockutil/fileutil"
"github.com/ghetzel/go-stockutil/maputil"
"github.com/ghetzel/go-stockutil/sliceutil"
"github.com/ghetzel/go-stockutil/stringutil"
"github.com/ghetzel/go-stockutil/typeutil"
"github.com/kelvins/sunrisesunset"
"github.com/montanaflynn/stats"
blackfriday "github.com/russross/blackfriday/v2"
"golang.org/x/net/html"
)
var Base32Alphabet = base32.NewEncoding(`abcdefghijklmnopqrstuvwxyz234567`)
var globalFunctions = make(FuncMap)
// Register a function that will be available to all template expressions, wherever they appear.
func RegisterGlobalFunction(name string, fn any) {
if fn != nil {
globalFunctions[name] = fn
} else {
delete(globalFunctions, name)
}
}
type fileInfo struct {
Parent string
Directory bool
os.FileInfo
}
func (info *fileInfo) toMap() map[string]any {
var full = path.Join(info.Parent, info.Name())
var data = map[string]any{
`name`: info.Name(),
`path`: full,
`size`: info.Size(),
`last_modified`: info.ModTime(),
`directory`: info.IsDir(),
}
if !info.IsDir() {
data[`mimetype`] = fileutil.GetMimeType(full)
}
return data
}
func (info *fileInfo) MarshalJSON() ([]byte, error) {
return json.Marshal(info.toMap())
}
func (info *fileInfo) String() string {
return path.Join(info.Parent, info.Name())
}
type statsUnaryFn func(stats.Float64Data) (float64, error)
type statsUnary struct {
Name string
Function statsUnaryFn
}
func MinNonZero(data stats.Float64Data) (float64, error) {
for i, v := range data {
if v == 0 {
data = append(data[:i], data[i+1:]...)
}
}
return stats.Min(data)
}
func GetFunctions(server *Server) (funcGroups, FuncMap) {
if server != nil {
server.lockGetFunctions.Lock()
defer server.lockGetFunctions.Unlock()
}
var funcs FuncMap = make(FuncMap)
for k, v := range globalFunctions {
funcs[k] = v
}
var groups funcGroups = make(funcGroups, 0)
// String Processing
groups = append(groups, loadStandardFunctionsString(funcs, server))
// File Pathname Handling
groups = append(groups, loadStandardFunctionsPath(funcs, server))
// Encoding / Decoding
groups = append(groups, loadStandardFunctionsCodecs(funcs, server))
// Type Handling and Conversion
groups = append(groups, loadStandardFunctionsTypes(funcs, server))
// Time and Date Formatting
groups = append(groups, loadStandardFunctionsTime(funcs, server))
// Random Numbers and Encoding
groups = append(groups, loadStandardFunctionsCryptoRand(funcs, server))
// Numeric/Math Functions
groups = append(groups, loadStandardFunctionsMath(funcs, server))
// Collections
groups = append(groups, loadStandardFunctionsCollections(funcs, server))
// HTML processing
groups = append(groups, loadStandardFunctionsHtmlProcessing(funcs, server))
// Colors
groups = append(groups, loadStandardFunctionsColor(funcs, server))
// Unit Conversions
groups = append(groups, loadStandardFunctionsConvert(funcs, server))
// Template Introspection functions
groups = append(groups, loadStandardFunctionsIntrospection(funcs, server))
// Comparators
groups = append(groups, loadStandardFunctionsComparisons(funcs, server))
// Highlighting
groups = append(groups, loadStandardFunctionsLangHighlighting(funcs, server))
// Celestial & Astronomical
groups = append(groups, loadStandardFunctionsCelestial(funcs, server))
// Documentation for runtime functions
groups = append(groups, loadRuntimeFunctionsVariables(server))
groups = append(groups, loadRuntimeFunctionsRequest(server))
groups.PopulateFuncMap(funcs)
return groups, funcs
}
func GetStandardFunctions(server *Server) FuncMap {
_, funcs := GetFunctions(server)
return funcs
}
type statsTplFunc func(in any) (float64, error) // {}
func delimited(comma rune, header []any, lines []any) (string, error) {
var output = bytes.NewBufferString(``)
var csvwriter = csv.NewWriter(output)
csvwriter.Comma = comma
csvwriter.UseCRLF = true
var input = make([][]string, 0)
var columnNames = sliceutil.Stringify(header)
input = append(input, columnNames)
for _, line := range lines {
var lineslice = sliceutil.Sliceify(line)
for i, value := range lineslice {
if typeutil.IsArray(value) && len(sliceutil.Compact(sliceutil.Sliceify(value))) == 0 {
if i+1 < len(lineslice) {
lineslice = append(lineslice[:i], lineslice[i+1:]...)
} else {
lineslice = lineslice[:i]
}
} else if typeutil.IsMap(value) {
var m = maputil.M(value)
for j, col := range columnNames {
if j < len(lineslice) {
lineslice[j] = m.Get(col)
}
}
}
}
input = append(input, sliceutil.Stringify(
sliceutil.Flatten(lineslice),
))
}
if err := csvwriter.WriteAll(input); err != nil {
return ``, err
}
return output.String(), nil
}
func tmFmt(value any, format ...string) (string, error) {
if value == nil || typeutil.String(value) == `` {
return ``, nil
}
var v = typeutil.Time(value)
if v.IsZero() {
return ``, fmt.Errorf("invalid time: %v", value)
}
var tmFormat string
var formatName string
if len(format) == 0 {
tmFormat = time.RFC3339
} else {
formatName = format[0]
switch formatName {
case `kitchen`:
tmFormat = time.Kitchen
case `timer`:
tmFormat = `15:04:05`
case `rfc3339`:
tmFormat = time.RFC3339
case `rfc3339ns`:
tmFormat = time.RFC3339Nano
case `rfc822`:
tmFormat = time.RFC822
case `rfc822z`:
tmFormat = time.RFC822Z
case `rfc1123`:
tmFormat = time.RFC1123
case `rfc1123z`:
tmFormat = time.RFC1123Z
case `epoch`:
return fmt.Sprintf("%d", v.Unix()), nil
case `epoch-ms`:
return fmt.Sprintf("%d", int64(v.UnixNano()/1000000)), nil
case `epoch-us`:
return fmt.Sprintf("%d", int64(v.UnixNano()/1000)), nil
case `epoch-ns`:
return fmt.Sprintf("%d", int64(v.UnixNano())), nil
case `day`:
tmFormat = `Monday`
case `slash`:
tmFormat = `01/02/2006`
case `slash-dmy`:
tmFormat = `02/01/2006`
case `ymd`:
tmFormat = `2006-01-02`
case `ruby`:
tmFormat = time.RubyDate
case `ansi`, `ansic`:
tmFormat = time.ANSIC
case `unixdate`:
tmFormat = time.UnixDate
case `stamp`:
tmFormat = time.Stamp
case `stamp-ms`:
tmFormat = time.StampMilli
case `stamp-us`:
tmFormat = time.StampMicro
case `stamp-ns`:
tmFormat = time.StampNano
default:
tmFormat = formatName
}
}
var vStr string
switch tmFormat {
case `human`:
vStr = humanize.Time(v)
default:
vStr = v.Format(tmFormat)
}
if formatName == `timer` {
if len(strings.Split(vStr, `:`)) == 3 {
vStr = strings.TrimPrefix(vStr, `00:`)
}
}
return vStr, nil
}
func calcFn(op string, values ...any) (float64, error) {
var valuesF = make([]float64, len(values))
for i, v := range values {
if vF, err := stringutil.ConvertToFloat(v); err == nil {
valuesF[i] = vF
} else {
return 0, err
}
}
switch len(valuesF) {
case 0:
return 0.0, nil
case 1:
return valuesF[0], nil
default:
var out = valuesF[0]
for _, v := range valuesF[1:] {
switch op {
case `+`:
out += v
case `-`:
out -= v
case `*`:
out *= v
case `^`:
out = math.Pow(out, v)
case `/`:
if v == 0.0 {
return 0, fmt.Errorf("cannot divide by zero")
}
out /= v
case `%`:
if v == 0.0 {
return 0, fmt.Errorf("cannot divide by zero")
}
out = math.Mod(out, v)
}
}
return out, nil
}
}
func filterByKey(funcs FuncMap, input any, key string, exprs ...any) ([]any, error) {
var out = make([]any, 0)
var expr = sliceutil.First(exprs)
var exprStr = fmt.Sprintf("%v", expr)
for i, mapitem := range sliceutil.Sliceify(input) {
var submap = maputil.M(mapitem)
if item := submap.Get(key); !item.IsNil() {
if stringutil.IsSurroundedBy(exprStr, `{{`, `}}`) {
var tmpl = NewTemplate(`inline`, TextEngine)
tmpl.Funcs(funcs)
if err := tmpl.ParseString(exprStr); err == nil {
var output = bytes.NewBuffer(nil)
if err := tmpl.Render(output, item.Value, ``); err == nil {
if evalValue := stringutil.Autotype(output.String()); !typeutil.IsZero(evalValue) {
out = append(out, mapitem)
}
} else {
return nil, fmt.Errorf("item %d: %v", i, err)
}
} else {
return nil, fmt.Errorf("failed to parse template: %v", err)
}
} else if typeutil.IsArray(expr) {
// if we were given an array, then matching ANY item in the array yields true
for _, want := range sliceutil.Sliceify(expr) {
if ok, err := stringutil.RelaxedEqual(item, want); err == nil && ok {
out = append(out, mapitem)
break
}
}
} else if ok, err := stringutil.RelaxedEqual(item, expr); err == nil && ok {
out = append(out, mapitem)
}
}
}
return out, nil
}
func uniqByKey(funcs FuncMap, input any, key string, saveLast bool, exprs ...any) ([]any, error) {
var out = make([]any, 0)
var expr = sliceutil.First(exprs)
var exprStr = fmt.Sprintf("%v", expr)
var valuesEncountered = make(map[string]int)
for i, submap := range sliceutil.Sliceify(input) {
if typeutil.IsMap(submap) {
if item := maputil.DeepGet(submap, strings.Split(key, `.`)); item != nil {
var valkey string
if stringutil.IsSurroundedBy(exprStr, `{{`, `}}`) {
var tmpl = NewTemplate(`inline`, TextEngine)
tmpl.Funcs(funcs)
if err := tmpl.ParseString(exprStr); err == nil {
var output = bytes.NewBuffer(nil)
if err := tmpl.Render(output, item, ``); err == nil {
valkey = output.String()
} else {
return nil, fmt.Errorf("item %d: %v", i, err)
}
} else {
return nil, fmt.Errorf("failed to parse template: %v", err)
}
} else {
valkey = fmt.Sprintf("%v", item)
}
// if we're saving the last value, then always overwrite; otherwise, only
// mark this item for inclusion in the output if nothing else has been in this
// spot before
if _, ok := valuesEncountered[valkey]; saveLast || !ok {
valuesEncountered[valkey] = i
}
}
}
}
// put only the unique values into the output
for i, submap := range sliceutil.Sliceify(input) {
for _, vi := range valuesEncountered {
if i == vi {
out = append(out, submap)
}
}
}
return out, nil
}
func commonses(slice any, cmp string) (any, error) {
var counts = make(map[any]int)
if err := sliceutil.Each(slice, func(i int, value any) error {
if c, ok := counts[value]; ok {
counts[value] = c + 1
} else {
counts[value] = 1
}
return nil
}); err == nil {
var out any
var threshold int
for value, count := range counts {
if out == nil {
out = value
}
switch cmp {
case `most`:
if count > threshold {
out = value
threshold = count
}
case `least`:
if count < threshold {
out = value
threshold = count
}
default:
return nil, fmt.Errorf("unknown comparator %q", cmp)
}
}
return out, nil
} else {
return nil, err
}
}
func htmlNodeToMap(node *html.Node) map[string]any {
var output = make(map[string]any)
if node != nil && node.Type == html.ElementNode {
var text = ``
var children = make([]map[string]any, 0)
var attrs = make(map[string]any)
for child := node.FirstChild; child != nil; child = child.NextSibling {
switch child.Type {
case html.TextNode:
text += child.Data
case html.ElementNode:
if child != node {
if childData := htmlNodeToMap(child); len(childData) > 0 {
children = append(children, childData)
}
}
}
}
text = strings.TrimSpace(text)
for _, attr := range node.Attr {
attrs[attr.Key] = stringutil.Autotype(attr.Val)
}
if len(attrs) > 0 {
output[`attributes`] = attrs
}
if text != `` {
output[`text`] = text
}
if len(children) > 0 {
output[`children`] = children
}
// only if the node has anything useful at all in it...
if len(output) > 0 {
output[`name`] = node.DataAtom.String()
}
}
return output
}
func getSunriseSunset(latitude float64, longitude float64, atTime ...any) (time.Time, time.Time, error) {
var at time.Time
if len(atTime) > 0 {
if tm, err := stringutil.ConvertToTime(atTime[0]); err == nil {
at = tm
} else {
return time.Time{}, time.Time{}, err
}
} else {
at = time.Now()
}
_, offset := at.Zone()
var p = sunrisesunset.Parameters{
Latitude: latitude,
Longitude: longitude,
UtcOffset: (float64(offset) / 60.0 / 60.0),
Date: at,
}
if sunrise, sunset, err := p.GetSunriseSunset(); err == nil {
sunrise = time.Date(at.Year(), at.Month(), at.Day(), sunrise.Hour(), sunrise.Minute(), sunrise.Second(), 0, at.Location())
sunset = time.Date(at.Year(), at.Month(), at.Day(), sunset.Hour(), sunset.Minute(), sunset.Second(), 0, at.Location())
return sunrise, sunset, nil
} else {
return time.Time{}, time.Time{}, err
}
}
func timeCmp(before bool, first any, secondI ...any) (bool, error) {
var second any
if len(secondI) == 0 {
second = first
first = time.Now()
} else {
second = secondI[0]
}
if firstT, err := stringutil.ConvertToTime(first); err == nil {
if secondT, err := stringutil.ConvertToTime(second); err == nil {
if before {
return firstT.Before(secondT), nil
} else {
return firstT.After(secondT), nil
}
} else {
return false, err
}
} else {
return false, err
}
}
func timeDelta(now time.Time, tm time.Time, dur time.Duration, lte bool) (bool, error) {
if tm.IsZero() {
return false, fmt.Errorf("invalid time value")
} else if dur == 0 {
return false, fmt.Errorf("invalid duration value")
}
var threshold = now.Add(time.Duration(-1) * dur)
if lte {
return (tm.Equal(threshold) || tm.After(threshold)), nil
} else {
return tm.Before(threshold), nil
}
}
func cmp(op string, first any, second any) (bool, error) {
fStr, ok1 := first.(string)
sStr, ok2 := second.(string)
if ok1 && ok2 {
switch op {
case `gt`:
return fStr > sStr, nil
case `ge`:
return fStr >= sStr, nil
case `lt`:
return fStr < sStr, nil
case `le`:
return fStr <= sStr, nil
default:
return false, fmt.Errorf("invalid operator %q", op)
}
} else {
var fVal = typeutil.Float(first)
var sVal = typeutil.Float(second)
switch op {
case `gt`:
return fVal > sVal, nil
case `ge`:
return fVal >= sVal, nil
case `lt`:
return fVal < sVal, nil
case `le`:
return fVal <= sVal, nil
default:
return false, fmt.Errorf("invalid operator %q", op)
}
}
}
func toMarkdownExt(extensions ...string) blackfriday.Extensions {
if len(extensions) > 0 {
var ext blackfriday.Extensions
for _, x := range extensions {
switch stringutil.Hyphenate(x) {
case `no-intra-emphasis`:
ext |= blackfriday.NoIntraEmphasis
case `tables`:
ext |= blackfriday.Tables
case `fenced-code`:
ext |= blackfriday.FencedCode
case `autolink`:
ext |= blackfriday.Autolink
case `strikethrough`:
ext |= blackfriday.Strikethrough
case `lax-html-blocks`:
ext |= blackfriday.LaxHTMLBlocks
case `space-headings`:
ext |= blackfriday.SpaceHeadings
case `hard-line-break`:
ext |= blackfriday.HardLineBreak
case `tab-size-eight`:
ext |= blackfriday.TabSizeEight
case `footnotes`:
ext |= blackfriday.Footnotes
case `no-empty-line-before-block`:
ext |= blackfriday.NoEmptyLineBeforeBlock
case `heading-ids`:
ext |= blackfriday.HeadingIDs
case `titleblock`:
ext |= blackfriday.Titleblock
case `auto-heading-ids`:
ext |= blackfriday.AutoHeadingIDs
case `backslash-line-break`:
ext |= blackfriday.BackslashLineBreak
case `definition-lists`:
ext |= blackfriday.DefinitionLists
case `common`:
ext |= blackfriday.CommonExtensions
}
}
return ext
} else {
return blackfriday.CommonExtensions
}
}
func htmldoc(docI any) (*goquery.Document, error) {
if d, ok := docI.(*goquery.Document); ok {
return d, nil
} else if d, ok := docI.(string); ok {
return goquery.NewDocumentFromReader(bytes.NewBufferString(d))
} else if d, ok := docI.(template.HTML); ok {
return goquery.NewDocumentFromReader(bytes.NewBufferString(string(d)))
} else {
return nil, fmt.Errorf("expected a HTML document string or object, got: %T", docI)
}
}
func htmlModify(docI any, selector string, action string, k string, v any, extra ...any) (template.HTML, error) {
if doc, err := htmldoc(docI); err == nil {
switch action {
case `remove`:
doc.Find(selector).Remove()
case `add-class`:
doc.Find(selector).AddClass(sliceutil.Stringify(sliceutil.Flatten(v))...)
case `remove-class`:
doc.Find(selector).RemoveClass(sliceutil.Stringify(sliceutil.Flatten(v))...)
case `set-attr`:
doc.Find(selector).SetAttr(k, typeutil.String(v))
case `find-replace-attr`:
if len(extra) > 0 {
if rxFind, err := regexp.Compile(typeutil.String(extra[0])); err == nil {
doc.Find(selector).Each(func(i int, match *goquery.Selection) {
if current, ok := match.Attr(k); ok {
match.SetAttr(k, rxFind.ReplaceAllString(current, typeutil.String(v)))
}
})
} else {
return ``, fmt.Errorf("invalid find expression: %v", err)
}
} else {
return ``, fmt.Errorf("no find expression specified")
}
case `find-replace-text`:
if len(extra) > 0 {
if rxFind, err := regexp.Compile(typeutil.String(extra[0])); err == nil {
doc.Find(selector).Each(func(i int, match *goquery.Selection) {
for _, node := range match.Nodes {
// recursively walk the subtree from this node and apply the
// find/replace to all text therein
walkNodeTree(node, func(n *html.Node) bool {
switch n.Type {
case html.TextNode:
n.Data = rxFind.ReplaceAllString(n.Data, typeutil.String(v))
}
return true
})
}
})
} else {
return ``, fmt.Errorf("invalid find expression: %v", err)
}
} else {
return ``, fmt.Errorf("no find expression specified")
}
default:
return ``, fmt.Errorf("unknown HTML action %q", action)
}
doc.End()
output, err := doc.Html()
return template.HTML(output), err
} else {
return ``, err
}
}
// recursively walk a subtree starting from a given node, calling fn for each node
// (including the entry point).
func walkNodeTree(node *html.Node, fn func(child *html.Node) bool) {
if !fn(node) {
return
}
switch node.Type {
case html.ElementNode:
for child := node.FirstChild; child != nil; child = child.NextSibling {
if !fn(child) {
return
}
}
}
}
func toBytes(input any) []byte {
var in []byte
if v, ok := input.([]byte); ok {
in = v
} else {
in = []byte(typeutil.String(input))
}
return in
}
func readFromFS(fs http.FileSystem, filename string) ([]byte, error) {
if file, err := fs.Open(filename); err == nil {
defer file.Close()
return io.ReadAll(file)
} else {
return nil, err
}
}