godotenv.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // Package godotenv is a go port of the ruby dotenv library (https://github.com/bkeepers/dotenv)
  2. //
  3. // Examples/readme can be found on the GitHub page at https://github.com/joho/godotenv
  4. //
  5. // The TL;DR is that you make a .env file that looks something like
  6. //
  7. // SOME_ENV_VAR=somevalue
  8. //
  9. // and then in your go code you can call
  10. //
  11. // godotenv.Load()
  12. //
  13. // and all the env vars declared in .env will be available through os.Getenv("SOME_ENV_VAR")
  14. package godotenv
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "os"
  20. "os/exec"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. )
  25. const doubleQuoteSpecialChars = "\\\n\r\"!$`"
  26. // Parse reads an env file from io.Reader, returning a map of keys and values.
  27. func Parse(r io.Reader) (map[string]string, error) {
  28. var buf bytes.Buffer
  29. _, err := io.Copy(&buf, r)
  30. if err != nil {
  31. return nil, err
  32. }
  33. return UnmarshalBytes(buf.Bytes())
  34. }
  35. // Load will read your env file(s) and load them into ENV for this process.
  36. //
  37. // Call this function as close as possible to the start of your program (ideally in main).
  38. //
  39. // If you call Load without any args it will default to loading .env in the current path.
  40. //
  41. // You can otherwise tell it which files to load (there can be more than one) like:
  42. //
  43. // godotenv.Load("fileone", "filetwo")
  44. //
  45. // It's important to note that it WILL NOT OVERRIDE an env variable that already exists - consider the .env file to set dev vars or sensible defaults.
  46. func Load(filenames ...string) (err error) {
  47. filenames = filenamesOrDefault(filenames)
  48. for _, filename := range filenames {
  49. err = loadFile(filename, false)
  50. if err != nil {
  51. return // return early on a spazout
  52. }
  53. }
  54. return
  55. }
  56. // Overload will read your env file(s) and load them into ENV for this process.
  57. //
  58. // Call this function as close as possible to the start of your program (ideally in main).
  59. //
  60. // If you call Overload without any args it will default to loading .env in the current path.
  61. //
  62. // You can otherwise tell it which files to load (there can be more than one) like:
  63. //
  64. // godotenv.Overload("fileone", "filetwo")
  65. //
  66. // It's important to note this WILL OVERRIDE an env variable that already exists - consider the .env file to forcefully set all vars.
  67. func Overload(filenames ...string) (err error) {
  68. filenames = filenamesOrDefault(filenames)
  69. for _, filename := range filenames {
  70. err = loadFile(filename, true)
  71. if err != nil {
  72. return // return early on a spazout
  73. }
  74. }
  75. return
  76. }
  77. // Read all env (with same file loading semantics as Load) but return values as
  78. // a map rather than automatically writing values into env
  79. func Read(filenames ...string) (envMap map[string]string, err error) {
  80. filenames = filenamesOrDefault(filenames)
  81. envMap = make(map[string]string)
  82. for _, filename := range filenames {
  83. individualEnvMap, individualErr := readFile(filename)
  84. if individualErr != nil {
  85. err = individualErr
  86. return // return early on a spazout
  87. }
  88. for key, value := range individualEnvMap {
  89. envMap[key] = value
  90. }
  91. }
  92. return
  93. }
  94. // Unmarshal reads an env file from a string, returning a map of keys and values.
  95. func Unmarshal(str string) (envMap map[string]string, err error) {
  96. return UnmarshalBytes([]byte(str))
  97. }
  98. // UnmarshalBytes parses env file from byte slice of chars, returning a map of keys and values.
  99. func UnmarshalBytes(src []byte) (map[string]string, error) {
  100. out := make(map[string]string)
  101. err := parseBytes(src, out)
  102. return out, err
  103. }
  104. // Exec loads env vars from the specified filenames (empty map falls back to default)
  105. // then executes the cmd specified.
  106. //
  107. // Simply hooks up os.Stdin/err/out to the command and calls Run().
  108. //
  109. // If you want more fine grained control over your command it's recommended
  110. // that you use `Load()`, `Overload()` or `Read()` and the `os/exec` package yourself.
  111. func Exec(filenames []string, cmd string, cmdArgs []string, overload bool) error {
  112. op := Load
  113. if overload {
  114. op = Overload
  115. }
  116. if err := op(filenames...); err != nil {
  117. return err
  118. }
  119. command := exec.Command(cmd, cmdArgs...)
  120. command.Stdin = os.Stdin
  121. command.Stdout = os.Stdout
  122. command.Stderr = os.Stderr
  123. return command.Run()
  124. }
  125. // Write serializes the given environment and writes it to a file.
  126. func Write(envMap map[string]string, filename string) error {
  127. content, err := Marshal(envMap)
  128. if err != nil {
  129. return err
  130. }
  131. file, err := os.Create(filename)
  132. if err != nil {
  133. return err
  134. }
  135. defer file.Close()
  136. _, err = file.WriteString(content + "\n")
  137. if err != nil {
  138. return err
  139. }
  140. return file.Sync()
  141. }
  142. // Marshal outputs the given environment as a dotenv-formatted environment file.
  143. // Each line is in the format: KEY="VALUE" where VALUE is backslash-escaped.
  144. func Marshal(envMap map[string]string) (string, error) {
  145. lines := make([]string, 0, len(envMap))
  146. for k, v := range envMap {
  147. if d, err := strconv.Atoi(v); err == nil {
  148. lines = append(lines, fmt.Sprintf(`%s=%d`, k, d))
  149. } else {
  150. lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v)))
  151. }
  152. }
  153. sort.Strings(lines)
  154. return strings.Join(lines, "\n"), nil
  155. }
  156. func filenamesOrDefault(filenames []string) []string {
  157. if len(filenames) == 0 {
  158. return []string{".env"}
  159. }
  160. return filenames
  161. }
  162. func loadFile(filename string, overload bool) error {
  163. envMap, err := readFile(filename)
  164. if err != nil {
  165. return err
  166. }
  167. currentEnv := map[string]bool{}
  168. rawEnv := os.Environ()
  169. for _, rawEnvLine := range rawEnv {
  170. key := strings.Split(rawEnvLine, "=")[0]
  171. currentEnv[key] = true
  172. }
  173. for key, value := range envMap {
  174. if !currentEnv[key] || overload {
  175. _ = os.Setenv(key, value)
  176. }
  177. }
  178. return nil
  179. }
  180. func readFile(filename string) (envMap map[string]string, err error) {
  181. file, err := os.Open(filename)
  182. if err != nil {
  183. return
  184. }
  185. defer file.Close()
  186. return Parse(file)
  187. }
  188. func doubleQuoteEscape(line string) string {
  189. for _, c := range doubleQuoteSpecialChars {
  190. toReplace := "\\" + string(c)
  191. if c == '\n' {
  192. toReplace = `\n`
  193. }
  194. if c == '\r' {
  195. toReplace = `\r`
  196. }
  197. line = strings.Replace(line, string(c), toReplace, -1)
  198. }
  199. return line
  200. }