utils.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package parser
  2. import (
  3. "strconv"
  4. "strings"
  5. )
  6. // dumps the AST defined by `node` as a list of sexps. Returns a string
  7. // suitable for printing.
  8. func (node *Node) Dump() string {
  9. str := ""
  10. str += node.Value
  11. for _, n := range node.Children {
  12. str += "(" + n.Dump() + ")\n"
  13. }
  14. if node.Next != nil {
  15. for n := node.Next; n != nil; n = n.Next {
  16. if len(n.Children) > 0 {
  17. str += " " + n.Dump()
  18. } else {
  19. str += " " + strconv.Quote(n.Value)
  20. }
  21. }
  22. }
  23. return strings.TrimSpace(str)
  24. }
  25. // performs the dispatch based on the two primal strings, cmd and args. Please
  26. // look at the dispatch table in parser.go to see how these dispatchers work.
  27. func fullDispatch(cmd, args string) (*Node, map[string]bool, error) {
  28. fn := dispatch[cmd]
  29. // Ignore invalid Dockerfile instructions
  30. if fn == nil {
  31. fn = parseIgnore
  32. }
  33. sexp, attrs, err := fn(args)
  34. if err != nil {
  35. return nil, nil, err
  36. }
  37. return sexp, attrs, nil
  38. }
  39. // splitCommand takes a single line of text and parses out the cmd and args,
  40. // which are used for dispatching to more exact parsing functions.
  41. func splitCommand(line string) (string, string, error) {
  42. var args string
  43. // Make sure we get the same results irrespective of leading/trailing spaces
  44. cmdline := TOKEN_WHITESPACE.Split(strings.TrimSpace(line), 2)
  45. cmd := strings.ToLower(cmdline[0])
  46. if len(cmdline) == 2 {
  47. args = strings.TrimSpace(cmdline[1])
  48. }
  49. // the cmd should never have whitespace, but it's possible for the args to
  50. // have trailing whitespace.
  51. return cmd, args, nil
  52. }
  53. // covers comments and empty lines. Lines should be trimmed before passing to
  54. // this function.
  55. func stripComments(line string) string {
  56. // string is already trimmed at this point
  57. if TOKEN_COMMENT.MatchString(line) {
  58. return TOKEN_COMMENT.ReplaceAllString(line, "")
  59. }
  60. return line
  61. }