parser.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package godotenv
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "regexp"
  7. "strings"
  8. "unicode"
  9. )
  10. const (
  11. charComment = '#'
  12. prefixSingleQuote = '\''
  13. prefixDoubleQuote = '"'
  14. exportPrefix = "export"
  15. )
  16. func parseBytes(src []byte, out map[string]string) error {
  17. src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1)
  18. cutset := src
  19. for {
  20. cutset = getStatementStart(cutset)
  21. if cutset == nil {
  22. // reached end of file
  23. break
  24. }
  25. key, left, err := locateKeyName(cutset)
  26. if err != nil {
  27. return err
  28. }
  29. value, left, err := extractVarValue(left, out)
  30. if err != nil {
  31. return err
  32. }
  33. out[key] = value
  34. cutset = left
  35. }
  36. return nil
  37. }
  38. // getStatementPosition returns position of statement begin.
  39. //
  40. // It skips any comment line or non-whitespace character.
  41. func getStatementStart(src []byte) []byte {
  42. pos := indexOfNonSpaceChar(src)
  43. if pos == -1 {
  44. return nil
  45. }
  46. src = src[pos:]
  47. if src[0] != charComment {
  48. return src
  49. }
  50. // skip comment section
  51. pos = bytes.IndexFunc(src, isCharFunc('\n'))
  52. if pos == -1 {
  53. return nil
  54. }
  55. return getStatementStart(src[pos:])
  56. }
  57. // locateKeyName locates and parses key name and returns rest of slice
  58. func locateKeyName(src []byte) (key string, cutset []byte, err error) {
  59. // trim "export" and space at beginning
  60. src = bytes.TrimLeftFunc(src, isSpace)
  61. if bytes.HasPrefix(src, []byte(exportPrefix)) {
  62. trimmed := bytes.TrimPrefix(src, []byte(exportPrefix))
  63. if bytes.IndexFunc(trimmed, isSpace) == 0 {
  64. src = bytes.TrimLeftFunc(trimmed, isSpace)
  65. }
  66. }
  67. // locate key name end and validate it in single loop
  68. offset := 0
  69. loop:
  70. for i, char := range src {
  71. rchar := rune(char)
  72. if isSpace(rchar) {
  73. continue
  74. }
  75. switch char {
  76. case '=', ':':
  77. // library also supports yaml-style value declaration
  78. key = string(src[0:i])
  79. offset = i + 1
  80. break loop
  81. case '_':
  82. default:
  83. // variable name should match [A-Za-z0-9_.]
  84. if unicode.IsLetter(rchar) || unicode.IsNumber(rchar) || rchar == '.' {
  85. continue
  86. }
  87. return "", nil, fmt.Errorf(
  88. `unexpected character %q in variable name near %q`,
  89. string(char), string(src))
  90. }
  91. }
  92. if len(src) == 0 {
  93. return "", nil, errors.New("zero length string")
  94. }
  95. // trim whitespace
  96. key = strings.TrimRightFunc(key, unicode.IsSpace)
  97. cutset = bytes.TrimLeftFunc(src[offset:], isSpace)
  98. return key, cutset, nil
  99. }
  100. // extractVarValue extracts variable value and returns rest of slice
  101. func extractVarValue(src []byte, vars map[string]string) (value string, rest []byte, err error) {
  102. quote, hasPrefix := hasQuotePrefix(src)
  103. if !hasPrefix {
  104. // unquoted value - read until end of line
  105. endOfLine := bytes.IndexFunc(src, isLineEnd)
  106. // Hit EOF without a trailing newline
  107. if endOfLine == -1 {
  108. endOfLine = len(src)
  109. if endOfLine == 0 {
  110. return "", nil, nil
  111. }
  112. }
  113. // Convert line to rune away to do accurate countback of runes
  114. line := []rune(string(src[0:endOfLine]))
  115. // Assume end of line is end of var
  116. endOfVar := len(line)
  117. if endOfVar == 0 {
  118. return "", src[endOfLine:], nil
  119. }
  120. // Work backwards to check if the line ends in whitespace then
  121. // a comment (ie asdasd # some comment)
  122. for i := endOfVar - 1; i >= 0; i-- {
  123. if line[i] == charComment && i > 0 {
  124. if isSpace(line[i-1]) {
  125. endOfVar = i
  126. break
  127. }
  128. }
  129. }
  130. trimmed := strings.TrimFunc(string(line[0:endOfVar]), isSpace)
  131. return expandVariables(trimmed, vars), src[endOfLine:], nil
  132. }
  133. // lookup quoted string terminator
  134. for i := 1; i < len(src); i++ {
  135. if char := src[i]; char != quote {
  136. continue
  137. }
  138. // skip escaped quote symbol (\" or \', depends on quote)
  139. if prevChar := src[i-1]; prevChar == '\\' {
  140. continue
  141. }
  142. // trim quotes
  143. trimFunc := isCharFunc(rune(quote))
  144. value = string(bytes.TrimLeftFunc(bytes.TrimRightFunc(src[0:i], trimFunc), trimFunc))
  145. if quote == prefixDoubleQuote {
  146. // unescape newlines for double quote (this is compat feature)
  147. // and expand environment variables
  148. value = expandVariables(expandEscapes(value), vars)
  149. }
  150. return value, src[i+1:], nil
  151. }
  152. // return formatted error if quoted string is not terminated
  153. valEndIndex := bytes.IndexFunc(src, isCharFunc('\n'))
  154. if valEndIndex == -1 {
  155. valEndIndex = len(src)
  156. }
  157. return "", nil, fmt.Errorf("unterminated quoted value %s", src[:valEndIndex])
  158. }
  159. func expandEscapes(str string) string {
  160. out := escapeRegex.ReplaceAllStringFunc(str, func(match string) string {
  161. c := strings.TrimPrefix(match, `\`)
  162. switch c {
  163. case "n":
  164. return "\n"
  165. case "r":
  166. return "\r"
  167. default:
  168. return match
  169. }
  170. })
  171. return unescapeCharsRegex.ReplaceAllString(out, "$1")
  172. }
  173. func indexOfNonSpaceChar(src []byte) int {
  174. return bytes.IndexFunc(src, func(r rune) bool {
  175. return !unicode.IsSpace(r)
  176. })
  177. }
  178. // hasQuotePrefix reports whether charset starts with single or double quote and returns quote character
  179. func hasQuotePrefix(src []byte) (prefix byte, isQuored bool) {
  180. if len(src) == 0 {
  181. return 0, false
  182. }
  183. switch prefix := src[0]; prefix {
  184. case prefixDoubleQuote, prefixSingleQuote:
  185. return prefix, true
  186. default:
  187. return 0, false
  188. }
  189. }
  190. func isCharFunc(char rune) func(rune) bool {
  191. return func(v rune) bool {
  192. return v == char
  193. }
  194. }
  195. // isSpace reports whether the rune is a space character but not line break character
  196. //
  197. // this differs from unicode.IsSpace, which also applies line break as space
  198. func isSpace(r rune) bool {
  199. switch r {
  200. case '\t', '\v', '\f', '\r', ' ', 0x85, 0xA0:
  201. return true
  202. }
  203. return false
  204. }
  205. func isLineEnd(r rune) bool {
  206. if r == '\n' || r == '\r' {
  207. return true
  208. }
  209. return false
  210. }
  211. var (
  212. escapeRegex = regexp.MustCompile(`\\.`)
  213. expandVarRegex = regexp.MustCompile(`(\\)?(\$)(\()?\{?([A-Z0-9_]+)?\}?`)
  214. unescapeCharsRegex = regexp.MustCompile(`\\([^$])`)
  215. )
  216. func expandVariables(v string, m map[string]string) string {
  217. return expandVarRegex.ReplaceAllStringFunc(v, func(s string) string {
  218. submatch := expandVarRegex.FindStringSubmatch(s)
  219. if submatch == nil {
  220. return s
  221. }
  222. if submatch[1] == "\\" || submatch[2] == "(" {
  223. return submatch[0][1:]
  224. } else if submatch[4] != "" {
  225. return m[submatch[4]]
  226. }
  227. return s
  228. })
  229. }