Repository navigation
Expand file tree
/
Copy pathlexer.go
More file actions
524 lines (477 loc) · 15.3 KB
/
Copy pathlexer.go
File metadata and controls
524 lines (477 loc) · 15.3 KB
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
package ini
import (
"errors"
"fmt"
"io"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
type tokenKind uint8
const (
tokEOF tokenKind = iota
tokSection // [name] ; comment
tokKey // name = value ; comment
tokBooleanKey // name
tokNestedValue // indented line under a key with an empty value
tokRawBody // body of an unparseable section
)
type token struct {
kind tokenKind
name string
value string
comment string // for tokEOF, the comment lines after the last key
raw bool // for tokSection, the section is unparseable
line, column int // where the token starts, both from 1
}
// errorf reports err at the position of the token.
func (t token) errorf(err error) error {
return &ParseError{Line: t.line, Column: t.column, Err: err}
}
// lexer turns INI input into tokens. Its rules, and the order in which they
// apply, are those of gopkg.in/ini.v1, apart from the fixes listed in
// docs/migrate-v1-to-v2.md.
type lexer struct {
src string
pos int // offset of the next unread byte
eof bool // the last line read had no '\n'
opts *loadOptions
line int // number of the last line read, from 1
comment []string // comment pieces for the next section or key
lastValueEmpty bool // the last key had an empty value, so indented lines are nested values
inRaw bool // inside an unparseable section
raw strings.Builder
}
// next returns the next token, or tokEOF at the end of input.
func (l *lexer) next() (token, error) {
for !l.eof {
raw := l.readLine()
lineNum := l.line
column := func(s string) int { return utf8.RuneCountInString(raw[:len(raw)-len(s)]) + 1 }
if l.opts.AllowNestedValues && l.lastValueEmpty && raw != "" && (raw[0] == ' ' || raw[0] == '\t') {
value := strings.TrimSpace(raw)
return token{kind: tokNestedValue, value: value, line: lineNum, column: column(strings.TrimLeftFunc(raw, unicode.IsSpace))}, nil
}
line := strings.TrimLeftFunc(raw, unicode.IsSpace)
var tok token
var err error
switch {
case line == "":
continue
case l.startsWithCommentSymbol(line):
// Keep the line break so comment lines stay on separate lines.
l.comment = append(l.comment, line)
continue
case line[0] == '[':
if l.raw.Len() > 0 {
l.unread(raw)
return l.rawBody(), nil
}
tok, err = l.section(line)
case l.inRaw:
l.raw.WriteString(line)
continue
default:
var ok bool
if tok, ok, err = l.key(line); !ok && err == nil {
continue
}
}
if err != nil {
return token{}, &ParseError{Line: lineNum, Column: column(line), Err: err}
}
tok.line, tok.column = lineNum, column(line)
return tok, nil
}
if l.raw.Len() > 0 {
return l.rawBody(), nil
}
return token{kind: tokEOF, comment: l.takeComment()}, nil
}
// readLine returns the next line including its '\n', if any.
func (l *lexer) readLine() string {
rest := l.src[l.pos:]
i := strings.IndexByte(rest, '\n')
if i < 0 {
l.pos, l.eof = len(l.src), true
l.line++
return rest
}
l.pos += i + 1
l.line++
return rest[:i+1]
}
// unread puts back the line just read.
func (l *lexer) unread(line string) {
l.pos -= len(line)
l.eof = false
l.line--
}
func (l *lexer) startsWithCommentSymbol(line string) bool {
return startsWithAny(line, l.opts.CommentSymbols)
}
// startsWithAny reports whether the first character of s is one of chars.
func startsWithAny(s, chars string) bool {
r, _ := utf8.DecodeRuneInString(s)
return r != utf8.RuneError && strings.ContainsRune(chars, r)
}
func (l *lexer) takeComment() string {
c := strings.TrimSpace(strings.Join(l.comment, ""))
l.comment = l.comment[:0]
return c
}
func (l *lexer) rawBody() token {
t := token{kind: tokRawBody, value: l.raw.String()}
l.raw.Reset()
return t
}
// section reads a "[name] ; comment" line. The name ends at the last ']'.
func (l *lexer) section(line string) (token, error) {
closeIdx := strings.LastIndexByte(line, ']')
if closeIdx == -1 {
return token{}, fmt.Errorf("unclosed section: %s", line)
}
name := line[1:closeIdx]
if i := strings.IndexAny(line[closeIdx+1:], l.opts.CommentSymbols); i > -1 {
l.comment = append(l.comment, line[closeIdx+1+i:])
}
l.lastValueEmpty = false
l.inRaw = false
for _, s := range l.opts.UnparseableSections {
if s == name || ((l.opts.Insensitive || l.opts.InsensitiveSections) && strings.EqualFold(s, name)) {
l.inRaw = true
break
}
}
return token{kind: tokSection, name: name, comment: l.takeComment(), raw: l.inRaw}, nil
}
// key reads a "name = value" line, or a boolean key when the line has no
// delimiter. ok is false for a line that SkipUnrecognizableLines skips.
func (l *lexer) key(line string) (_ token, ok bool, _ error) {
name, offset, err := readKeyName(l.opts.KeyValueDelimiters, line)
switch {
case err == nil:
value, err := l.readValue(line[offset:])
if err != nil {
return token{}, false, err
}
l.lastValueEmpty = value == ""
return token{kind: tokKey, name: name, value: value, comment: l.takeComment()}, true, nil
case errors.Is(err, ErrDelimiterNotFound) && l.opts.AllowBooleanKeys:
// The whole line is the key name, read like a value.
name, err := l.readValue(line)
if err != nil {
return token{}, false, err
}
return token{kind: tokBooleanKey, name: name, comment: l.takeComment()}, true, nil
case (errors.Is(err, ErrDelimiterNotFound) || errors.Is(err, ErrEmptyKeyName)) && l.opts.SkipUnrecognizableLines:
return token{}, false, nil
}
return token{}, false, err
}
// readValue reads a value that starts in "in", the rest of the current line,
// and any following lines it spans. The rules apply in a fixed order, which
// decides the result when they overlap: a value is either quoted, continued
// with a backslash, or plain. For a plain value the inline comment is cut
// before surrounding quotes are stripped, so `"a;b" ;c` is `a;b` with comment
// `;c`, but `"a;b" x` is `"a` with comment `;b" x`.
func (l *lexer) readValue(in string) (string, error) {
line := strings.TrimLeftFunc(in, unicode.IsSpace)
if line == "" {
if l.opts.AllowPythonMultilineValues && strings.HasSuffix(in, "\n") {
return l.readPythonMultilines(""), nil
}
return "", nil
}
if q := l.valueQuote(line); q != "" {
return l.readQuoted(line, q)
}
endsLine := line[len(line)-1] == '\n'
line = strings.TrimSpace(line)
if !l.opts.IgnoreContinuation && strings.HasSuffix(line, `\`) {
return l.readContinuationLines(line[:len(line)-1]), nil
}
if !l.opts.IgnoreInlineComment {
line = l.cutInlineComment(line)
}
switch {
case !l.opts.PreserveSurroundingQuotes && (hasSurroundedQuote(line, '\'') || hasSurroundedQuote(line, '"')):
return line[1 : len(line)-1], nil
case l.opts.UnescapeValueCommentSymbols:
// Last symbol first, so \; is unescaped before \#.
symbols := []rune(l.opts.CommentSymbols)
for i := len(symbols) - 1; i >= 0; i-- {
c := string(symbols[i])
line = strings.ReplaceAll(line, `\`+c, c)
}
return line, nil
case l.opts.AllowPythonMultilineValues && endsLine:
return l.readPythonMultilines(line), nil
}
return line, nil
}
// valueQuote returns the quote that opens line as a quoted value: `"""`, "`",
// or `"` with UnescapeValueDoubleQuotes. Single quotes and plain double
// quotes are handled later, as surrounding quotes.
func (l *lexer) valueQuote(line string) string {
switch {
case len(line) > 3 && line[:3] == `"""`:
return `"""`
case line[0] == '`':
return "`"
case l.opts.UnescapeValueDoubleQuotes && line[0] == '"':
return `"`
}
return ""
}
// readQuoted reads a value that starts with quote q and ends at the last q on
// the same line or, failing that, the first later line containing q.
func (l *lexer) readQuoted(line, q string) (string, error) {
rest := line[len(q):]
if i := strings.LastIndex(rest, q); i > -1 {
if q == `"` {
return strings.ReplaceAll(rest[:i], `\"`, `"`), nil
}
return rest[:i], nil
}
var b strings.Builder
b.WriteString(rest)
for {
next := l.readLine()
i := strings.LastIndex(next, q)
switch {
case i == -1:
b.WriteString(next)
if l.eof {
return "", fmt.Errorf("missing closing key quote from %q to %q", line, next)
}
case !l.opts.IgnoreContinuation && strings.HasSuffix(strings.TrimSpace(next[i+len(q):]), `\`):
// A backslash after the closing quote continues the value.
b.WriteString(next)
default:
b.WriteString(next[:i])
if j := strings.IndexAny(next[i:], l.opts.CommentSymbols); j > -1 {
l.comment = append(l.comment, strings.TrimSpace(next[i+j:]))
}
return b.String(), nil
}
}
}
// cutInlineComment moves a trailing "# ..." or "; ..." of a plain value to
// the comment. With SpaceBeforeInlineComment the symbol must follow a space.
// A value in single or double quotes keeps the comment symbols inside them,
// when only spaces or a comment follow the closing quote.
func (l *lexer) cutInlineComment(line string) string {
if line[0] == '\'' || line[0] == '"' {
if j := strings.IndexByte(line[1:], line[0]); j > -1 {
end := j + 2
if rest := line[end:]; strings.TrimSpace(rest) == "" {
return line
} else if i := l.inlineCommentIndex(rest); i > -1 && strings.TrimSpace(rest[:i]) == "" {
l.comment = append(l.comment, rest[i:])
return line[:end]
}
}
}
i := l.inlineCommentIndex(line)
if i == -1 {
return line
}
l.comment = append(l.comment, line[i:])
return strings.TrimSpace(line[:i])
}
// inlineCommentIndex returns the index of the first comment symbol in s, or
// with SpaceBeforeInlineComment of the first one after a space, or -1.
func (l *lexer) inlineCommentIndex(s string) int {
if !l.opts.SpaceBeforeInlineComment {
return strings.IndexAny(s, l.opts.CommentSymbols)
}
for i := 0; i < len(s); i++ {
if s[i] == ' ' && startsWithAny(s[i+1:], l.opts.CommentSymbols) {
return i
}
}
return -1
}
// readContinuationLines appends trimmed following lines while they end with
// a backslash, up to the first line that doesn't or a blank line. val is the
// first line without its backslash.
func (l *lexer) readContinuationLines(val string) string {
var b strings.Builder
b.WriteString(val)
for {
next := strings.TrimSpace(l.readLine())
if next == "" {
return b.String()
}
if !strings.HasSuffix(next, `\`) {
b.WriteString(next)
return b.String()
}
b.WriteString(next[:len(next)-1])
}
}
// readPythonMultilines appends the following lines that start with a space,
// tab or form feed, each on a new line with its indentation kept. Empty
// lines followed by such a line are part of the value too, as in Python's
// configparser.
func (l *lexer) readPythonMultilines(line string) string {
var b strings.Builder
b.WriteString(line)
for {
rest := l.src[l.pos:]
empty := len(rest) - len(strings.TrimLeft(rest, "\r\n"))
if empty == len(rest) || strings.IndexByte(" \t\f", rest[empty]) == -1 {
return b.String()
}
if empty > 0 && rest[empty-1] != '\n' {
// A lone "\r" before the indented line isn't an empty line.
return b.String()
}
for range empty {
if l.src[l.pos] == '\n' {
l.line++
b.WriteByte('\n')
}
l.pos++
}
next := strings.TrimSuffix(l.readLine(), "\n")
b.WriteByte('\n')
b.WriteString(next)
}
}
// skipBOM strips the UTF-8, UTF-16 LE and UTF-16 BE byte order marks at
// the start of src. Some tools add a second one to a file that has one.
// http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding
func skipBOM(src string) string {
for {
switch {
case len(src) >= 2 && (src[0] == 0xFE && src[1] == 0xFF || src[0] == 0xFF && src[1] == 0xFE):
src = src[2:]
case len(src) >= 3 && src[0] == 0xEF && src[1] == 0xBB && src[2] == 0xBF:
src = src[3:]
default:
return src
}
}
}
// parse reads all of reader and adds its sections and keys to f. The caller
// holds the lock, or f isn't shared yet.
func (f *File) parse(reader io.Reader) error {
var b strings.Builder
if _, err := io.Copy(&b, reader); err != nil {
return err
}
l := &lexer{src: skipBOM(b.String()), opts: &f.options}
// Ignore error because default section name is never empty string.
name := f.options.DefaultSection
if f.options.Insensitive || f.options.InsensitiveSections {
name = strings.ToLower(name)
}
section, _ := f.addSection(name)
var lastRegularKey *Key
count := 1 // Counter for auto-increment key names ("-"), per section.
for {
tok, err := l.next()
if err != nil {
return err
}
switch tok.kind {
case tokEOF:
if tok.comment != "" {
// Comment lines after the last key are kept on the last
// section, which isn't the one read last when the input
// reopens an earlier section, and are written after it.
// Sections added later are written after them.
last := f.sections[len(f.sections)-1]
last.footer = strings.TrimSpace(last.footer + "\n" + tok.comment)
}
return nil
case tokSection:
if section, err = f.addSection(tok.name); err != nil {
return tok.errorf(err)
}
section.comment = tok.comment
// A section with keys, such as the default one, stays a key section
// when its raw header has no body.
section.isRawSection = section.isRawSection || (tok.raw && len(section.keys) == 0)
count = 1
case tokRawBody:
section.isRawSection = true
section.rawBody += tok.value
case tokNestedValue:
if err = lastRegularKey.addNestedValue(tok.value); err != nil {
return tok.errorf(err)
}
case tokBooleanKey:
key, err := section.addBooleanKey(tok.name)
if err != nil {
return tok.errorf(err)
}
key.comment = tok.comment
case tokKey:
name, isAutoIncr := tok.name, tok.name == "-"
if isAutoIncr {
name = "#" + strconv.Itoa(count)
count++
}
key, err := section.addKey(name, tok.value)
if err != nil {
return tok.errorf(err)
}
key.isAutoIncrement = isAutoIncr
key.comment = tok.comment
lastRegularKey = key
}
}
}
// readKeyName returns the key name at the start of line and the offset of
// the value after its delimiter.
func readKeyName(delimiters string, line string) (string, int, error) {
// Check if key name surrounded by quotes.
var keyQuote string
switch line[0] {
case '"':
if len(line) > 6 && line[0:3] == `"""` {
keyQuote = `"""`
} else {
keyQuote = `"`
}
case '`':
keyQuote = "`"
}
// Read the key name.
var endIdx int
if len(keyQuote) > 0 {
startIdx := len(keyQuote)
// The name ends at the first closing quote, so """"""name"""=value has
// an empty name and fails, as it did in v1.
pos := strings.Index(line[startIdx:], keyQuote)
if pos == -1 {
return "", -1, fmt.Errorf("missing closing key quote: %s", line)
}
pos += startIdx
// Find key-value delimiter
i := strings.IndexAny(line[pos+startIdx:], delimiters)
if i < 0 {
return "", -1, fmt.Errorf("%w: %s", ErrDelimiterNotFound, line)
}
endIdx = pos + i
return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil
}
endIdx = strings.IndexAny(line, delimiters)
if endIdx < 0 {
return "", -1, fmt.Errorf("%w: %s", ErrDelimiterNotFound, line)
}
if endIdx == 0 {
return "", -1, fmt.Errorf("%w: %s", ErrEmptyKeyName, line)
}
return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil
}
// hasSurroundedQuote reports whether in starts and ends with quote and has no
// other quote of the same kind.
func hasSurroundedQuote(in string, quote byte) bool {
return len(in) >= 2 && in[0] == quote && in[len(in)-1] == quote &&
strings.IndexByte(in[1:], quote) == len(in)-2
}