summaryrefslogtreecommitdiff
path: root/cgitrc/parser.go
blob: 4af57e78348f6816802808354e0685e705916afb (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
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
package cgitrc

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

type parserState int

const (
	parserStateLineStart parserState = iota
	parserStateComment
	parserStateKey
	parserStateValue
)

// Parser parses a cgitrc file.
type Parser struct {
	Fields []*ParserField

	state parserState
	keys  []string
	key   bytes.Buffer
	value bytes.Buffer

	lineNo uint
}

// ParserField describes a single key-value pair.
type ParserField struct {
	Keys   []string
	Value  string
	LineNo uint
}

// Write pushes data to the parser.
func (p *Parser) Write(buf []byte) (n int, err error) {
	for _, b := range buf {
		switch p.state {
		case parserStateLineStart:
			err = p.parseLineStart(b)
		case parserStateComment:
			if b == '\n' {
				p.state = parserStateLineStart
			}
		case parserStateKey:
			err = p.parseKey(b)
		case parserStateValue:
			p.parseValue(b)
		}
		if err != nil {
			err = fmt.Errorf("line %d: %v", p.lineNo, err)
			return
		}
		n++
	}
	return
}

// Close finishes parsing.
func (p *Parser) Close() (err error) {
	if p.state != parserStateLineStart {
		err = errors.New("unexpected EOF")
	}
	return
}

func (p *Parser) parseLineStart(b byte) (err error) {
	p.lineNo++
	switch b {
	case '\n':
	case '#':
		p.state = parserStateComment
	default:
		p.state = parserStateKey
		err = p.parseKey(b)
	}
	return
}

func (p *Parser) parseKey(b byte) (err error) {
	switch b {
	case '\n':
		err = errors.New("unexpected linefeed")
	case '.', '=':
		p.keys = append(p.keys, p.key.String())
		p.key.Reset()
		if b == '=' {
			p.state = parserStateValue
		}
	default:
		p.key.WriteByte(b)
	}
	return
}

func (p *Parser) parseValue(b byte) {
	switch b {
	case '\n':
		p.Fields = append(p.Fields, &ParserField{
			Keys:   p.keys,
			Value:  p.value.String(),
			LineNo: p.lineNo,
		})
		p.keys = nil
		p.value.Reset()
		p.state = parserStateLineStart
	default:
		p.value.WriteByte(b)
	}
}

// Key returns the field keys joined by '.'.
func (f ParserField) Key() string {
	return strings.Join(f.Keys, ".")
}