/
export_utility.go
105 lines (90 loc) · 2.39 KB
/
export_utility.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
/*
Copyright (C) 2018 OpenControl Contributors. See LICENSE.md for license.
*/
package export
import (
"strconv"
"strings"
)
////////////////////////////////////////////////////////////////////////
// Package functions
// escapedPrefixMatch - escape a string in prep for regexp
func escapeStringForRegexp(a string) string {
specialChars := []string{"(", ")", ".", "?"}
for i := range specialChars {
specialChar := specialChars[i]
a = strings.Replace(a, specialChar, "\\"+specialChar, -1)
}
return a
}
// stringInSlice - is a string in a list?
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
// utility function to return an error list from single error
func returnErrors(err error) []error {
var result []error
result = append(result, err)
return result
}
// isScalar - is a given value a supported scalar?
func isScalar(value interface{}) bool {
// first, check all supported simple types
result := false
if _, okStr := value.(string); okStr {
result = true
} else if _, okFloat64 := value.(float64); okFloat64 {
result = true
} else if _, okBool := value.(bool); okBool {
result = true
}
return result
}
// flattenDiscoverKey - handle what a flattened array key should be
func discoverKey(config *Config, value interface{}, lkey string, index int) string {
// default value
defaultKey := lkey + strconv.Itoa(index)
// only process if we must infer keys
if !config.InferKeys {
return defaultKey
}
// we can only handle maps
input, okMapType := value.(map[string]interface{})
if !okMapType {
return defaultKey
}
// determine weights for the keyname to use
const invalidKeyName = "invalid"
const invalidKeyWeight = 99
keyWeights := make(map[string]int)
keyWeights["key"] = 0
keyWeights["control_key"] = 1
keyWeights["name"] = 2
// iterate over the map, just looking at the keys
foundKeyWeight := invalidKeyWeight
foundKeyName := invalidKeyName
for rkey, rvalue := range input {
// must be a string scalar
_, isStr := rvalue.(string)
if !isStr {
continue
}
if curKeyWeight, hasKey := keyWeights[rkey]; hasKey {
if curKeyWeight < foundKeyWeight {
foundKeyWeight = curKeyWeight
foundKeyName = rvalue.(string)
}
}
}
// return the bestest key we can find
if foundKeyWeight != invalidKeyWeight {
return lkey + foundKeyName
}
// return the default
return defaultKey
}