-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
109 lines (85 loc) · 2.3 KB
/
parser.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
// Package vipertpl extends viper's functionality with ability to use golang
// templates in string variables
package vipertpl
import (
"bytes"
"errors"
"fmt"
"os/exec"
"strings"
"text/template"
"github.com/spf13/viper"
)
// New creates new Parser.
func New(funcs template.FuncMap) *Parser {
return &Parser{funcs}
}
// Parser is a struct holding `Parse` functionality.
type Parser struct {
funcs template.FuncMap
}
// Parse goes though all the keys stored in viper config and parses them with
// golang's internal templating engine.
func Parse(v *viper.Viper) error {
p := Parser{}
return p.Parse(v)
}
// Parse goes though all the keys stored in viper config and parses them with
// golang's internal templating engine.
func (p *Parser) Parse(v *viper.Viper) error {
for _, key := range v.AllKeys() {
parser := parser{v: v, visitedKeys: map[string]struct{}{}}
parser.funcs = template.FuncMap{
"ViperGet": parser.tplFuncViperGet,
"Exec": tplFuncExec,
}
for k, v := range p.funcs {
parser.funcs[k] = v
}
val := v.Get(key)
_, err := parser.parseTpl(key, val)
if err != nil {
return err
}
}
return nil
}
type parser struct {
v *viper.Viper
visitedKeys map[string]struct{}
funcs template.FuncMap
}
func (p *parser) tplFuncViperGet(key string) (interface{}, error) {
if _, isVisited := p.visitedKeys[key]; isVisited {
return "", fmt.Errorf("not able to parse tpl for key %s: %w", key, ErrCircularDependency)
}
val := p.v.Get(key)
p.visitedKeys[key] = struct{}{}
return p.parseTpl(key, val)
}
func (p *parser) parseTpl(key string, rawVal interface{}) (interface{}, error) {
val, ok := rawVal.(string)
if !ok {
return rawVal, nil
}
tpl, err := template.New(val).Funcs(p.funcs).Parse(val)
if err != nil {
return val, err
}
var buf bytes.Buffer
if err := tpl.Execute(&buf, nil); err != nil {
return val, err
}
p.v.Set(key, buf.String())
return buf.String(), nil
}
func tplFuncExec(cmd string, args ...string) (string, error) {
out, err := exec.Command(cmd, args...).CombinedOutput()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
// ErrCircularDependency is returned when there is a circular dependency caused
// by using tpl "ViperGet" function.
var ErrCircularDependency = errors.New("circular dependency")