/
parser.go
160 lines (125 loc) · 4.35 KB
/
parser.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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/*
Copyright 2023 The Nuclio Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package inlineparser
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/nuclio/errors"
"github.com/nuclio/logger"
"gopkg.in/yaml.v3"
)
const StartBlockKeyword = "@nuclio."
// Block represents a block
type Block struct {
Contents map[string]interface{}
RawContents string
Error error
}
// ConfigParser parsers inline configuration in files
type ConfigParser interface {
Parse(path string) (map[string]Block, error)
}
// InlineParser parses comment in code
type InlineParser struct {
logger logger.Logger
currentStateLineHandler func(line string) error
currentBlockName string
currentBlockContents string
currentCommentChar string
startBlockPattern string
currentBlocks map[string]Block
}
func NewParser(parentLogger logger.Logger, commentChar string) *InlineParser {
return &InlineParser{
logger: parentLogger.GetChild("inlineparser"),
currentCommentChar: commentChar,
}
}
// Parse looks for a block starting with a comment character and "@nuclio.". It then adds this
// to the list of inline configuration blocks. For example:
//
// @nuclio.configure
//
// function.yaml:
// apiVersion: "nuclio.io/v1"
// kind: "NuclioFunction"
// spec:
// runtime: "golang"
// triggers:
// http:
// numWorkers: 8
// kind: http
func (p *InlineParser) Parse(path string) (map[string]Block, error) {
reader, err := os.OpenFile(path, os.O_RDONLY, os.FileMode(0644))
if err != nil {
return nil, errors.Wrap(err, "Failed to open function file")
}
scanner := bufio.NewScanner(reader)
// prepare stuff for states
p.currentBlocks = map[string]Block{}
p.startBlockPattern = fmt.Sprintf("%s%s", p.currentCommentChar, StartBlockKeyword)
// init state to looking for start block
p.currentStateLineHandler = p.lookingForStartBlockStateHandleLine
p.logger.DebugWith("Starting to look for block pattern", "pattern", p.startBlockPattern)
// read a line
for scanner.Scan() {
// handle the current line in the state machine
if err := p.currentStateLineHandler(scanner.Text()); err != nil {
return nil, errors.Wrap(err, "Failed to handle line")
}
}
return p.currentBlocks, nil
}
func (p *InlineParser) lookingForStartBlockStateHandleLine(line string) error {
spacelessLine := strings.ReplaceAll(line, " ", "")
// if the string starts with <commandChar><space>@nuclio. - we found a match
if strings.HasPrefix(spacelessLine, p.startBlockPattern) {
// set current block name: `// @nuclio.createFiles` -> `createFiles`
p.currentBlockName = strings.Trim(spacelessLine[len(p.startBlockPattern):], " ")
p.logger.DebugWith("Found block start", "block name", p.currentBlockName)
// switch state
p.currentStateLineHandler = p.readingBlockStateHandleLine
}
return nil
}
func (p *InlineParser) readingBlockStateHandleLine(line string) error {
// if the line doesn't start with a comment character, close the block
if !strings.HasPrefix(line, p.currentCommentChar) {
block := Block{
RawContents: p.currentBlockContents,
}
p.logger.DebugWith("Found block end", "contentsLen", len(p.currentBlockContents))
// parse yaml
if err := yaml.Unmarshal([]byte(p.currentBlockContents), &block.Contents); err != nil {
block.Error = errors.Wrapf(err, "Failed to unmarshal inline block: %s", p.currentBlockName)
}
// add block to current blocks
p.currentBlocks[p.currentBlockName] = block
// clear current block
p.currentBlockContents = ""
// go back to looking for blocks
p.currentStateLineHandler = p.lookingForStartBlockStateHandleLine
// and we're done
return nil
}
// skip the comment
line = line[len(p.currentCommentChar):]
// if there's more contents, skip the first space (since space must follow character)
if line != "" {
line = line[1:]
}
p.currentBlockContents += line + "\n"
return nil
}