forked from rockintest/rocktest-go
/
mapLookup.go
79 lines (62 loc) · 1.29 KB
/
mapLookup.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
package text
import (
"os"
"regexp"
log "github.com/sirupsen/logrus"
)
type MapLookup struct {
Map map[string]string
}
func NewMapLookup(m map[string]string) *MapLookup {
ret := new(MapLookup)
ret.Map = m
return ret
}
func (l MapLookup) getValue(s string) (string, bool) {
ret, ok := l.Map[s]
if ok {
return ret, ok
} else {
env := os.Getenv(s)
if env == "" {
return s, false
} else {
return env, true
}
}
}
func (l MapLookup) Lookup(s string) (string, bool, error) {
// Do we have expression like
// ${variable?value if set::value if not set} or
// ${variable::value if not set}
re, err := regexp.Compile(`([^?]+)(?:\?(.*))?::(.*)`)
if err != nil {
log.Errorf(err.Error())
return s, false, nil
}
if re.Match([]byte(s)) {
res := re.FindAllStringSubmatch(s, -1)
name := res[0][1]
valset := res[0][2]
valunset := res[0][3]
log.Tracef("%v", res)
log.Tracef("Name: \"%s\", Val is set: \"%s\", val if not set: \"%s\"", name, valset, valunset)
val, found := l.getValue(name)
if found {
if valset != "" {
return valset, true, nil
} else {
return val, true, nil
}
} else {
if valunset != "" {
return valunset, true, nil
} else {
return s, false, nil
}
}
} else {
str, ok := l.getValue(s)
return str, ok, nil
}
}