Debian Codegraph @

dockerfile/parser/line_parsers.go

raw
1 package parser
2
3 // line parsers are dispatch calls that parse a single unit of text into a
4 // Node object which contains the whole statement. Dockerfiles have varied
5 // (but not usually unique, see ONBUILD for a unique example) parsing rules
6 // per-command, and these unify the processing in a way that makes it
7 // manageable.
8
9 import (
10 "encoding/json"
11 "errors"
12 "fmt"
13 "sort"
14 "strings"
15 "unicode"
16 "unicode/utf8"
17
18 "github.com/openshift/imagebuilder/dockerfile/command"
19 )
20
21 var (
22 errDockerfileNotStringArray = errors.New("when using JSON array syntax, arrays must be comprised of strings only")
23 )
24
25 const (
26 commandLabel = "LABEL"
27 )
28
29 // ignore the current argument. This will still leave a command parsed, but
30 // will not incorporate the arguments into the ast.
31 func parseIgnore(rest string, d *Directive) (*Node, map[string]bool, error) {
32 return &Node{}, nil, nil
33 }
34
35 // used for onbuild. Could potentially be used for anything that represents a
36 // statement with sub-statements.
37 //
38 // ONBUILD RUN foo bar -> (onbuild (run foo bar))
39 func parseSubCommand(rest string, d *Directive) (*Node, map[string]bool, error) {
40 if rest == "" {
41 return nil, nil, nil
42 }
43
44 child, err := newNodeFromLine(rest, d)
45 if err != nil {
46 return nil, nil, err
47 }
48
49 return &Node{Children: []*Node{child}}, nil, nil
50 }
51
52 // helper to parse words (i.e space delimited or quoted strings) in a statement.
53 // The quotes are preserved as part of this function and they are stripped later
54 // as part of processWords().
55 func parseWords(rest string, d *Directive) []string {
56 const (
57 inSpaces = iota // looking for start of a word
58 inWord
59 inQuote
60 )
61
62 words := []string{}
63 phase := inSpaces
64 word := ""
65 quote := '\000'
66 blankOK := false
67 var ch rune
68 var chWidth int
69
70 for pos := 0; pos <= len(rest); pos += chWidth {
71 if pos != len(rest) {
72 ch, chWidth = utf8.DecodeRuneInString(rest[pos:])
73 }
74
75 if phase == inSpaces { // Looking for start of word
76 if pos == len(rest) { // end of input
77 break
78 }
79 if unicode.IsSpace(ch) { // skip spaces
80 continue
81 }
82 phase = inWord // found it, fall through
83 }
84 if (phase == inWord || phase == inQuote) && (pos == len(rest)) {
85 if blankOK || len(word) > 0 {
86 words = append(words, word)
87 }
88 break
89 }
90 if phase == inWord {
91 if unicode.IsSpace(ch) {
92 phase = inSpaces
93 if blankOK || len(word) > 0 {
94 words = append(words, word)
95 }
96 word = ""
97 blankOK = false
98 continue
99 }
100 if ch == '\'' || ch == '"' {
101 quote = ch
102 blankOK = true
103 phase = inQuote
104 }
105 if ch == d.escapeToken {
106 if pos+chWidth == len(rest) {
107 continue // just skip an escape token at end of line
108 }
109 // If we're not quoted and we see an escape token, then always just
110 // add the escape token plus the char to the word, even if the char
111 // is a quote.
112 word += string(ch)
113 pos += chWidth
114 ch, chWidth = utf8.DecodeRuneInString(rest[pos:])
115 }
116 word += string(ch)
117 continue
118 }
119 if phase == inQuote {
120 if ch == quote {
121 phase = inWord
122 }
123 // The escape token is special except for ' quotes - can't escape anything for '
124 if ch == d.escapeToken && quote != '\'' {
125 if pos+chWidth == len(rest) {
126 phase = inWord
127 continue // just skip the escape token at end
128 }
129 pos += chWidth
130 word += string(ch)
131 ch, chWidth = utf8.DecodeRuneInString(rest[pos:])
132 }
133 word += string(ch)
134 }
135 }
136
137 return words
138 }
139
140 // parse environment like statements. Note that this does *not* handle
141 // variable interpolation, which will be handled in the evaluator.
142 func parseNameVal(rest string, key string, d *Directive) (*Node, error) {
143 // This is kind of tricky because we need to support the old
144 // variant: KEY name value
145 // as well as the new one: KEY name=value ...
146 // The trigger to know which one is being used will be whether we hit
147 // a space or = first. space ==> old, "=" ==> new
148
149 words := parseWords(rest, d)
150 if len(words) == 0 {
151 return nil, nil
152 }
153
154 // Old format (KEY name value)
155 if !strings.Contains(words[0], "=") {
156 parts := tokenWhitespace.Split(rest, 2)
157 if len(parts) < 2 {
158 return nil, fmt.Errorf("%s must have two arguments", key)
159 }
160 return newKeyValueNode(parts[0], parts[1]), nil
161 }
162
163 var rootNode *Node
164 var prevNode *Node
165 for _, word := range words {
166 if !strings.Contains(word, "=") {
167 return nil, fmt.Errorf("Syntax error - can't find = in %q. Must be of the form: name=value", word)
168 }
169
170 parts := strings.SplitN(word, "=", 2)
171 node := newKeyValueNode(parts[0], parts[1])
172 rootNode, prevNode = appendKeyValueNode(node, rootNode, prevNode)
173 }
174
175 return rootNode, nil
176 }
177
178 func newKeyValueNode(key, value string) *Node {
179 return &Node{
180 Value: key,
181 Next: &Node{Value: value},
182 }
183 }
184
185 func appendKeyValueNode(node, rootNode, prevNode *Node) (*Node, *Node) {
186 if rootNode == nil {
187 rootNode = node
188 }
189 if prevNode != nil {
190 prevNode.Next = node
191 }
192
193 prevNode = node.Next
194 return rootNode, prevNode
195 }
196
197 func parseEnv(rest string, d *Directive) (*Node, map[string]bool, error) {
198 node, err := parseNameVal(rest, "ENV", d)
199 return node, nil, err
200 }
201
202 func parseLabel(rest string, d *Directive) (*Node, map[string]bool, error) {
203 node, err := parseNameVal(rest, commandLabel, d)
204 return node, nil, err
205 }
206
207 // NodeFromLabels returns a Node for the injected labels
208 func NodeFromLabels(labels map[string]string) *Node {
209 keys := []string{}
210 for key := range labels {
211 keys = append(keys, key)
212 }
213 // Sort the label to have a repeatable order
214 sort.Strings(keys)
215
216 labelPairs := []string{}
217 var rootNode *Node
218 var prevNode *Node
219 for _, key := range keys {
220 value := labels[key]
221 labelPairs = append(labelPairs, fmt.Sprintf("%q='%s'", key, value))
222 // Value must be single quoted to prevent env variable expansion
223 // See https://github.com/docker/docker/issues/26027
224 node := newKeyValueNode(key, "'"+value+"'")
225 rootNode, prevNode = appendKeyValueNode(node, rootNode, prevNode)
226 }
227
228 return &Node{
229 Value: command.Label,
230 Original: commandLabel + " " + strings.Join(labelPairs, " "),
231 Next: rootNode,
232 }
233 }
234
235 // parses a statement containing one or more keyword definition(s) and/or
236 // value assignments, like `name1 name2= name3="" name4=value`.
237 // Note that this is a stricter format than the old format of assignment,
238 // allowed by parseNameVal(), in a way that this only allows assignment of the
239 // form `keyword=[<value>]` like `name2=`, `name3=""`, and `name4=value` above.
240 // In addition, a keyword definition alone is of the form `keyword` like `name1`
241 // above. And the assignments `name2=` and `name3=""` are equivalent and
242 // assign an empty value to the respective keywords.
243 func parseNameOrNameVal(rest string, d *Directive) (*Node, map[string]bool, error) {
244 words := parseWords(rest, d)
245 if len(words) == 0 {
246 return nil, nil, nil
247 }
248
249 var (
250 rootnode *Node
251 prevNode *Node
252 )
253 for i, word := range words {
254 node := &Node{}
255 node.Value = word
256 if i == 0 {
257 rootnode = node
258 } else {
259 prevNode.Next = node
260 }
261 prevNode = node
262 }
263
264 return rootnode, nil, nil
265 }
266
267 // parses a whitespace-delimited set of arguments. The result is effectively a
268 // linked list of string arguments.
269 func parseStringsWhitespaceDelimited(rest string, d *Directive) (*Node, map[string]bool, error) {
270 if rest == "" {
271 return nil, nil, nil
272 }
273
274 node := &Node{}
275 rootnode := node
276 prevnode := node
277 for _, str := range tokenWhitespace.Split(rest, -1) { // use regexp
278 prevnode = node
279 node.Value = str
280 node.Next = &Node{}
281 node = node.Next
282 }
283
284 // XXX to get around regexp.Split *always* providing an empty string at the
285 // end due to how our loop is constructed, nil out the last node in the
286 // chain.
287 prevnode.Next = nil
288
289 return rootnode, nil, nil
290 }
291
292 // parseString just wraps the string in quotes and returns a working node.
293 func parseString(rest string, d *Directive) (*Node, map[string]bool, error) {
294 if rest == "" {
295 return nil, nil, nil
296 }
297 n := &Node{}
298 n.Value = rest
299 return n, nil, nil
300 }
301
302 // parseJSON converts JSON arrays to an AST.
303 func parseJSON(rest string, d *Directive) (*Node, map[string]bool, error) {
304 rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
305 if !strings.HasPrefix(rest, "[") {
306 return nil, nil, fmt.Errorf(`Error parsing "%s" as a JSON array`, rest)
307 }
308
309 var myJSON []interface{}
310 if err := json.NewDecoder(strings.NewReader(rest)).Decode(&myJSON); err != nil {
311 return nil, nil, err
312 }
313
314 var top, prev *Node
315 for _, str := range myJSON {
316 s, ok := str.(string)
317 if !ok {
318 return nil, nil, errDockerfileNotStringArray
319 }
320
321 node := &Node{Value: s}
322 if prev == nil {
323 top = node
324 } else {
325 prev.Next = node
326 }
327 prev = node
328 }
329
330 return top, map[string]bool{"json": true}, nil
331 }
332
333 // parseMaybeJSON determines if the argument appears to be a JSON array. If
334 // so, passes to parseJSON; if not, quotes the result and returns a single
335 // node.
336 func parseMaybeJSON(rest string, d *Directive) (*Node, map[string]bool, error) {
337 if rest == "" {
338 return nil, nil, nil
339 }
340
341 node, attrs, err := parseJSON(rest, d)
342
343 if err == nil {
344 return node, attrs, nil
345 }
346 if err == errDockerfileNotStringArray {
347 return nil, nil, err
348 }
349
350 node = &Node{}
351 node.Value = rest
352 return node, nil, nil
353 }
354
355 // parseMaybeJSONToList determines if the argument appears to be a JSON array. If
356 // so, passes to parseJSON; if not, attempts to parse it as a whitespace
357 // delimited string.
358 func parseMaybeJSONToList(rest string, d *Directive) (*Node, map[string]bool, error) {
359 node, attrs, err := parseJSON(rest, d)
360
361 if err == nil {
362 return node, attrs, nil
363 }
364 if err == errDockerfileNotStringArray {
365 return nil, nil, err
366 }
367
368 return parseStringsWhitespaceDelimited(rest, d)
369 }
370
371 // The HEALTHCHECK command is like parseMaybeJSON, but has an extra type argument.
372 func parseHealthConfig(rest string, d *Directive) (*Node, map[string]bool, error) {
373 // Find end of first argument
374 var sep int
375 for ; sep < len(rest); sep++ {
376 if unicode.IsSpace(rune(rest[sep])) {
377 break
378 }
379 }
380 next := sep
381 for ; next < len(rest); next++ {
382 if !unicode.IsSpace(rune(rest[next])) {
383 break
384 }
385 }
386
387 if sep == 0 {
388 return nil, nil, nil
389 }
390
391 typ := rest[:sep]
392 cmd, attrs, err := parseMaybeJSON(rest[next:], d)
393 if err != nil {
394 return nil, nil, err
395 }
396
397 return &Node{Value: typ, Next: cmd}, attrs, err
398 }