forked from ochinchina/supervisord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_expression.go
91 lines (75 loc) · 2.07 KB
/
string_expression.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
package config
import (
"fmt"
"os"
"strconv"
"strings"
)
// StringExpression replace the python String like "%(var)s" to string
type StringExpression struct {
env map[string]string // the environment variable used to replace the var in the python expression
}
// NewStringExpression create a new StringExpression with the environment variables
func NewStringExpression(envs ...string) *StringExpression {
se := &StringExpression{env: make(map[string]string)}
for _, env := range os.Environ() {
t := strings.SplitN(env, "=", 2)
se.env["ENV_"+t[0]] = t[1]
}
n := len(envs)
for i := 0; i+1 < n; i += 2 {
se.env[envs[i]] = envs[i+1]
}
hostname, err := os.Hostname()
if err == nil {
se.env["host_node_name"] = hostname
}
return se
}
// Add adds environment variable (key,value)
func (se *StringExpression) Add(key string, value string) *StringExpression {
se.env[key] = value
return se
}
// Eval substitutes "%(var)s" in given string with evaluated values, and returns resulting string
func (se *StringExpression) Eval(s string) (string, error) {
for {
// find variable start indicator
start := strings.Index(s, "%(")
if start == -1 {
return s, nil
}
end := start + 1
n := len(s)
// find variable end indicator
for end < n && s[end] != ')' {
end++
}
// find the type of the variable
typ := end + 1
for typ < n && !((s[typ] >= 'a' && s[typ] <= 'z') || (s[typ] >= 'A' && s[typ] <= 'Z')) {
typ++
}
// evaluate the variable
if typ < n {
varName := s[start+2 : end]
varValue, ok := se.env[varName]
if !ok {
return "", fmt.Errorf("fail to find the environment variable %s", varName)
}
if s[typ] == 'd' {
i, err := strconv.Atoi(varValue)
if err != nil {
return "", fmt.Errorf("can't convert %s to integer", varValue)
}
s = s[0:start] + fmt.Sprintf("%"+s[end+1:typ+1], i) + s[typ+1:]
} else if s[typ] == 's' {
s = s[0:start] + varValue + s[typ+1:]
} else {
return "", fmt.Errorf("not implement type:%v", s[typ])
}
} else {
return "", fmt.Errorf("invalid string expression format")
}
}
}