-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.go
3464 lines (2967 loc) · 102 KB
/
functions.go
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package templateManager
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"fmt"
"math/rand"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"github.com/grokify/html-strip-tags-go" // => strip
"github.com/google/uuid"
)
/*
Returns a function map for use with the Go template standard library
*/
func getDefaultFunctions() map[string]any {
return map[string]any{
"add": add,
"bool": toBool,
"capfirst": capfirst,
"collection": collection,
"concat": concat,
"contains": contains,
"cut": cut,
"date": date,
"datetime": datetime,
"default": defaultVal,
"divide": divide,
"divideceil": divideCeil,
"dividefloor": divideFloor,
"divisibleby": divisibleBy,
"dl": dl,
"endswith": endswith,
"equal": equal,
"first": first,
"firstof": firstOf,
"float": toFloat,
"formattime": formattime,
"gto": greaterThan,
"gte": greaterThanEqual,
"htmldecode": htmlDecode,
"htmlencode": htmlEncode,
"int": toInt,
"iterable": iterable,
"join": join,
"jsondecode": jsonDecode,
"jsonencode": jsonEncode,
"key": keyFn,
"keys": keys,
"kind": kind,
"last": last,
"length": length,
"list": list,
"lto": lessThan,
"lte": lessThanEqual,
"localtime": localtime,
"lower": lower,
"lpad": lpad,
"ltrim": ltrim,
"md5": md5Fn,
"mktime": mktime,
"multiply": multiply,
"nl2br": nl2br,
"notequal": notequal,
"now": now,
"ol": ol,
"ordinal": ordinal,
"paragraph": paragraph,
"pluralise": pluralise,
"prefix": prefix,
"query": query,
"random": random,
"regexp": regexpFindAll,
"regexpreplace": regexpReplaceAll,
"replace": replaceAll,
"round": round,
"rpad": rpad,
"rtrim": rtrim,
"sha1": sha1Fn,
"sha256": sha256Fn,
"sha512": sha512Fn,
"split": split,
"startswith": startswith,
"string": toString,
"striptags": stripTags,
"substr": substr,
"subtract": subtract,
"suffix": suffix,
"time": timeFn,
"timesince": timeSince,
"timeuntil": timeUntil,
"title": title,
"trim": trim,
"truncate": truncate,
"truncatewords": truncatewords,
"type": typeFn,
"uuid": uuid.NewString,
"ul": ul,
"upper": upper,
"urldecode": urlDecode,
"urlencode": urlEncode,
"values": values,
"wordcount": wordcount,
"wrap": wrap,
"year": year,
"yesno": yesno,
}
}
/*
Returns a function map for use with the Go template standard library that will replace many of their functions
with more consistent, fault tolerant and chainable alternatives
*/
func getOverloadFunctions() map[string]any {
return map[string]any{
"eq": equal,
"gt": greaterThan,
"ge": greaterThanEqual,
"len": length,
"index": keyFn,
"lt": lessThan,
"le": lessThanEqual,
"ne": notequal,
"html": htmlEncode,
"urlquery": urlEncode,
}
}
/*
func add[T any](value T, to T) (T, error)
Adds a value to the existing item.
For numeric items this is a simple addition. For other types this is appended / merged as appropriate.
*/
func add(value reflect.Value, to reflect.Value) (reflect.Value, error) {
sig := "add(value any, to any)"
value = reflectHelperUnpackInterface(value)
to = reflectHelperUnpackInterface(to)
if !value.IsValid() {
err := logError(sig + " `value` added cannot be an untyped nil value")
return to, err
}
if !to.IsValid() {
err := logError(sig + " value being added `to` cannot be an untyped nil value")
return to, err
}
// It's a simple type, do it recursively
if reflectHelperIsNumeric(value) || value.Kind() == reflect.String {
switch to.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
reflect.Uint64:
addVal, _ := reflectHelperConvertToFloat64(value)
toVal, _ := reflectHelperConvertToFloat64(to)
return reflect.ValueOf(int64(roundFloat(addVal + toVal, 0))).Convert(to.Type()), nil
case reflect.Float32, reflect.Float64:
addVal, _ := reflectHelperConvertToFloat64(value)
toVal, _ := reflectHelperConvertToFloat64(to)
return reflect.ValueOf(addVal + toVal).Convert(to.Type()), nil
case reflect.String:
addVal, _ := reflectHelperConvertToString(value)
return reflect.ValueOf(to.String() + addVal), nil
}
return recursiveHelper(to, reflect.ValueOf(add), value)
}
// It's a more complex type, no recursion and stricter checks
if err := reflectHelperLooseTypeCompatibility(value, to); err != nil {
err = logError(sig + " the `value` and `to` parameters must have the same approximate types; trying to add %s to %s", value.Type(), to.Type())
return to, err
}
switch to.Kind() {
case reflect.Slice:
slice, _ := reflectHelperCreateEmptySlice(value)
slice = reflect.AppendSlice(slice, to)
slice = reflect.AppendSlice(slice, value)
return slice, nil
case reflect.Array:
slice, _ := reflectHelperCreateEmptySlice(value)
for i := 0; i < to.Len(); i++ {
slice = reflect.Append(slice, to.Index(i))
}
for i := 0; i < value.Len(); i++ {
slice = reflect.Append(slice, value.Index(i))
}
arr, _ := reflectHelperConvertSliceToArray(slice)
return arr, nil
case reflect.Map:
tmp := reflect.MakeMap(to.Type())
iter := to.MapRange()
for iter.Next() {
tmp.SetMapIndex(iter.Key(), iter.Value())
}
iter = value.MapRange()
for iter.Next() {
if val := tmp.MapIndex(iter.Key()); val.IsValid() {
recurse, _ := add(iter.Value(), val)
tmp.SetMapIndex(iter.Key(), recurse)
} else {
tmp.SetMapIndex(iter.Key(), iter.Value())
}
}
return tmp, nil
}
return to, nil
}
/*
func capfirst[T any](value T) (T, error)
Capitalises the first letter of strings. Does not alter any other letters.
If `value` is a slice, array or map it will apply this conversion to any string elements that they contain.
*/
func capfirst(value reflect.Value) (reflect.Value, error) {
sig := "capfirst(value string)"
value = reflectHelperUnpackInterface(value)
if !value.IsValid() {
err := logWarning(sig + " cannot accept an untyped nil `value`")
return value, err
}
switch value.Kind() {
case reflect.String:
runes := []rune(value.String())
for i, r := range runes {
if unicode.IsLetter(r) {
if ! unicode.IsTitle(r) {
runes[i] = []rune(strings.ToUpper(string(r)))[0]
}
break
}
}
return reflect.ValueOf(string(runes)), nil
}
return recursiveHelper(value, reflect.ValueOf(capfirst))
}
/*
func collection(pairs ...any) (map[string]any, error)
Allows several variables to be packaged together into a map for passing to templates.
*/
func collection(pairs ...any) (map[string]any, error) {
sig := "collection(pairs ...any)"
length := len(pairs)
if length == 0 || length % 2 != 0 {
err := logError(sig + " can only accept pairs of arguments (string / any)")
return map[string]any{}, err
}
collection := make(map[string]any, length / 2)
for i := 0; i < length; i += 2 {
key, ok := pairs[i].(string)
if !ok {
err := logError(sig + " first member of a pair must be a string")
return map[string]any{}, err
}
collection[key] = pairs[i + 1]
}
return collection, nil
}
/*
func concat(values ...any) (string, error)
Concatenates any number of string-able values together in the order that they were declared.
*/
func concat(values ...reflect.Value) (reflect.Value, error) {
sig := "concat(values ...any)"
if len(values) < 1 {
err := logError(sig + " requires at least 1 parameter")
return reflect.ValueOf(""), err
}
str := ""
for _, value := range values {
value = reflectHelperUnpackInterface(value)
val, err := reflectHelperConvertAnythingToString(value)
if err == nil {
str += val
} else {
logWarning(sig + " attempting to append an invalid value: %v (%s) - it was ignored", value, value.Type())
}
}
return reflect.ValueOf(str), nil
}
/*
func contains(find any, within any) (bool, error)
Returns a boolean value to determine whether the `find` value is contained in the `within` value.
The `find` value can act on strings, slices, arrays and maps.
*/
func contains(find reflect.Value, within reflect.Value) (bool, error) {
sig := "contains(find any, within string|slice|map)"
find = reflectHelperUnpackInterface(find)
within = reflectHelperUnpackInterface(within)
if !find.IsValid() {
err := logWarning(sig + " is trying to search for an untyped nil value")
return false, err
}
if !within.IsValid() {
err := logWarning(sig + " is trying to search within an untyped nil value")
return false, err
}
switch within.Kind() {
case reflect.String:
val, err := reflectHelperConvertToString(find)
if err == nil {
return strings.Contains(within.String(), val), nil
}
err = logError(sig + " can't search within a string using a %s", find.Type())
return false, err
case reflect.Array, reflect.Slice:
var err error = nil
if reflectHelperGetSliceType(within) == find.Type().String() {
for i := 0; i < within.Len(); i++ {
if reflect.DeepEqual(within.Index(i).Interface(), find.Interface()) {
return true, err
}
}
} else {
err = logError(sig + " can't search within a slice type %s using a %s", reflectHelperGetSliceType(within), find.Type())
}
return false, err
case reflect.Map:
var err error = nil
if reflectHelperGetMapType(within) == find.Type().String() {
iter := within.MapRange()
for iter.Next() {
if reflect.DeepEqual(iter.Value().Interface(), find.Interface()) {
return true, err
}
}
} else {
err = logError(sig + " can't search within a map type %s using a %s", reflectHelperGetMapType(within), find.Type())
}
return false, err
case reflect.Struct:
for i := 0; i < within.NumField(); i++ {
field, err := reflectHelperGetStructValue(within, reflect.ValueOf(i))
if err == nil {
if field.Type().String() == find.Type().String() {
if reflect.DeepEqual(field.Interface(), find.Interface()) {
return true, nil
}
}
}
}
return false, nil
}
err := logWarning(sig + " can't search within an item of type %s", within.Type())
return false, err
}
/*
func cut[T any](remove string, from T) (T, error)
Will `remove` a string value that is contained in the `from` value.
If `from` is a slice, array or map it will apply this conversion to any string elements that they contain.
*/
func cut(remove reflect.Value, from reflect.Value) (reflect.Value, error) {
return replaceAll(remove, reflect.ValueOf(""), from)
}
/*
Returns a simple date string (by default: "d/m/Y").
Supports Go, Python and PHP formatting standards.
It can accept various parameter combinations:
date() // Current date and default output format
date(time time.Time) // Passed in time and default output format
date(format string) // Current date and custom output format
date(format string, time time.Time) // Time returned in the format specified
date(format string, time string) // Time in `time.RFC3339` format parsed into the format specified
// date "15:04" "2019-04-23T11:30:05Z"
date(format string, layout string, time string) // Time with a custom layout rule specifying an output format
// date "15:04" "Jan 2, 2006 at 3:04pm (MST)" "Feb 3, 2013 at 7:54pm (PST)"
// date "H:i" "Y-m-d H:i:s (T)" "2013-02-03 19:54:00 (PST)"
*/
func date(params ...any) (string, error) {
format := dateDefaultDateFormat
if len(params) == 0 {
return timeFn(format)
} else if len(params) == 1 {
switch val := params[0].(type) {
case time.Time:
return timeFn(format, val)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return timeFn(format, params[0])
}
}
return timeFn(params...)
}
/*
Returns a simple datetime string (by default: "d/m/Y H:i").
Supports Go, Python and PHP formatting standards.
It can accept various parameter combinations:
datetime() // Current date and default output format
datetime(time time.Time) // Passed in time and default output format
datetime(format string) // Current date and custom output format
datetime(format string, time time.Time) // Time returned in the format specified
datetime(format string, time string) // Time in `time.RFC3339` format parsed into the format specified
// datetime "02/01 15:04" "2019-04-23T11:30:05Z"
datetime(format string, layout string, time string) // Time with a custom layout rule specifying an output format
// datetime "02/01 15:04" "1 2, 2006 at 3:04pm" "2 3, 2013 at 7:54pm"
// datetime "m/d H:i" "Y-m-d H:i:s (T)" "2013-02-03 19:54:00 (PST)"
*/
func datetime(params ...any) (string, error) {
format := dateDefaultDatetimeFormat
if len(params) == 0 {
return timeFn(format)
} else if len(params) == 1 {
switch val := params[0].(type) {
case time.Time:
return timeFn(format, val)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return timeFn(format, params[0])
}
}
return timeFn(params...)
}
/*
func defaultVal(def any, test any) (any, error)
Will return the second `test` value if it is not empty, else return the `def` value
*/
func defaultVal(def reflect.Value, test reflect.Value) (reflect.Value, error) {
sig := "default(def any, value any)"
def = reflectHelperUnpackInterface(def)
test = reflectHelperUnpackInterface(test)
if !def.IsValid() {
err := logError(sig + " cannot set an untyped nil value as the default")
return reflect.Value{}, err
}
switch test.Kind() {
case reflect.String, reflect.Array, reflect.Slice, reflect.Map:
if test.Len() > 0 {
return test, nil
}
case reflect.Bool:
if test.Bool() {
return test, nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
reflect.Uint64, reflect.Float32, reflect.Float64:
if integer, err := reflectHelperConvertToInt(test); err == nil {
if integer != 0 {
return test, nil
}
}
case reflect.Struct:
if !reflectHelperIsEmptyStruct(test) {
return test, nil
}
}
return def, nil
}
/*
func divide[T any](divisor int|float, value T) (T, error)
Divides the `value` by the `divisor` and rounds if a float to integer conversion is required.
If `value` is a slice, array or map it will apply this conversion to any numeric elements that they contain.
*/
func divide(divisor reflect.Value, value reflect.Value) (reflect.Value, error) {
return divideHelper(reflect.ValueOf("round"), divisor, value)
}
/*
func divideceil[T any](divisor int|float, value T) (T, error)
Divides the `value` by the `divisor` and rounds up if a float to integer conversion is required.
If `value` is a slice, array or map it will apply this conversion to any numeric elements that they contain.
*/
func divideCeil(divisor reflect.Value, value reflect.Value) (reflect.Value, error) {
return divideHelper(reflect.ValueOf("ceil"), divisor, value)
}
/*
func dividefloor[T any](divisor int|float, value T) (T, error)
Divides the `value` by the `divisor` and rounds down if a float to integer conversion is required.
If `value` is a slice, array or map it will apply this conversion to any numeric elements that they contain.
*/
func divideFloor(divisor reflect.Value, value reflect.Value) (reflect.Value, error) {
return divideHelper(reflect.ValueOf("floor"), divisor, value)
}
/*
func divisibleby[T any](divisor int, value T) (bool, error)
Determines if the `value` is divisible by the `divisor`
*/
func divisibleBy(divisor reflect.Value, value reflect.Value) (bool, error) {
sig := "divisibleby(divisor int, value any)"
value = reflectHelperUnpackInterface(value)
if !divisor.IsValid() {
err := logError(sig + " divisor cannot be an untyped nil value")
return false, err
}
if !reflectHelperIsNumeric(divisor) {
err := logError(sig + " divisor must be numeric, not %s", value.Type())
return false, err
}
switch value.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
reflect.Uint64, reflect.Float32, reflect.Float64:
val, _ := reflectHelperConvertToFloat64(value)
div, _ := reflectHelperConvertToFloat64(divisor)
if div == 0.0 {
err := logWarning(sig + " divisor must not be zero")
return false, err
}
result := val / div
return equalFloats(result, roundFloat(result, 0)), nil
}
err := logWarning(sig + " attempting division of non numeric type: %s", value.Type())
return false, err
}
/*
func dl(value any) (string, error)
Converts slices, arrays or maps into an HTML definition list.
For maps this will use the keys as the dt elements.
*/
func dl(value reflect.Value) (string, error) {
return listHelper(value, "dl")
}
/*
func endswith(find any, value any) (bool, error)
Determines if a string ends with a certain value.
*/
func endswith(find reflect.Value, value reflect.Value) (bool, error) {
sig := "endswith(find any, value any)"
find = reflectHelperUnpackInterface(find)
value = reflectHelperUnpackInterface(value)
if !find.IsValid() || find.Kind() != reflect.String {
err := logError(sig + " can only be used to find strings")
return false, err
}
if !value.IsValid() {
err := logError(sig + " cannot accept an untyped nil value")
return false, err
}
switch value.Kind() {
case reflect.String:
return strings.HasSuffix(value.String(), find.String()), nil
}
err := logError(sig + " can't handle items of type %s", value.Type())
return false, err
}
/*
func equal(values ...any) (bool, error)
Determines whether any values are equal.
*/
func equal(values ...reflect.Value) (bool, error) {
sig := "equal(values ...any)"
if len(values) < 2 {
err := logError(sig + " at least two values required, %d provided", len(values))
return false, err
}
for i, value := range values {
values[i] = reflectHelperUnpackInterface(value)
value = values[i]
if !value.IsValid() {
err := logWarning(sig + " cannot compare untyped nil values")
return false, err
}
if i > 0 {
err := reflectHelperVeryLooseTypeCompatibility(value, values[i - 1])
if err != nil {
return false, nil
}
switch value.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
val1, _ := reflectHelperConvertToFloat64(value)
val2, _ := reflectHelperConvertToFloat64(values[i - 1])
if !equalFloats(val1, val2) {
return false, nil
}
case reflect.String:
if value.String() != values[i - 1].String() {
return false, nil
}
case reflect.Bool:
if value.Bool() != values[i - 1].Bool() {
return false, nil
}
case reflect.Array, reflect.Slice:
if !reflect.DeepEqual(value.Slice(0, value.Len() - 1).Interface(), values[i - 1].Slice(0, values[i - 1].Len() - 1).Interface()) {
return false, nil
}
case reflect.Map, reflect.Struct:
if !reflect.DeepEqual(value.Interface(), values[i - 1].Interface()) {
return false, nil
}
default:
return false, nil
}
}
}
return true, nil
}
/*
func first(value string|slice|array) (any, error)
Gets the first value from slices / arrays / maps / structs or the first word from strings.
*/
func first(value reflect.Value) (reflect.Value, error) {
sig := "first(value string|slice)"
value = reflectHelperUnpackInterface(value)
if !value.IsValid() {
err := logError(sig + " value cannot be an untyped nil value")
return reflect.Value{}, err
}
switch value.Kind() {
case reflect.String:
if value.Len() > 0 {
str := strings.Split(strings.TrimLeft(value.String(), " \n\r\t"), " ")[0]
return reflect.ValueOf(str), nil
}
case reflect.Array, reflect.Slice:
if value.Len() > 0 {
return value.Index(0), nil
}
case reflect.Map:
if value.Len() > 0 {
keys, err := reflectHelperMapSort(value)
if err == nil {
return value.MapIndex(keys.Index(0)), nil
} else {
iter := value.MapRange()
for iter.Next() {
return iter.Value(), nil
}
}
}
case reflect.Struct:
value, err := reflectHelperGetStructValue(value, reflect.ValueOf(0))
if err != nil {
err := logError(sig + " " + err.Error())
return reflect.Value{}, err
}
return value, nil
}
err := logError(sig + fmt.Sprintf(" can't handle items of type %s", value.Type()))
return reflect.Value{}, err
}
/*
func firstOf(values ...any) (any, error)
Accepts any number of values and returns the first one of them that exists and is not empty.
*/
func firstOf(values ...reflect.Value) (reflect.Value, error) {
sig := "firstof(values ...any)"
if len(values) < 1 {
err := logError(sig + " being called without any parameters")
return reflect.Value{}, err
}
for _, value := range values {
value = reflectHelperUnpackInterface(value)
if !value.IsValid() {
continue
}
switch value.Kind() {
case reflect.String, reflect.Array, reflect.Slice, reflect.Map:
if value.Len() > 0 {
return value, nil
}
case reflect.Struct:
empty := reflect.New(value.Type()).Elem().Interface()
if !reflect.DeepEqual(value.Interface(), empty) {
return value, nil
}
case reflect.Bool:
if value.Bool() {
return value, nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
reflect.Uint64, reflect.Float32, reflect.Float64:
if integer, err := reflectHelperConvertToInt(value); err == nil {
if integer != 0 {
return value, nil
}
}
}
}
return reflect.Value{}, nil
}
/*
func formattime(format string, t time.Time) (string, error)
Formats a time.Time object for display.
*/
func formattime(format string, t time.Time) (string, error) {
return t.Format(dateFormatHelper(format)), nil
}
/*
func greaterThan(value1 any, value2 any) (bool, error)
Determines if `value2` is greater than `value1`
*/
func greaterThan(value1 reflect.Value, value2 reflect.Value) (bool, error) {
sig := "gto(value any, value any)"
value1 = reflectHelperUnpackInterface(value1)
if !value1.IsValid() {
err := logError(sig + " values cannot be untyped nil values")
return false, err
}
value2 = reflectHelperUnpackInterface(value2)
if !value2.IsValid() {
err := logError(sig + " values cannot be untyped nil values")
return false, err
}
err := reflectHelperVeryLooseTypeCompatibility(value1, value2)
if err != nil {
err := logError(sig + " values of dramatically different types cannot be compared")
return false, err
}
switch value1.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
val1, _ := reflectHelperConvertToFloat64(value1)
val2, _ := reflectHelperConvertToFloat64(value2)
if val2 > val1 {
return true, nil
}
default:
err = logError(sig + " values cannot be type %s", value1.Type())
return false, err
}
return false, nil
}
/*
func greaterThanEqual(value1 any, value2 any) (bool, error)
Determines if `value2` is greater than or equal to `value1`
*/
func greaterThanEqual(value1 reflect.Value, value2 reflect.Value) (bool, error) {
sig := "gte(value any, value any)"
value1 = reflectHelperUnpackInterface(value1)
if !value1.IsValid() {
err := logError(sig + " values cannot be untyped nils")
return false, err
}
value2 = reflectHelperUnpackInterface(value2)
if !value2.IsValid() {
err := logError(sig + " values cannot be untyped nils")
return false, err
}
err := reflectHelperVeryLooseTypeCompatibility(value1, value2)
if err != nil {
err := logError(sig + " values of dramatically different types cannot be compared")
return false, err
}
switch value1.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
val1, _ := reflectHelperConvertToFloat64(value1)
val2, _ := reflectHelperConvertToFloat64(value2)
if val2 >= val1 || equalFloats(val1, val2) {
return true, err
}
default:
err = logError(sig + " values cannot be type %s", value1.Type())
return false, err
}
return false, nil
}
/*
func htmlDecode[T any](value T) (T, error)
Converts HTML character-entity equivalents back into their literal, usable forms.
If `value` is a slice, array or map it will apply this conversion to any string elements that they contain.
*/
func htmlDecode(value reflect.Value) (reflect.Value, error) {
sig := "htmldecode(value any)"
value = reflectHelperUnpackInterface(value)
if !value.IsValid() {
err := logError(sig + " values cannot be untyped nils")
return value, err
}
switch value.Kind() {
case reflect.String:
find := []string{ "<", ">", "<", ">", "<", ">", """, """, """, "'", "'", "'", "&", "&", "&" }
replace := []string{ "<", ">", "<", ">", "<", ">", `"`, `"`, `"`, "'", "'", "'", "&", "&", "&" }
replacer, err := replaceHelper(find, replace)
if err != nil {
err := logError(err.Error())
return reflect.Value{}, err
}
return reflect.ValueOf(replacer.Replace(value.String())), nil
}
return recursiveHelper(value, reflect.ValueOf(htmlDecode))
}
/*
func htmlEncode[T any](value T) (T, error)
Converts literal HTML special characters into safe, character-entity equivalents.
If `value` is a slice, array or map it will apply this conversion to any string elements that they contain.
*/
func htmlEncode(value reflect.Value) (reflect.Value, error) {
sig := "htmlencode(value any)"
value = reflectHelperUnpackInterface(value)
if !value.IsValid() {
err := logError(sig + " values cannot be untyped nils")
return value, err
}
switch value.Kind() {
case reflect.String:
find := []string{ "<", ">", `"`, "'", "&" }
replace := []string{ "<", ">", """, "'", "&" }
replacer, err := replaceHelper(find, replace)
if err != nil {
err := logError(err.Error())
return reflect.Value{}, err
}
return reflect.ValueOf(replacer.Replace(value.String())), nil
}
return recursiveHelper(value, reflect.ValueOf(htmlEncode))
}
/*
func iterable(value ...int) ([]int, error)
Creates an integer slice so as to spoof a `for` loop:
{{ range $v := iterable 5 }} -> for v := 0; v < 5; v++
{{ range $v := iterable 3 5 }} -> for v := 3; v < 5; v++
{{ range $v := iterable 3 5 2 }} -> for v := 3; v < 5; v += 2
*/
func iterable(values ...reflect.Value) ([]int, error) {
sig := "iterable(values ...int)"
if len(values) < 1 {
err := logError(sig + " requires at least one value")
return []int{}, err
}
start := reflect.ValueOf(0)
end := reflect.ValueOf(0)
increment := reflect.ValueOf(1)
switch len(values) {
case 1:
end = values[0]
case 2:
start = values[0]
end = values[1]
default:
start = values[0]
end = values[1]
increment = values[2]
}
start = reflectHelperUnpackInterface(start)
end = reflectHelperUnpackInterface(end)
increment = reflectHelperUnpackInterface(increment)
if !start.IsValid() || !reflectHelperIsInteger(start) {
err := logWarning(sig + " start value cannot be an untyped nil")
if err != nil {
return []int{}, err
}
logWarning(sig + " not halting on warnings, setting start to 0")
start = reflect.ValueOf(0)
}
if !end.IsValid() || !reflectHelperIsInteger(end) {
err := logWarning(sig + " end value cannot be an untyped nil")
if err != nil {
return []int{}, err
}
logWarning(sig + " not halting on warnings, setting end to 0")
end = reflect.ValueOf(0)
}
if !increment.IsValid() || !reflectHelperIsInteger(increment) {
err := logWarning(sig + " increment value cannot be an untyped nil")
if err != nil {
return []int{}, err
}
logWarning(sig + " not halting on warnings, setting increment to 1")
increment = reflect.ValueOf(1)
}
st, _ := reflectHelperConvertToInt(start)
en, _ := reflectHelperConvertToInt(end)
in, _ := reflectHelperConvertToInt(increment)
if in == 0 {
err := logError(sig + " increment value must not be zero")
return []int{}, err
}
if st > en && in > 0 {
if len(values) < 3 {
in = -1
} else {
err := logError(sig + " if start > end, increment value must be negative")
return []int{}, err
}
}
if en > st && in < 0 {
err := logError(sig + " if end > start, increment value must be positive")
return []int{}, err
}
items := []int{}
if st > en && in < 0 {
for i := st; i > en; i += in {
items = append(items, i)
}
} else {
for i := st; i < en; i += in {
items = append(items, i)
}
}