From 5d289f440502940d9fd8bed27b1c652fa5bca72d Mon Sep 17 00:00:00 2001 From: Alex Quick Date: Sun, 16 Jul 2017 18:31:51 -0400 Subject: [PATCH] escape some other bash-y special chars ($!) --- godotenv.go | 16 ++++++++++++---- godotenv_test.go | 4 ++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/godotenv.go b/godotenv.go index 26d2af9..de2ff39 100644 --- a/godotenv.go +++ b/godotenv.go @@ -24,6 +24,8 @@ import ( "strings" ) +const doubleQuoteSpecialChars = "\\\n\r\"!$`" + // Load will read your env file(s) and load them into ENV for this process. // // Call this function as close as possible to the start of your program (ideally in main) @@ -297,9 +299,15 @@ func isIgnoredLine(line string) bool { } func doubleQuoteEscape(line string) string { - line = strings.Replace(line, `\`, `\\`, -1) - line = strings.Replace(line, "\n", `\n`, -1) - line = strings.Replace(line, "\r", `\r`, -1) - line = strings.Replace(line, `"`, `\"`, -1) + for _, c := range doubleQuoteSpecialChars { + toReplace := "\\" + string(c) + if c == '\n' { + toReplace = `\n` + } + if c == '\r' { + toReplace = `\r` + } + line = strings.Replace(line, string(c), toReplace, -1) + } return line } diff --git a/godotenv_test.go b/godotenv_test.go index d554727..22e8f8b 100644 --- a/godotenv_test.go +++ b/godotenv_test.go @@ -346,8 +346,8 @@ func TestWrite(t *testing.T) { writeAndCompare(`key=va"lu"e`, `key="va\"lu\"e"`) //but single quotes are left alone writeAndCompare(`key=va'lu'e`, `key="va'lu'e"`) - // newlines and backslashes are escaped - writeAndCompare(`foo="ba\n\r\\r!"`, `foo="ba\n\r\\r!"`) + // newlines, backslashes, and some other special chars are escaped + writeAndCompare(`foo="$ba\n\r\\r!"`, `foo="\$ba\n\r\\r\!"`) } func TestRoundtrip(t *testing.T) {