-
Notifications
You must be signed in to change notification settings - Fork 60
/
file_handler.go
109 lines (91 loc) · 2.58 KB
/
file_handler.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 util
import (
"fmt"
"path/filepath"
"github.com/go-chassis/openlog"
"gopkg.in/yaml.v2"
)
//FileHandler decide how to convert a file content into key values
//archaius will manage file content as those key values
type FileHandler func(filePath string, content []byte) (map[string]interface{}, error)
//Convert2JavaProps is a FileHandler
//it convert the yaml content into java props
func Convert2JavaProps(p string, content []byte) (map[string]interface{}, error) {
configMap := make(map[string]interface{})
ss := yaml.MapSlice{}
err := yaml.Unmarshal([]byte(content), &ss)
if err != nil {
return nil, fmt.Errorf("yaml unmarshal [%s] failed, %s", content, err)
}
configMap = retrieveItems("", ss)
return configMap, nil
}
func retrieveItems(prefix string, subItems yaml.MapSlice) map[string]interface{} {
if prefix != "" {
prefix += "."
}
result := map[string]interface{}{}
for _, item := range subItems {
//check the item key first
k, ok := checkKey(item.Key)
if !ok {
continue
}
//If there are sub-items existing
switch item.Value.(type) {
//sub items in a map
case yaml.MapSlice:
subResult := retrieveItems(prefix+item.Key.(string), item.Value.(yaml.MapSlice))
for k, v := range subResult {
result[k] = v
}
// sub items in an array
case []interface{}:
keyVal := item.Value.([]interface{})
result[prefix+k] = retrieveItemInSlice(keyVal)
// sub item is a string
case string:
result[prefix+k] = ExpandValueEnv(item.Value.(string))
// sub item in other type
default:
result[prefix+k] = item.Value
}
}
return result
}
func checkKey(key interface{}) (string, bool) {
k, ok := key.(string)
if !ok {
openlog.Error("yaml tag is not string", openlog.WithTags(
openlog.Tags{
"key": key,
},
))
return "", false
}
return k, true
}
func retrieveItemInSlice(value []interface{}) []interface{} {
for i, v := range value {
switch v.(type) {
case yaml.MapSlice:
value[i] = retrieveItems("", v.(yaml.MapSlice))
case string:
value[i] = ExpandValueEnv(v.(string))
default:
//do nothing
}
}
return value
}
//UseFileNameAsKeyContentAsValue is a FileHandler, it sets the yaml file name as key and the content as value
func UseFileNameAsKeyContentAsValue(p string, content []byte) (map[string]interface{}, error) {
_, filename := filepath.Split(p)
configMap := make(map[string]interface{})
configMap[filename] = content
return configMap, nil
}
//Convert2configMap is legacy API
func Convert2configMap(p string, content []byte) (map[string]interface{}, error) {
return UseFileNameAsKeyContentAsValue(p, content)
}