Skip to content
This repository was archived by the owner on Jan 12, 2022. It is now read-only.

Commit 88e7c8b

Browse files
committed
support for writing envs out in dotenv format
1 parent c9360df commit 88e7c8b

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

godotenv.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package godotenv
1616
import (
1717
"bufio"
1818
"errors"
19+
"fmt"
1920
"io"
2021
"os"
2122
"os/exec"
@@ -119,6 +120,11 @@ func Parse(r io.Reader) (envMap map[string]string, err error) {
119120
return
120121
}
121122

123+
//ParseString reads an env file from a string, returning a map of keys and values.
124+
func ParseString(str string) (envMap map[string]string, err error) {
125+
return Parse(strings.NewReader(str))
126+
}
127+
122128
// Exec loads env vars from the specified filenames (empty map falls back to default)
123129
// then executes the cmd specified.
124130
//
@@ -136,6 +142,31 @@ func Exec(filenames []string, cmd string, cmdArgs []string) error {
136142
return command.Run()
137143
}
138144

145+
// Write serializes the given environment and writes it to a file
146+
func Write(envMap map[string]string, filename string) error {
147+
content, error := WriteString(envMap)
148+
if error != nil {
149+
return error
150+
}
151+
file, error := os.Create(filename)
152+
if error != nil {
153+
return error
154+
}
155+
_, err := file.WriteString(content)
156+
return err
157+
}
158+
159+
// WriteString outputs the given environment as a dotenv-formatted environment file.
160+
//
161+
// Each line is in the format: KEY="VALUE" where VALUE is backslash-escaped.
162+
func WriteString(envMap map[string]string) (string, error) {
163+
lines := make([]string, 0, len(envMap))
164+
for k, v := range envMap {
165+
lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v)))
166+
}
167+
return strings.Join(lines, "\n"), nil
168+
}
169+
139170
func filenamesOrDefault(filenames []string) []string {
140171
if len(filenames) == 0 {
141172
return []string{".env"}
@@ -264,3 +295,11 @@ func isIgnoredLine(line string) bool {
264295
trimmedLine := strings.Trim(line, " \n\t")
265296
return len(trimmedLine) == 0 || strings.HasPrefix(trimmedLine, "#")
266297
}
298+
299+
func doubleQuoteEscape(line string) string {
300+
line = strings.Replace(line, `\`, `\\`, -1)
301+
line = strings.Replace(line, "\n", `\n`, -1)
302+
line = strings.Replace(line, "\r", `\r`, -1)
303+
line = strings.Replace(line, `"`, `\"`, -1)
304+
return line
305+
}

godotenv_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package godotenv
22

33
import (
44
"bytes"
5+
"fmt"
56
"os"
7+
"reflect"
68
"testing"
79
)
810

@@ -326,3 +328,47 @@ func TestErrorParsing(t *testing.T) {
326328
t.Errorf("Expected error, got %v", envMap)
327329
}
328330
}
331+
332+
func TestWrite(t *testing.T) {
333+
writeAndCompare := func(env string, expected string) {
334+
envMap, _ := ParseString(env)
335+
actual, _ := WriteString(envMap)
336+
if expected != actual {
337+
t.Errorf("Expected '%v' (%v) to write as '%v', got '%v' instead.", env, envMap, expected, actual)
338+
}
339+
}
340+
//just test some single lines to show the general idea
341+
//TestRoundtrip makes most of the good assertions
342+
343+
//values are always double-quoted
344+
writeAndCompare(`key=value`, `key="value"`)
345+
//double-quotes are escaped
346+
writeAndCompare(`key=va"lu"e`, `key="va\"lu\"e"`)
347+
//but single quotes are left alone
348+
writeAndCompare(`key=va'lu'e`, `key="va'lu'e"`)
349+
// newlines and backslashes are escaped
350+
writeAndCompare(`foo="ba\n\r\\r!"`, `foo="ba\n\r\\r!"`)
351+
}
352+
353+
func TestRoundtrip(t *testing.T) {
354+
fixtures := []string{"equals.env", "exported.env", "invalid1.env", "plain.env", "quoted.env"}
355+
for _, fixture := range fixtures {
356+
fixtureFilename := fmt.Sprintf("fixtures/%s", fixture)
357+
env, err := readFile(fixtureFilename)
358+
if err != nil {
359+
continue
360+
}
361+
rep, err := WriteString(env)
362+
if err != nil {
363+
continue
364+
}
365+
roundtripped, err := ParseString(rep)
366+
if err != nil {
367+
continue
368+
}
369+
if !reflect.DeepEqual(env, roundtripped) {
370+
t.Errorf("Expected '%s' to roundtrip as '%v', got '%v' instead", fixtureFilename, env, roundtripped)
371+
}
372+
373+
}
374+
}

0 commit comments

Comments
 (0)