-
Notifications
You must be signed in to change notification settings - Fork 10
/
scanner.go
73 lines (55 loc) · 1.31 KB
/
scanner.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
package goyesql
import (
"bufio"
"errors"
"io"
)
var (
// ErrTagMissing occurs when a query has no tag
ErrTagMissing = errors.New("Query without tag")
// ErrTagOverwritten occurs when a tag is overwritten by a new one
ErrTagOverwritten = errors.New("Tag overwritten")
)
// Tag is a string prefixing a Query
type Tag string
// Queries is a map associating a Tag to its Query
type Queries map[Tag]string
// ParseReader takes an io.Reader and returns Queries or an error.
func ParseReader(reader io.Reader) (Queries, error) {
var (
lastTag Tag
lastLine parsedLine
)
queries := make(Queries)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := parseLine(scanner.Text())
switch line.Type {
case lineBlank, lineComment:
// we don't care about blank and comment lines
continue
case lineQuery:
// got a query but no tag before
if lastTag == "" {
return nil, ErrTagMissing
}
query := line.Value
// if query is multiline
if queries[lastTag] != "" {
query = " " + query
}
queries[lastTag] += query
case lineTag:
// got a tag after another tag
if lastLine.Type == lineTag {
return nil, ErrTagOverwritten
}
lastTag = Tag(line.Value)
}
lastLine = line
}
if err := scanner.Err(); err != nil {
return nil, err
}
return queries, nil
}