parser.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. "runtime"
  10. "strconv"
  11. "strings"
  12. "unicode"
  13. "github.com/docker/docker/builder/dockerfile/command"
  14. "github.com/docker/docker/pkg/system"
  15. "github.com/pkg/errors"
  16. )
  17. // Node is a structure used to represent a parse tree.
  18. //
  19. // In the node there are three fields, Value, Next, and Children. Value is the
  20. // current token's string value. Next is always the next non-child token, and
  21. // children contains all the children. Here's an example:
  22. //
  23. // (value next (child child-next child-next-next) next-next)
  24. //
  25. // This data structure is frankly pretty lousy for handling complex languages,
  26. // but lucky for us the Dockerfile isn't very complicated. This structure
  27. // works a little more effectively than a "proper" parse tree for our needs.
  28. //
  29. type Node struct {
  30. Value string // actual content
  31. Next *Node // the next item in the current sexp
  32. Children []*Node // the children of this sexp
  33. Attributes map[string]bool // special attributes for this node
  34. Original string // original line used before parsing
  35. Flags []string // only top Node should have this set
  36. StartLine int // the line in the original dockerfile where the node begins
  37. endLine int // the line in the original dockerfile where the node ends
  38. }
  39. // Dump dumps the AST defined by `node` as a list of sexps.
  40. // Returns a string suitable for printing.
  41. func (node *Node) Dump() string {
  42. str := ""
  43. str += node.Value
  44. if len(node.Flags) > 0 {
  45. str += fmt.Sprintf(" %q", node.Flags)
  46. }
  47. for _, n := range node.Children {
  48. str += "(" + n.Dump() + ")\n"
  49. }
  50. for n := node.Next; n != nil; n = n.Next {
  51. if len(n.Children) > 0 {
  52. str += " " + n.Dump()
  53. } else {
  54. str += " " + strconv.Quote(n.Value)
  55. }
  56. }
  57. return strings.TrimSpace(str)
  58. }
  59. func (node *Node) lines(start, end int) {
  60. node.StartLine = start
  61. node.endLine = end
  62. }
  63. // AddChild adds a new child node, and updates line information
  64. func (node *Node) AddChild(child *Node, startLine, endLine int) {
  65. child.lines(startLine, endLine)
  66. if node.StartLine < 0 {
  67. node.StartLine = startLine
  68. }
  69. node.endLine = endLine
  70. node.Children = append(node.Children, child)
  71. }
  72. var (
  73. dispatch map[string]func(string, *Directive) (*Node, map[string]bool, error)
  74. tokenWhitespace = regexp.MustCompile(`[\t\v\f\r ]+`)
  75. tokenEscapeCommand = regexp.MustCompile(`^#[ \t]*escape[ \t]*=[ \t]*(?P<escapechar>.).*$`)
  76. tokenPlatformCommand = regexp.MustCompile(`^#[ \t]*platform[ \t]*=[ \t]*(?P<platform>.*)$`)
  77. tokenComment = regexp.MustCompile(`^#.*$`)
  78. )
  79. // DefaultEscapeToken is the default escape token
  80. const DefaultEscapeToken = '\\'
  81. // defaultPlatformToken is the platform assumed for the build if not explicitly provided
  82. var defaultPlatformToken = runtime.GOOS
  83. // Directive is the structure used during a build run to hold the state of
  84. // parsing directives.
  85. type Directive struct {
  86. escapeToken rune // Current escape token
  87. platformToken string // Current platform token
  88. lineContinuationRegex *regexp.Regexp // Current line continuation regex
  89. processingComplete bool // Whether we are done looking for directives
  90. escapeSeen bool // Whether the escape directive has been seen
  91. platformSeen bool // Whether the platform directive has been seen
  92. }
  93. // setEscapeToken sets the default token for escaping characters in a Dockerfile.
  94. func (d *Directive) setEscapeToken(s string) error {
  95. if s != "`" && s != "\\" {
  96. return fmt.Errorf("invalid ESCAPE '%s'. Must be ` or \\", s)
  97. }
  98. d.escapeToken = rune(s[0])
  99. d.lineContinuationRegex = regexp.MustCompile(`\` + s + `[ \t]*$`)
  100. return nil
  101. }
  102. // setPlatformToken sets the default platform for pulling images in a Dockerfile.
  103. func (d *Directive) setPlatformToken(s string) error {
  104. s = strings.ToLower(s)
  105. valid := []string{runtime.GOOS}
  106. if system.LCOWSupported() {
  107. valid = append(valid, "linux")
  108. }
  109. for _, item := range valid {
  110. if s == item {
  111. d.platformToken = s
  112. return nil
  113. }
  114. }
  115. return fmt.Errorf("invalid PLATFORM '%s'. Must be one of %v", s, valid)
  116. }
  117. // possibleParserDirective looks for one or more parser directives '# escapeToken=<char>' and
  118. // '# platform=<string>'. Parser directives must precede any builder instruction
  119. // or other comments, and cannot be repeated.
  120. func (d *Directive) possibleParserDirective(line string) error {
  121. if d.processingComplete {
  122. return nil
  123. }
  124. tecMatch := tokenEscapeCommand.FindStringSubmatch(strings.ToLower(line))
  125. if len(tecMatch) != 0 {
  126. for i, n := range tokenEscapeCommand.SubexpNames() {
  127. if n == "escapechar" {
  128. if d.escapeSeen {
  129. return errors.New("only one escape parser directive can be used")
  130. }
  131. d.escapeSeen = true
  132. return d.setEscapeToken(tecMatch[i])
  133. }
  134. }
  135. }
  136. // TODO @jhowardmsft LCOW Support: Eventually this check can be removed,
  137. // but only recognise a platform token if running in LCOW mode.
  138. if system.LCOWSupported() {
  139. tpcMatch := tokenPlatformCommand.FindStringSubmatch(strings.ToLower(line))
  140. if len(tpcMatch) != 0 {
  141. for i, n := range tokenPlatformCommand.SubexpNames() {
  142. if n == "platform" {
  143. if d.platformSeen {
  144. return errors.New("only one platform parser directive can be used")
  145. }
  146. d.platformSeen = true
  147. return d.setPlatformToken(tpcMatch[i])
  148. }
  149. }
  150. }
  151. }
  152. d.processingComplete = true
  153. return nil
  154. }
  155. // NewDefaultDirective returns a new Directive with the default escapeToken token
  156. func NewDefaultDirective() *Directive {
  157. directive := Directive{}
  158. directive.setEscapeToken(string(DefaultEscapeToken))
  159. directive.setPlatformToken(defaultPlatformToken)
  160. return &directive
  161. }
  162. func init() {
  163. // Dispatch Table. see line_parsers.go for the parse functions.
  164. // The command is parsed and mapped to the line parser. The line parser
  165. // receives the arguments but not the command, and returns an AST after
  166. // reformulating the arguments according to the rules in the parser
  167. // functions. Errors are propagated up by Parse() and the resulting AST can
  168. // be incorporated directly into the existing AST as a next.
  169. dispatch = map[string]func(string, *Directive) (*Node, map[string]bool, error){
  170. command.Add: parseMaybeJSONToList,
  171. command.Arg: parseNameOrNameVal,
  172. command.Cmd: parseMaybeJSON,
  173. command.Copy: parseMaybeJSONToList,
  174. command.Entrypoint: parseMaybeJSON,
  175. command.Env: parseEnv,
  176. command.Expose: parseStringsWhitespaceDelimited,
  177. command.From: parseStringsWhitespaceDelimited,
  178. command.Healthcheck: parseHealthConfig,
  179. command.Label: parseLabel,
  180. command.Maintainer: parseString,
  181. command.Onbuild: parseSubCommand,
  182. command.Run: parseMaybeJSON,
  183. command.Shell: parseMaybeJSON,
  184. command.StopSignal: parseString,
  185. command.User: parseString,
  186. command.Volume: parseMaybeJSONToList,
  187. command.Workdir: parseString,
  188. }
  189. }
  190. // newNodeFromLine splits the line into parts, and dispatches to a function
  191. // based on the command and command arguments. A Node is created from the
  192. // result of the dispatch.
  193. func newNodeFromLine(line string, directive *Directive) (*Node, error) {
  194. cmd, flags, args, err := splitCommand(line)
  195. if err != nil {
  196. return nil, err
  197. }
  198. fn := dispatch[cmd]
  199. // Ignore invalid Dockerfile instructions
  200. if fn == nil {
  201. fn = parseIgnore
  202. }
  203. next, attrs, err := fn(args, directive)
  204. if err != nil {
  205. return nil, err
  206. }
  207. return &Node{
  208. Value: cmd,
  209. Original: line,
  210. Flags: flags,
  211. Next: next,
  212. Attributes: attrs,
  213. }, nil
  214. }
  215. // Result is the result of parsing a Dockerfile
  216. type Result struct {
  217. AST *Node
  218. EscapeToken rune
  219. Platform string
  220. Warnings []string
  221. }
  222. // PrintWarnings to the writer
  223. func (r *Result) PrintWarnings(out io.Writer) {
  224. if len(r.Warnings) == 0 {
  225. return
  226. }
  227. fmt.Fprintf(out, strings.Join(r.Warnings, "\n")+"\n")
  228. }
  229. // Parse reads lines from a Reader, parses the lines into an AST and returns
  230. // the AST and escape token
  231. func Parse(rwc io.Reader) (*Result, error) {
  232. d := NewDefaultDirective()
  233. currentLine := 0
  234. root := &Node{StartLine: -1}
  235. scanner := bufio.NewScanner(rwc)
  236. warnings := []string{}
  237. var err error
  238. for scanner.Scan() {
  239. bytesRead := scanner.Bytes()
  240. if currentLine == 0 {
  241. // First line, strip the byte-order-marker if present
  242. bytesRead = bytes.TrimPrefix(bytesRead, utf8bom)
  243. }
  244. bytesRead, err = processLine(d, bytesRead, true)
  245. if err != nil {
  246. return nil, err
  247. }
  248. currentLine++
  249. startLine := currentLine
  250. line, isEndOfLine := trimContinuationCharacter(string(bytesRead), d)
  251. if isEndOfLine && line == "" {
  252. continue
  253. }
  254. var hasEmptyContinuationLine bool
  255. for !isEndOfLine && scanner.Scan() {
  256. bytesRead, err := processLine(d, scanner.Bytes(), false)
  257. if err != nil {
  258. return nil, err
  259. }
  260. currentLine++
  261. if isComment(scanner.Bytes()) {
  262. // original line was a comment (processLine strips comments)
  263. continue
  264. }
  265. if isEmptyContinuationLine(bytesRead) {
  266. hasEmptyContinuationLine = true
  267. continue
  268. }
  269. continuationLine := string(bytesRead)
  270. continuationLine, isEndOfLine = trimContinuationCharacter(continuationLine, d)
  271. line += continuationLine
  272. }
  273. if hasEmptyContinuationLine {
  274. warning := "[WARNING]: Empty continuation line found in:\n " + line
  275. warnings = append(warnings, warning)
  276. }
  277. child, err := newNodeFromLine(line, d)
  278. if err != nil {
  279. return nil, err
  280. }
  281. root.AddChild(child, startLine, currentLine)
  282. }
  283. if len(warnings) > 0 {
  284. warnings = append(warnings, "[WARNING]: Empty continuation lines will become errors in a future release.")
  285. }
  286. return &Result{
  287. AST: root,
  288. Warnings: warnings,
  289. EscapeToken: d.escapeToken,
  290. Platform: d.platformToken,
  291. }, nil
  292. }
  293. func trimComments(src []byte) []byte {
  294. return tokenComment.ReplaceAll(src, []byte{})
  295. }
  296. func trimWhitespace(src []byte) []byte {
  297. return bytes.TrimLeftFunc(src, unicode.IsSpace)
  298. }
  299. func isComment(line []byte) bool {
  300. return tokenComment.Match(trimWhitespace(line))
  301. }
  302. func isEmptyContinuationLine(line []byte) bool {
  303. return len(trimWhitespace(line)) == 0
  304. }
  305. var utf8bom = []byte{0xEF, 0xBB, 0xBF}
  306. func trimContinuationCharacter(line string, d *Directive) (string, bool) {
  307. if d.lineContinuationRegex.MatchString(line) {
  308. line = d.lineContinuationRegex.ReplaceAllString(line, "")
  309. return line, false
  310. }
  311. return line, true
  312. }
  313. // TODO: remove stripLeftWhitespace after deprecation period. It seems silly
  314. // to preserve whitespace on continuation lines. Why is that done?
  315. func processLine(d *Directive, token []byte, stripLeftWhitespace bool) ([]byte, error) {
  316. if stripLeftWhitespace {
  317. token = trimWhitespace(token)
  318. }
  319. return trimComments(token), d.possibleParserDirective(string(token))
  320. }