-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
75 lines (60 loc) · 1.47 KB
/
parser.go
File metadata and controls
75 lines (60 loc) · 1.47 KB
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
package acorn
import (
"bufio"
"io"
"os"
"strings"
)
// Parser tells how to parse files for code generation instructions
type Parser struct {
Comment string
Command string
}
// NewParser returns a new Acorn Parser
func NewParser(comment, command string) *Parser {
return &Parser{Comment: comment, Command: command}
}
// Handler defines the callback interface
type Handler func([]string)
// Parse parses the reader, calling back with commands
func (p *Parser) Parse(reader io.Reader, callback Handler) error {
var currentCommand []string
endCommand := func() {
if currentCommand != nil {
callback(currentCommand)
}
currentCommand = nil
}
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if !strings.HasPrefix(line, p.Comment) {
endCommand()
continue
}
line = strings.TrimSpace(strings.TrimPrefix(line, p.Comment))
if currentCommand != nil {
if line == "" {
endCommand()
continue
}
currentCommand = append(currentCommand, line)
continue
}
if strings.HasPrefix(line, p.Command) {
line := strings.TrimSpace(strings.TrimPrefix(line, p.Command))
currentCommand = []string{line}
}
}
endCommand()
return scanner.Err()
}
// ParseFile opens a file for reading and parses it, calling back with commands
func (p *Parser) ParseFile(name string, callback Handler) error {
file, err := os.Open(name)
defer file.Close()
if err != nil {
return err
}
return p.Parse(file, callback)
}