parser.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // Package parser implements a parser and parse tree dumper for Dockerfiles.
  2. package parser
  3. import (
  4. "bufio"
  5. "bytes"
  6. "fmt"
  7. "io"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "unicode"
  12. "github.com/docker/docker/builder/dockerfile/command"
  13. )
  14. // Node is a structure used to represent a parse tree.
  15. //
  16. // In the node there are three fields, Value, Next, and Children. Value is the
  17. // current token's string value. Next is always the next non-child token, and
  18. // children contains all the children. Here's an example:
  19. //
  20. // (value next (child child-next child-next-next) next-next)
  21. //
  22. // This data structure is frankly pretty lousy for handling complex languages,
  23. // but lucky for us the Dockerfile isn't very complicated. This structure
  24. // works a little more effectively than a "proper" parse tree for our needs.
  25. //
  26. type Node struct {
  27. Value string // actual content
  28. Next *Node // the next item in the current sexp
  29. Children []*Node // the children of this sexp
  30. Attributes map[string]bool // special attributes for this node
  31. Original string // original line used before parsing
  32. Flags []string // only top Node should have this set
  33. StartLine int // the line in the original dockerfile where the node begins
  34. EndLine int // the line in the original dockerfile where the node ends
  35. }
  36. // Dump dumps the AST defined by `node` as a list of sexps.
  37. // Returns a string suitable for printing.
  38. func (node *Node) Dump() string {
  39. str := ""
  40. str += node.Value
  41. if len(node.Flags) > 0 {
  42. str += fmt.Sprintf(" %q", node.Flags)
  43. }
  44. for _, n := range node.Children {
  45. str += "(" + n.Dump() + ")\n"
  46. }
  47. for n := node.Next; n != nil; n = n.Next {
  48. if len(n.Children) > 0 {
  49. str += " " + n.Dump()
  50. } else {
  51. str += " " + strconv.Quote(n.Value)
  52. }
  53. }
  54. return strings.TrimSpace(str)
  55. }
  56. // Directive is the structure used during a build run to hold the state of
  57. // parsing directives.
  58. type Directive struct {
  59. EscapeToken rune // Current escape token
  60. LineContinuationRegex *regexp.Regexp // Current line continuation regex
  61. LookingForDirectives bool // Whether we are currently looking for directives
  62. EscapeSeen bool // Whether the escape directive has been seen
  63. }
  64. var (
  65. dispatch map[string]func(string, *Directive) (*Node, map[string]bool, error)
  66. tokenWhitespace = regexp.MustCompile(`[\t\v\f\r ]+`)
  67. tokenEscapeCommand = regexp.MustCompile(`^#[ \t]*escape[ \t]*=[ \t]*(?P<escapechar>.).*$`)
  68. tokenComment = regexp.MustCompile(`^#.*$`)
  69. )
  70. // DefaultEscapeToken is the default escape token
  71. const DefaultEscapeToken = "\\"
  72. // SetEscapeToken sets the default token for escaping characters in a Dockerfile.
  73. func SetEscapeToken(s string, d *Directive) error {
  74. if s != "`" && s != "\\" {
  75. return fmt.Errorf("invalid ESCAPE '%s'. Must be ` or \\", s)
  76. }
  77. d.EscapeToken = rune(s[0])
  78. d.LineContinuationRegex = regexp.MustCompile(`\` + s + `[ \t]*$`)
  79. return nil
  80. }
  81. func init() {
  82. // Dispatch Table. see line_parsers.go for the parse functions.
  83. // The command is parsed and mapped to the line parser. The line parser
  84. // receives the arguments but not the command, and returns an AST after
  85. // reformulating the arguments according to the rules in the parser
  86. // functions. Errors are propagated up by Parse() and the resulting AST can
  87. // be incorporated directly into the existing AST as a next.
  88. dispatch = map[string]func(string, *Directive) (*Node, map[string]bool, error){
  89. command.Add: parseMaybeJSONToList,
  90. command.Arg: parseNameOrNameVal,
  91. command.Cmd: parseMaybeJSON,
  92. command.Copy: parseMaybeJSONToList,
  93. command.Entrypoint: parseMaybeJSON,
  94. command.Env: parseEnv,
  95. command.Expose: parseStringsWhitespaceDelimited,
  96. command.From: parseString,
  97. command.Healthcheck: parseHealthConfig,
  98. command.Label: parseLabel,
  99. command.Maintainer: parseString,
  100. command.Onbuild: parseSubCommand,
  101. command.Run: parseMaybeJSON,
  102. command.Shell: parseMaybeJSON,
  103. command.StopSignal: parseString,
  104. command.User: parseString,
  105. command.Volume: parseMaybeJSONToList,
  106. command.Workdir: parseString,
  107. }
  108. }
  109. // ParseLine parses a line and returns the remainder.
  110. func ParseLine(line string, d *Directive, ignoreCont bool) (string, *Node, error) {
  111. if escapeFound, err := handleParserDirective(line, d); err != nil || escapeFound {
  112. d.EscapeSeen = escapeFound
  113. return "", nil, err
  114. }
  115. d.LookingForDirectives = false
  116. if line = stripComments(line); line == "" {
  117. return "", nil, nil
  118. }
  119. if !ignoreCont && d.LineContinuationRegex.MatchString(line) {
  120. line = d.LineContinuationRegex.ReplaceAllString(line, "")
  121. return line, nil, nil
  122. }
  123. node, err := newNodeFromLine(line, d)
  124. return "", node, err
  125. }
  126. // newNodeFromLine splits the line into parts, and dispatches to a function
  127. // based on the command and command arguments. A Node is created from the
  128. // result of the dispatch.
  129. func newNodeFromLine(line string, directive *Directive) (*Node, error) {
  130. cmd, flags, args, err := splitCommand(line)
  131. if err != nil {
  132. return nil, err
  133. }
  134. fn := dispatch[cmd]
  135. // Ignore invalid Dockerfile instructions
  136. if fn == nil {
  137. fn = parseIgnore
  138. }
  139. next, attrs, err := fn(args, directive)
  140. if err != nil {
  141. return nil, err
  142. }
  143. return &Node{
  144. Value: cmd,
  145. Original: line,
  146. Flags: flags,
  147. Next: next,
  148. Attributes: attrs,
  149. }, nil
  150. }
  151. // Handle the parser directive '# escape=<char>. Parser directives must precede
  152. // any builder instruction or other comments, and cannot be repeated.
  153. func handleParserDirective(line string, d *Directive) (bool, error) {
  154. if !d.LookingForDirectives {
  155. return false, nil
  156. }
  157. tecMatch := tokenEscapeCommand.FindStringSubmatch(strings.ToLower(line))
  158. if len(tecMatch) == 0 {
  159. return false, nil
  160. }
  161. if d.EscapeSeen == true {
  162. return false, fmt.Errorf("only one escape parser directive can be used")
  163. }
  164. for i, n := range tokenEscapeCommand.SubexpNames() {
  165. if n == "escapechar" {
  166. if err := SetEscapeToken(tecMatch[i], d); err != nil {
  167. return false, err
  168. }
  169. return true, nil
  170. }
  171. }
  172. return false, nil
  173. }
  174. // Parse is the main parse routine.
  175. // It handles an io.ReadWriteCloser and returns the root of the AST.
  176. func Parse(rwc io.Reader, d *Directive) (*Node, error) {
  177. currentLine := 0
  178. root := &Node{}
  179. root.StartLine = -1
  180. scanner := bufio.NewScanner(rwc)
  181. utf8bom := []byte{0xEF, 0xBB, 0xBF}
  182. for scanner.Scan() {
  183. scannedBytes := scanner.Bytes()
  184. // We trim UTF8 BOM
  185. if currentLine == 0 {
  186. scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom)
  187. }
  188. scannedLine := strings.TrimLeftFunc(string(scannedBytes), unicode.IsSpace)
  189. currentLine++
  190. line, child, err := ParseLine(scannedLine, d, false)
  191. if err != nil {
  192. return nil, err
  193. }
  194. startLine := currentLine
  195. if line != "" && child == nil {
  196. for scanner.Scan() {
  197. newline := scanner.Text()
  198. currentLine++
  199. if stripComments(strings.TrimSpace(newline)) == "" {
  200. continue
  201. }
  202. line, child, err = ParseLine(line+newline, d, false)
  203. if err != nil {
  204. return nil, err
  205. }
  206. if child != nil {
  207. break
  208. }
  209. }
  210. if child == nil && line != "" {
  211. // When we call ParseLine we'll pass in 'true' for
  212. // the ignoreCont param if we're at the EOF. This will
  213. // prevent the func from returning immediately w/o
  214. // parsing the line thinking that there's more input
  215. // to come.
  216. _, child, err = ParseLine(line, d, scanner.Err() == nil)
  217. if err != nil {
  218. return nil, err
  219. }
  220. }
  221. }
  222. if child != nil {
  223. // Update the line information for the current child.
  224. child.StartLine = startLine
  225. child.EndLine = currentLine
  226. // Update the line information for the root. The starting line of the root is always the
  227. // starting line of the first child and the ending line is the ending line of the last child.
  228. if root.StartLine < 0 {
  229. root.StartLine = currentLine
  230. }
  231. root.EndLine = currentLine
  232. root.Children = append(root.Children, child)
  233. }
  234. }
  235. return root, nil
  236. }
  237. // covers comments and empty lines. Lines should be trimmed before passing to
  238. // this function.
  239. func stripComments(line string) string {
  240. // string is already trimmed at this point
  241. if tokenComment.MatchString(line) {
  242. return tokenComment.ReplaceAllString(line, "")
  243. }
  244. return line
  245. }