aboutsummaryrefslogtreecommitdiff
path: root/config/section.go
blob: fd06eee4efbc30edce9a4e70f2bf6281e2f02655 (about) (plain) (blame)
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
package config

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"strings"
)

func (p *configParser) parseSection() error {
	var name bytes.Buffer

	for {
		ch, err := p.nextChar()
		if errors.Is(err, io.EOF) {
			return p.parseError("unexpected EOF in section header")
		}

		if err != nil {
			return err
		}

		if ch == ']' {
			section := name.String()
			if !isValidSection(section) {
				return p.parseError(fmt.Sprintf("invalid section name: %q", section))
			}

			p.currentSection = strings.ToLower(section)
			p.currentSubsec = ""

			return nil
		}

		if isWhitespace(ch) {
			return p.parseExtendedSection(&name)
		}

		if !isKeyChar(ch) && ch != '.' {
			return p.parseError(fmt.Sprintf("invalid character in section name: %q", ch))
		}

		name.WriteByte(toLower(ch))
	}
}

func isValidSection(s string) bool {
	if len(s) == 0 {
		return false
	}

	for i := range len(s) {
		ch := s[i]
		if !isLetter(ch) && !isDigit(ch) && ch != '-' && ch != '.' {
			return false
		}
	}

	return true
}