-
Notifications
You must be signed in to change notification settings - Fork 0
/
expander.go
100 lines (75 loc) · 2 KB
/
expander.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
package expandvars
import (
"errors"
"fmt"
"os"
"strings"
)
const varDelimiter = "$"
// ErrUnsupportedExpander indicates that the provided expander is not supported.
var ErrUnsupportedExpander = errors.New("unsupported expander")
// EnvExpander expands variables using env vars.
var EnvExpander Expander = os.ExpandEnv
// Pairs is a pair of old and new to be replaced.
type Pairs = map[string]string
// Expander expands the variables in a string.
type Expander func(string) string
// Replacer replace string.
type Replacer interface {
Replace(string) string
}
// BeforeScenario expands variables from a provider that will be called only once before every scenario.
func BeforeScenario(provide func() Pairs) func() Expander {
return func() Expander {
return mapExpander(provide())
}
}
func placeholder(name string) string {
return fmt.Sprintf("%s%s", varDelimiter, name)
}
// runtimeExpander expands variables from a provider.
func runtimeExpander(provide func() Pairs) Expander {
return func(s string) string {
return mapExpander(provide())(s)
}
}
// mapExpander initiates a new variable expander from a map of values.
func mapExpander(pairs Pairs) Expander {
oldNew := make([]string, 0, 2*len(pairs))
for k, v := range pairs {
oldNew = append(oldNew, placeholder(k), v)
}
return strings.NewReplacer(oldNew...).Replace
}
func chainExpanders(expanders ...interface{}) Expander {
l := make([]Expander, 0, len(expanders))
for _, e := range expanders {
l = append(l, newExpander(e))
}
return func(s string) string {
for _, expand := range l {
s = expand(s)
}
return s
}
}
func newExpander(e interface{}) Expander {
switch e := e.(type) {
case Pairs:
return mapExpander(e)
case func() Pairs:
return runtimeExpander(e)
case func() Expander:
return e()
case Replacer:
return e.Replace
case Expander:
return e
case func(string) string:
return e
}
panic(fmt.Errorf("%w: got %T", ErrUnsupportedExpander, e))
}
func doExpand(expand Expander, s string) string {
return expand(s)
}