shellwords.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package shellwords
  2. import (
  3. "errors"
  4. "os"
  5. "regexp"
  6. "strings"
  7. )
  8. var (
  9. ParseEnv bool = false
  10. ParseBacktick bool = false
  11. )
  12. var envRe = regexp.MustCompile(`\$({[a-zA-Z0-9_]+}|[a-zA-Z0-9_]+)`)
  13. func isSpace(r rune) bool {
  14. switch r {
  15. case ' ', '\t', '\r', '\n':
  16. return true
  17. }
  18. return false
  19. }
  20. func replaceEnv(s string) string {
  21. return envRe.ReplaceAllStringFunc(s, func(s string) string {
  22. s = s[1:]
  23. if s[0] == '{' {
  24. s = s[1 : len(s)-1]
  25. }
  26. return os.Getenv(s)
  27. })
  28. }
  29. type Parser struct {
  30. ParseEnv bool
  31. ParseBacktick bool
  32. }
  33. func NewParser() *Parser {
  34. return &Parser{ParseEnv, ParseBacktick}
  35. }
  36. func (p *Parser) Parse(line string) ([]string, error) {
  37. line = strings.TrimSpace(line)
  38. args := []string{}
  39. buf := ""
  40. var escaped, doubleQuoted, singleQuoted, backQuote bool
  41. backtick := ""
  42. for _, r := range line {
  43. if escaped {
  44. buf += string(r)
  45. escaped = false
  46. continue
  47. }
  48. if r == '\\' {
  49. if singleQuoted {
  50. buf += string(r)
  51. } else {
  52. escaped = true
  53. }
  54. continue
  55. }
  56. if isSpace(r) {
  57. if singleQuoted || doubleQuoted || backQuote {
  58. buf += string(r)
  59. backtick += string(r)
  60. } else if buf != "" {
  61. if p.ParseEnv {
  62. buf = replaceEnv(buf)
  63. }
  64. args = append(args, buf)
  65. buf = ""
  66. }
  67. continue
  68. }
  69. switch r {
  70. case '`':
  71. if !singleQuoted && !doubleQuoted {
  72. if p.ParseBacktick {
  73. if backQuote {
  74. out, err := shellRun(backtick)
  75. if err != nil {
  76. return nil, err
  77. }
  78. buf = out
  79. }
  80. backtick = ""
  81. backQuote = !backQuote
  82. continue
  83. }
  84. backtick = ""
  85. backQuote = !backQuote
  86. }
  87. case '"':
  88. if !singleQuoted {
  89. doubleQuoted = !doubleQuoted
  90. continue
  91. }
  92. case '\'':
  93. if !doubleQuoted {
  94. singleQuoted = !singleQuoted
  95. continue
  96. }
  97. }
  98. buf += string(r)
  99. if backQuote {
  100. backtick += string(r)
  101. }
  102. }
  103. if buf != "" {
  104. if p.ParseEnv {
  105. buf = replaceEnv(buf)
  106. }
  107. args = append(args, buf)
  108. }
  109. if escaped || singleQuoted || doubleQuoted || backQuote {
  110. return nil, errors.New("invalid command line string")
  111. }
  112. return args, nil
  113. }
  114. func Parse(line string) ([]string, error) {
  115. return NewParser().Parse(line)
  116. }