-
Notifications
You must be signed in to change notification settings - Fork 0
/
scanner.go
71 lines (58 loc) · 1.26 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
// Credits to https://github.com/gchaincl/dotsql
package queries
import (
"bufio"
"path/filepath"
"regexp"
"strings"
)
type Scanner struct {
line string
queries map[string]string
current string
}
type stateFn func(*Scanner) stateFn
func getTag(line string) string {
re := regexp.MustCompile("^\\s*--\\s*name:\\s*(\\S+)")
matches := re.FindStringSubmatch(line)
if matches == nil {
return ""
}
return matches[1]
}
func initialState(s *Scanner) stateFn {
if tag := getTag(s.line); len(tag) > 0 {
s.current = tag
return queryState
}
return initialState
}
func queryState(s *Scanner) stateFn {
if tag := getTag(s.line); len(tag) > 0 {
s.current = tag
} else {
s.appendQueryLine()
}
return queryState
}
func (s *Scanner) appendQueryLine() {
current := s.queries[s.current]
line := strings.Trim(s.line, " \t")
if len(line) == 0 {
return
}
if len(current) > 0 {
current = current + "\n"
}
current = current + line
s.queries[s.current] = current
}
func (s *Scanner) Run(fileName string, io *bufio.Scanner) map[string]string {
s.queries = make(map[string]string)
s.current = filepath.Base(strings.TrimSuffix(fileName, filepath.Ext(fileName)))
for state := queryState; io.Scan(); {
s.line = io.Text()
state = state(s)
}
return s.queries
}