forked from hidevopsio/hiboot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
replacer.go
229 lines (206 loc) · 6.26 KB
/
replacer.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// Copyright 2018 John Deng (hi.devops.io@gmail.com).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package replacer provides utilities that replace the reference and environment variables with its value
package replacer
import (
"errors"
"fmt"
"github.com/hidevopsio/hiboot/pkg/utils/reflector"
"os"
"reflect"
"regexp"
"strings"
)
const (
EmptyString = ""
)
var (
NilPointerError = errors.New("nil pointer error")
InvalidObjectError = errors.New("invalid object")
compiledRegExp = regexp.MustCompile(`\$\{(.*?)\}`)
)
// ParseVariables parse reference and env variables
func ParseVariables(src string, re *regexp.Regexp) [][]string {
matches := re.FindAllStringSubmatch(src, -1)
if matches == nil {
return nil
}
return matches
}
func GetMatches(source string) [][]string {
return ParseVariables(source, compiledRegExp)
}
// ReplaceStringVariables replace reference and env variables
func ReplaceStringVariables(source string, t interface{}) interface{} {
matches := ParseVariables(source, compiledRegExp)
for _, match := range matches {
varFullName := match[0]
// replace references
varName := match[1]
// check if it contains default value
var defaultValue string
n := strings.Index(varName, ":")
if n > 0 {
defaultValue = varName[n+1:]
varName = varName[:n]
//log.Debugf("name: %v, default value: %v", varName, defaultValue)
}
vars := strings.SplitN(varName, ".", -1)
refValue := ParseReferences(t, vars)
rvType := reflect.TypeOf(refValue)
var newValue string
switch rvType.Kind() {
case reflect.String:
newValue = refValue.(string)
// replace env
if newValue != "" {
source = strings.Replace(source, varFullName, newValue, -1)
}
case reflect.Slice:
return refValue
}
envValue := os.Getenv(varName)
// check if varName == strings.ToUpper(varName), the assume that varName is environment variable
if envValue != "" || varName == strings.ToUpper(varName) {
source = strings.Replace(source, varFullName, envValue, -1)
}
if envValue == "" && newValue == "" && defaultValue != "" {
source = strings.Replace(source, varFullName, defaultValue, -1)
}
}
return source
}
// GetFieldValue get filed value in reflected format
func GetFieldValue(f interface{}, name string) (retVal reflect.Value, err error) {
r := reflect.ValueOf(f)
if !r.IsNil() && r.IsValid() {
retVal = reflect.Indirect(r).FieldByName(name)
} else {
//log.Warn("invalid value")
err = InvalidObjectError
}
return
}
func GetReferenceValue(object interface{}, name string) (reflect.Value, error) {
capitalizedVarName := strings.Title(name)
retVal, err := GetFieldValue(object, capitalizedVarName)
if err == nil {
for _, field := range reflector.DeepFields(reflect.TypeOf(object)) {
if field.Tag.Get("mapstructure") == name {
retVal, err = GetFieldValue(object, field.Name)
break
}
}
}
return retVal, err
}
// ParseReferences parse the variable references
func ParseReferences(st interface{}, varName []string) interface{} {
var parent interface{}
parent = st
for _, vn := range varName {
field, err := GetReferenceValue(parent, vn)
if err == nil {
k := reflector.GetKindByValue(field)
switch k {
case reflect.String, reflect.Int, reflect.Float32:
fv := fmt.Sprintf("%v", field.Interface())
return fv
case reflect.Slice:
return field.Interface()
case reflect.Invalid:
return EmptyString
default:
// check if field is ptr
parent = field.Addr().Interface()
}
}
}
return EmptyString
}
// ReplaceMap replace references and env variables
func ReplaceMap(m map[string]interface{}, root interface{}) error {
if root == nil {
return NilPointerError
}
for k, v := range m {
// log.Println(k, ": ", v)
vt := reflect.TypeOf(v)
if vt.Kind() == reflect.String {
newStr := ReplaceStringVariables(v.(string), root)
m[k] = newStr
} else if vt.Kind() == reflect.Map {
mv := v.(map[string]interface{})
ReplaceMap(mv, root)
}
}
return nil
}
// Replace given env and reference variables inside specific struct
func Replace(to interface{}, root interface{}) error {
return reflector.ValidateReflectType(to, func(value *reflect.Value, reflectType reflect.Type, fieldSize int, isSlice bool) error {
for i := 0; i < fieldSize; i++ {
var dst reflect.Value
if isSlice {
dst = reflector.Indirect(value.Index(i))
//log.Debug(dst.Interface())
// TODO: refactoring below code
dstType := dst.Type().Name()
dstValue := dst.Interface()
dv := fmt.Sprintf("%v", dstValue)
//log.Debug("dstValue", dstValue)
if dst.Kind() != reflect.String {
child := dst.Addr().Interface()
Replace(child, root)
} else {
if dv != "" && dstType == "string" && dst.IsValid() && dst.CanSet() {
newStr := ReplaceStringVariables(dv, root)
dst.SetString(newStr.(string))
}
}
} else {
dst = reflector.Indirect(*value)
}
for _, field := range reflector.DeepFields(reflectType) {
fieldName := field.Name
//log.Debug("fieldName: ", fieldName)
if dstField := dst.FieldByName(fieldName); dstField.IsValid() && dstField.CanSet() {
fieldValue := dstField.Interface()
//log.Debug("fieldValue: ", fieldValue)
kind := dstField.Kind()
switch kind {
case reflect.String:
fv := fmt.Sprintf("%v", fieldValue)
newStr := ReplaceStringVariables(fv, root)
dstField.SetString(newStr.(string))
//case reflect.Slice:
// log.Debug("slice")
case reflect.Map:
childMap := dstField.Interface()
if !dstField.IsNil() {
ReplaceMap(childMap.(map[string]interface{}), root)
}
default:
//log.Debug(fieldName, " is a ", kind)
child := dstField.Addr()
if child.CanInterface() {
Replace(child.Interface(), root)
}
}
}
}
}
return nil
})
}