-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.go
81 lines (71 loc) · 1.95 KB
/
file.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
package flagconfig
import (
"bufio"
"bytes"
"io"
"os"
"strings"
)
// dumpExampleConfig returns the string representation of a configuration file
// with all parameters filled in with their default values
func (f *FlagConfig) dumpExampleConfig(projname string) string {
var buffer bytes.Buffer
buffer.WriteString("\n")
buffer.WriteString("#####################################\n")
buffer.WriteString("### " + projname + " configuration\n")
buffer.WriteString("#####################################\n")
buffer.WriteString("\n")
for _, param := range f.fullConfig {
if _, ok := f.cliOnly[param.Name()]; ok {
continue
}
buffer.WriteString("# " + param.Description() + "\n")
if defaults, ok := param.DefaultAsStrings(); ok {
if len(defaults) > 0 {
for i := range defaults {
buffer.WriteString(param.Name() + ": " + defaults[i] + "\n")
}
} else {
buffer.WriteString("# " + param.Name() + ": <something>\n")
}
} else {
buffer.WriteString(param.Name() + ": <required>\n")
}
buffer.WriteString("\n")
}
return buffer.String()
}
func setOrAppend(m map[string][]string, name, val string) {
if _, ok := m[name]; !ok {
m[name] = make([]string, 0, 8)
}
m[name] = append(m[name], val)
}
// readConfig returns a map of the key/values found in a given configuration file.
// Note: these key/values don't have to actually correspond to expected parameters,
// that parsing is done elsewhere
func readConfig(file string) (map[string][]string, error) {
fi, err := os.Open(file)
ret := map[string][]string{}
if err != nil {
return ret, err
}
r := bufio.NewReader(fi)
for {
line, err := r.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
line = strings.TrimRight(line, "\n")
if len(line) > 0 && line[0] != '#' {
spl := strings.SplitN(line, ":", 2)
name := strings.Trim(spl[0], " \t")
val := strings.Trim(spl[1], " \t")
setOrAppend(ret, name, val)
}
}
return ret, nil
}