-
Notifications
You must be signed in to change notification settings - Fork 19
/
configparser.go
316 lines (272 loc) · 7.63 KB
/
configparser.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package configparser
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"regexp"
"sort"
"strings"
"unicode"
)
var (
sectionHeader = regexp.MustCompile(`^\[([^]]+)\]`)
interpolater = regexp.MustCompile(`%\(([^)]*)\)s`)
)
var boolMapping = map[string]bool{
"1": true,
"true": true,
"on": true,
"yes": true,
"0": false,
"false": false,
"off": false,
"no": false,
}
// Dict is a simple string->string map.
type Dict map[string]string
// Config represents a Python style configuration file.
type Config map[string]*Section
// ConfigParser ties together a Config and default values for use in
// interpolated configuration values.
type ConfigParser struct {
config Config
defaults *Section
opt *options
}
// Keys returns a sorted slice of keys
func (d Dict) Keys() []string {
keys := make([]string, 0, len(d))
for key := range d {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func getNoSectionError(section string) error {
return fmt.Errorf("no section: %q", section)
}
func getNoOptionError(section, option string) error {
return fmt.Errorf("no option %q in section: %q", option, section)
}
// New creates a new ConfigParser.
func New() *ConfigParser {
return &ConfigParser{
config: make(Config),
defaults: newSection(defaultSectionName),
opt: defaultOptions(),
}
}
// NewWithOptions creates a new ConfigParser with options.
func NewWithOptions(opts ...optFunc) *ConfigParser {
opt := defaultOptions()
for _, fn := range opts {
fn(opt)
}
return &ConfigParser{
config: make(Config),
defaults: newSection(opt.defaultSection),
opt: opt,
}
}
// NewWithDefaults allows creation of a new ConfigParser with a pre-existing Dict.
func NewWithDefaults(defaults Dict) (*ConfigParser, error) {
p := New()
for key, value := range defaults {
if err := p.defaults.Add(key, value); err != nil {
return nil, fmt.Errorf("failed to add %q to %q: %w", key, value, err)
}
}
return p, nil
}
// NewConfigParserFromFile creates a new ConfigParser struct populated from the
// supplied filename.
func NewConfigParserFromFile(filename string) (*ConfigParser, error) {
p, err := Parse(filename)
if err != nil {
return nil, err
}
return p, nil
}
// ParseReader parses a ConfigParser from the provided input.
func ParseReader(in io.Reader) (*ConfigParser, error) {
p := New()
err := p.ParseReader(in)
return p, err
}
// ParseReaderWithOptions parses a ConfigParser from the provided input with given options.
func ParseReaderWithOptions(in io.Reader, opts ...optFunc) (*ConfigParser, error) {
p := NewWithOptions(opts...)
err := p.ParseReader(in)
return p, err
}
// Parse takes a filename and parses it into a ConfigParser value.
func Parse(filename string) (*ConfigParser, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
p, err := ParseReader(file)
if err != nil {
return nil, err
}
return p, nil
}
// ParseWithOptions takes a filename and parses it into a ConfigParser value with given options.
func ParseWithOptions(filename string, opts ...optFunc) (*ConfigParser, error) {
p := NewWithOptions(opts...)
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
err = p.ParseReader(bytes.NewReader(data))
return p, err
}
func writeSection(file *os.File, delimiter string, section *Section) error {
_, err := file.WriteString(fmt.Sprintf("[%s]\n", section.Name))
if err != nil {
return err
}
for _, option := range section.Options() {
_, err = file.WriteString(fmt.Sprintf("%s %s %s\n", option, delimiter, section.options[option]))
if err != nil {
return err
}
}
_, err = file.WriteString("\n")
return err
}
// SaveWithDelimiter writes the current state of the ConfigParser to the named
// file with the specified delimiter.
func (p *ConfigParser) SaveWithDelimiter(filename, delimiter string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
if len(p.defaults.Options()) > 0 {
err = writeSection(f, delimiter, p.defaults)
if err != nil {
return err
}
}
for _, s := range p.Sections() {
err = writeSection(f, delimiter, p.config[s])
if err != nil {
return err
}
}
return nil
}
// ParseReader parses data into ConfigParser from provided reader.
func (p *ConfigParser) ParseReader(in io.Reader) error {
reader := bufio.NewReader(in)
var lineNo int
var curSect *Section
var key, value string
keyValue := regexp.MustCompile(
fmt.Sprintf(
`([^%[1]s\s][^%[1]s]*)\s*(?P<vi>[%[1]s]+)\s*(.*)$`,
p.opt.delimiters,
),
)
keyWNoValue := regexp.MustCompile(
fmt.Sprintf(
`([^%[1]s\s][^%[1]s]*)\s*((?P<vi>[%[1]s]+)\s*(.*)$)?`,
p.opt.delimiters,
),
)
for {
l, _, err := reader.ReadLine()
if err != nil {
// If error is end of file, then current key should be checked before return.
if errors.Is(err, io.EOF) {
if key != "" {
if err := curSect.Add(key, value); err != nil {
return fmt.Errorf("failed to add %q = %q: %w", key, value, err)
}
}
return nil
}
return err
}
lineNo++
// Ensures regex will match and get copy of the line without space characters.
line := strings.TrimFunc(string(l), unicode.IsSpace)
// Skip comment lines.
if p.opt.commentPrefixes.HasPrefix(line) {
continue
}
// Check if key-value pair is currently in parsing process.
if key != "" {
if p.opt.multilinePrefixes.HasPrefix(string(l)) ||
(line == "" && p.opt.emptyLines) {
// If current key was defined and line starts with one of the
// multiline prefixes or it is an empty string which is allowed within values,
// then adding this line to the value.
if curSect == nil {
return fmt.Errorf("missing section header: %d %s", lineNo, line)
}
value += "\n" + p.opt.inlineCommentPrefixes.Split(line)
// If current line is added as a value part, may continue.
continue
} else {
// If key was defined, but current line does not start with any of the
// multiline prefixes or it is an empty line which is not allowed within values,
// then it counts as the value parsing is finished and it can be added
// to the current section.
if err := curSect.Add(key, value); err != nil {
return fmt.Errorf("failed to add %q = %q: %w", key, value, err)
}
// Drop key-value pair to empty strings.
key, value = "", ""
}
}
// If key was not defined and current line is empty it can be skipped.
if line == "" {
continue
}
if match := sectionHeader.FindStringSubmatch(line); len(match) > 0 {
section := p.opt.inlineCommentPrefixes.Split(match[1])
if section == p.opt.defaultSection {
curSect = p.defaults
} else if _, present := p.config[section]; !present {
curSect = newSection(section)
p.config[section] = curSect
} else if p.opt.strict {
return fmt.Errorf(
"section %q already exists and strict flag was set", section,
)
}
// Since section was defined on current line, may continue.
continue
}
if match := keyValue.FindStringSubmatch(line); len(match) > 0 {
if curSect == nil {
return fmt.Errorf("missing section header: %d %s", lineNo, line)
}
key = strings.TrimSpace(match[1])
if p.opt.strict {
if err := p.inOptions(key); err != nil {
return err
}
}
value = p.opt.inlineCommentPrefixes.Split(match[3])
} else if match = keyWNoValue.FindStringSubmatch(line); len(match) > 0 &&
p.opt.allowNoValue {
if curSect == nil {
return fmt.Errorf("missing section header: %d %s", lineNo, line)
}
key = strings.TrimSpace(match[1])
if p.opt.strict {
if err := p.inOptions(key); err != nil {
return err
}
}
value = p.opt.inlineCommentPrefixes.Split(match[4])
}
}
}