parser.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. var (
  57. dispatch map[string]func(string, *Directive) (*Node, map[string]bool, error)
  58. tokenWhitespace = regexp.MustCompile(`[\t\v\f\r ]+`)
  59. tokenEscapeCommand = regexp.MustCompile(`^#[ \t]*escape[ \t]*=[ \t]*(?P<escapechar>.).*$`)
  60. tokenComment = regexp.MustCompile(`^#.*$`)
  61. )
  62. // DefaultEscapeToken is the default escape token
  63. const DefaultEscapeToken = "\\"
  64. // Directive is the structure used during a build run to hold the state of
  65. // parsing directives.
  66. type Directive struct {
  67. escapeToken rune // Current escape token
  68. lineContinuationRegex *regexp.Regexp // Current line continuation regex
  69. lookingForDirectives bool // Whether we are currently looking for directives
  70. escapeSeen bool // Whether the escape directive has been seen
  71. }
  72. // SetEscapeToken sets the default token for escaping characters in a Dockerfile.
  73. func (d *Directive) SetEscapeToken(s string) 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. // EscapeToken returns the escape token
  82. func (d *Directive) EscapeToken() rune {
  83. return d.escapeToken
  84. }
  85. // NewDefaultDirective returns a new Directive with the default escapeToken token
  86. func NewDefaultDirective() *Directive {
  87. directive := Directive{
  88. escapeSeen: false,
  89. lookingForDirectives: true,
  90. }
  91. directive.SetEscapeToken(DefaultEscapeToken)
  92. return &directive
  93. }
  94. func init() {
  95. // Dispatch Table. see line_parsers.go for the parse functions.
  96. // The command is parsed and mapped to the line parser. The line parser
  97. // receives the arguments but not the command, and returns an AST after
  98. // reformulating the arguments according to the rules in the parser
  99. // functions. Errors are propagated up by Parse() and the resulting AST can
  100. // be incorporated directly into the existing AST as a next.
  101. dispatch = map[string]func(string, *Directive) (*Node, map[string]bool, error){
  102. command.Add: parseMaybeJSONToList,
  103. command.Arg: parseNameOrNameVal,
  104. command.Cmd: parseMaybeJSON,
  105. command.Copy: parseMaybeJSONToList,
  106. command.Entrypoint: parseMaybeJSON,
  107. command.Env: parseEnv,
  108. command.Expose: parseStringsWhitespaceDelimited,
  109. command.From: parseStringsWhitespaceDelimited,
  110. command.Healthcheck: parseHealthConfig,
  111. command.Label: parseLabel,
  112. command.Maintainer: parseString,
  113. command.Onbuild: parseSubCommand,
  114. command.Run: parseMaybeJSON,
  115. command.Shell: parseMaybeJSON,
  116. command.StopSignal: parseString,
  117. command.User: parseString,
  118. command.Volume: parseMaybeJSONToList,
  119. command.Workdir: parseString,
  120. }
  121. }
  122. // ParseLine parses a line and returns the remainder.
  123. func ParseLine(line string, d *Directive, ignoreCont bool) (string, *Node, error) {
  124. if escapeFound, err := handleParserDirective(line, d); err != nil || escapeFound {
  125. d.escapeSeen = escapeFound
  126. return "", nil, err
  127. }
  128. d.lookingForDirectives = false
  129. if line = stripComments(line); line == "" {
  130. return "", nil, nil
  131. }
  132. if !ignoreCont && d.lineContinuationRegex.MatchString(line) {
  133. line = d.lineContinuationRegex.ReplaceAllString(line, "")
  134. return line, nil, nil
  135. }
  136. node, err := newNodeFromLine(line, d)
  137. return "", node, err
  138. }
  139. // newNodeFromLine splits the line into parts, and dispatches to a function
  140. // based on the command and command arguments. A Node is created from the
  141. // result of the dispatch.
  142. func newNodeFromLine(line string, directive *Directive) (*Node, error) {
  143. cmd, flags, args, err := splitCommand(line)
  144. if err != nil {
  145. return nil, err
  146. }
  147. fn := dispatch[cmd]
  148. // Ignore invalid Dockerfile instructions
  149. if fn == nil {
  150. fn = parseIgnore
  151. }
  152. next, attrs, err := fn(args, directive)
  153. if err != nil {
  154. return nil, err
  155. }
  156. return &Node{
  157. Value: cmd,
  158. Original: line,
  159. Flags: flags,
  160. Next: next,
  161. Attributes: attrs,
  162. }, nil
  163. }
  164. // Handle the parser directive '# escapeToken=<char>. Parser directives must precede
  165. // any builder instruction or other comments, and cannot be repeated.
  166. func handleParserDirective(line string, d *Directive) (bool, error) {
  167. if !d.lookingForDirectives {
  168. return false, nil
  169. }
  170. tecMatch := tokenEscapeCommand.FindStringSubmatch(strings.ToLower(line))
  171. if len(tecMatch) == 0 {
  172. return false, nil
  173. }
  174. if d.escapeSeen == true {
  175. return false, fmt.Errorf("only one escape parser directive can be used")
  176. }
  177. for i, n := range tokenEscapeCommand.SubexpNames() {
  178. if n == "escapechar" {
  179. if err := d.SetEscapeToken(tecMatch[i]); err != nil {
  180. return false, err
  181. }
  182. return true, nil
  183. }
  184. }
  185. return false, nil
  186. }
  187. // Parse is the main parse routine.
  188. // It handles an io.ReadWriteCloser and returns the root of the AST.
  189. func Parse(rwc io.Reader, d *Directive) (*Node, error) {
  190. currentLine := 0
  191. root := &Node{}
  192. root.StartLine = -1
  193. scanner := bufio.NewScanner(rwc)
  194. utf8bom := []byte{0xEF, 0xBB, 0xBF}
  195. for scanner.Scan() {
  196. scannedBytes := scanner.Bytes()
  197. // We trim UTF8 BOM
  198. if currentLine == 0 {
  199. scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom)
  200. }
  201. scannedLine := strings.TrimLeftFunc(string(scannedBytes), unicode.IsSpace)
  202. currentLine++
  203. line, child, err := ParseLine(scannedLine, d, false)
  204. if err != nil {
  205. return nil, err
  206. }
  207. startLine := currentLine
  208. if line != "" && child == nil {
  209. for scanner.Scan() {
  210. newline := scanner.Text()
  211. currentLine++
  212. if stripComments(strings.TrimSpace(newline)) == "" {
  213. continue
  214. }
  215. line, child, err = ParseLine(line+newline, d, false)
  216. if err != nil {
  217. return nil, err
  218. }
  219. if child != nil {
  220. break
  221. }
  222. }
  223. if child == nil && line != "" {
  224. // When we call ParseLine we'll pass in 'true' for
  225. // the ignoreCont param if we're at the EOF. This will
  226. // prevent the func from returning immediately w/o
  227. // parsing the line thinking that there's more input
  228. // to come.
  229. _, child, err = ParseLine(line, d, scanner.Err() == nil)
  230. if err != nil {
  231. return nil, err
  232. }
  233. }
  234. }
  235. if child != nil {
  236. // Update the line information for the current child.
  237. child.StartLine = startLine
  238. child.EndLine = currentLine
  239. // Update the line information for the root. The starting line of the root is always the
  240. // starting line of the first child and the ending line is the ending line of the last child.
  241. if root.StartLine < 0 {
  242. root.StartLine = currentLine
  243. }
  244. root.EndLine = currentLine
  245. root.Children = append(root.Children, child)
  246. }
  247. }
  248. return root, nil
  249. }
  250. // covers comments and empty lines. Lines should be trimmed before passing to
  251. // this function.
  252. func stripComments(line string) string {
  253. // string is already trimmed at this point
  254. if tokenComment.MatchString(line) {
  255. return tokenComment.ReplaceAllString(line, "")
  256. }
  257. return line
  258. }