/
helpers.go
92 lines (82 loc) · 2.1 KB
/
helpers.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
package config
import (
"bytes"
"fmt"
"strings"
)
func isDynamicHostname(hostname string) bool {
return strings.Contains(hostname, `*`) ||
strings.Contains(hostname, `[`) ||
strings.Contains(hostname, `]`)
}
// BoolVal returns a boolean matching a configuration string
func BoolVal(input string) bool {
input = cleanupValue(input)
trueValues := []string{"yes", "ok", "true", "1", "enabled"}
for _, val := range trueValues {
if val == input {
return true
}
}
return false
}
func cleanupValue(input string) string {
return strings.TrimSpace(strings.ToLower(input))
}
// stringComment splits comment strings into <1024 char lines
func stringComment(name, value string) string {
maxLength := 1024 - len(name) - 9
ret := []string{}
for _, line := range splitSubN(value, maxLength) {
ret = append(ret, fmt.Sprintf(" # %s: %s", name, line))
}
return strings.Join(ret, "\n") + "\n"
}
// sliceComment splits comment strings into <1024 char lines
func sliceComment(name string, slice []string) string {
var (
bundles [][]string
bundleIdx = 0
curLen = 0
maxLength = 1024 - len(name) - 12
)
bundles = append(bundles, []string{})
for _, item := range slice {
for _, line := range strings.Split(item, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
if curLen+len(line) >= maxLength {
bundleIdx++
bundles = append(bundles, []string{})
curLen = 0
}
bundles[bundleIdx] = append(bundles[bundleIdx], line)
curLen += len(line) + 2
}
}
ret := []string{}
for _, bundle := range bundles {
ret = append(ret, fmt.Sprintf(" # %s: [%s]", name, strings.Join(bundle, ", ")))
}
return strings.Join(ret, "\n") + "\n"
}
// splitSubN splits a string by length
// from: http://stackoverflow.com/questions/25686109/split-string-by-length-in-golang
func splitSubN(s string, n int) []string {
sub := ""
subs := []string{}
runes := bytes.Runes([]byte(s))
l := len(runes)
for i, r := range runes {
sub = sub + string(r)
if (i+1)%n == 0 {
subs = append(subs, sub)
sub = ""
} else if (i + 1) == l {
subs = append(subs, sub)
}
}
return subs
}