-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
75 lines (64 loc) · 1.77 KB
/
utils.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
package skit
import (
"regexp"
"strings"
"text/template"
)
// ParseExprs parses given list of regular expressions and returns the
// compiled objects.
func ParseExprs(exprs []string) ([]*regexp.Regexp, error) {
rexps := []*regexp.Regexp{}
for _, exp := range exprs {
rexp, err := regexp.Compile(exp)
if err != nil {
return nil, err
}
rexps = append(rexps, rexp)
}
return rexps, nil
}
// RenderAll executes all templates passed in with the data and returns the rendered
// strings. Returns nil and an error on first execution failure.
func RenderAll(tpls []template.Template, data interface{}) ([]string, error) {
out := []string{}
for _, tpl := range tpls {
s, err := Render(tpl, data)
if err != nil {
return nil, err
}
out = append(out, s)
}
return out, nil
}
// Render executes the template with data and returns the rendered string.
func Render(tpl template.Template, data interface{}) (string, error) {
wr := &strings.Builder{}
if err := tpl.Execute(wr, data); err != nil {
return "", err
}
return wr.String(), nil
}
// RenderString creates template from tplStr and executes the template with
// data and returns the rendered string.
func RenderString(tplStr string, data interface{}) (string, error) {
tpl, err := template.New("simple").Parse(tplStr)
if err != nil {
return "", err
}
return Render(*tpl, data)
}
// CaptureAll matches s with the regex and returns all named capture values.
// Returns nil if the s was not a match.
func CaptureAll(regEx *regexp.Regexp, s string) map[string]interface{} {
match := regEx.FindStringSubmatch(s)
if match == nil {
return nil
}
paramsMap := map[string]interface{}{}
for i, name := range regEx.SubexpNames() {
if i > 0 && i <= len(match) {
paramsMap[name] = match[i]
}
}
return paramsMap
}