aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/pelletier/go-toml/keysparsing.go
blob: b67664f6d480e3a297b1c062dae11735dff3301a (plain)
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
// Parsing keys handling both bare and quoted keys.

package toml

import (
	"bytes"
	"fmt"
	"unicode"
)

func parseKey(key string) ([]string, error) {
	groups := []string{}
	var buffer bytes.Buffer
	inQuotes := false
	wasInQuotes := false
	escapeNext := false
	ignoreSpace := true
	expectDot := false

	for _, char := range key {
		if ignoreSpace {
			if char == ' ' {
				continue
			}
			ignoreSpace = false
		}
		if escapeNext {
			buffer.WriteRune(char)
			escapeNext = false
			continue
		}
		switch char {
		case '\\':
			escapeNext = true
			continue
		case '"':
			if inQuotes {
				groups = append(groups, buffer.String())
				buffer.Reset()
				wasInQuotes = true
			}
			inQuotes = !inQuotes
			expectDot = false
		case '.':
			if inQuotes {
				buffer.WriteRune(char)
			} else {
				if !wasInQuotes {
					if buffer.Len() == 0 {
						return nil, fmt.Errorf("empty key group")
					}
					groups = append(groups, buffer.String())
					buffer.Reset()
				}
				ignoreSpace = true
				expectDot = false
				wasInQuotes = false
			}
		case ' ':
			if inQuotes {
				buffer.WriteRune(char)
			} else {
				expectDot = true
			}
		default:
			if !inQuotes && !isValidBareChar(char) {
				return nil, fmt.Errorf("invalid bare character: %c", char)
			}
			if !inQuotes && expectDot {
				return nil, fmt.Errorf("what?")
			}
			buffer.WriteRune(char)
			expectDot = false
		}
	}
	if inQuotes {
		return nil, fmt.Errorf("mismatched quotes")
	}
	if escapeNext {
		return nil, fmt.Errorf("unfinished escape sequence")
	}
	if buffer.Len() > 0 {
		groups = append(groups, buffer.String())
	}
	if len(groups) == 0 {
		return nil, fmt.Errorf("empty key")
	}
	return groups, nil
}

func isValidBareChar(r rune) bool {
	return isAlphanumeric(r) || r == '-' || unicode.IsNumber(r)
}