-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunctions.go
More file actions
89 lines (73 loc) · 1.54 KB
/
functions.go
File metadata and controls
89 lines (73 loc) · 1.54 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
package transform
import (
"encoding/json"
"fmt"
"os"
"reflect"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/dongri/phonenumber"
"github.com/rs/zerolog/log"
)
func customFunctions() template.FuncMap {
f := sprig.GenericFuncMap()
delete(f, "last")
extra := template.FuncMap{
"last": func(x int, a interface{}) bool {
return x == reflect.ValueOf(a).Len()-1
},
"separator": separator,
"marshal": marshal,
"fromEnv": fromEnv,
"phoneIso3166": phoneIso3166,
"array_contains": func(a []interface{}, b string) bool {
for _, x := range a {
stringX, ok := x.(string)
if !ok {
return false
}
if stringX == b {
return true
}
}
return false
},
}
for k, v := range extra {
if _, ok := f[k]; !ok {
f[k] = v
} else {
fmt.Fprintf(os.Stderr, "duplicate template func [%s]\n", k)
}
}
return f
}
func separator(s string) func() string {
i := -1
return func() string {
i++
if i == 0 {
return ""
}
return s
}
}
func marshal(v any) string {
a, err := json.Marshal(v)
if err != nil {
log.Error().Err(err).Msg("failed to marshal any")
}
return string(a)
}
func fromEnv(key, envName string) string {
value := os.Getenv(envName)
strValue, err := json.Marshal(value)
if err != nil {
log.Error().Err(err).Msg("failed to marshal value")
}
return fmt.Sprintf("%q:%s", key, string(strValue))
}
func phoneIso3166(phone string) string {
country := phonenumber.GetISO3166ByNumber(phone, true)
return phonenumber.ParseWithLandLine(phone, country.Alpha2)
}