handle escaping more comprehensively

pull/34/head
Alex Quick 2017-05-06 00:50:30 -04:00
parent 325433c502
commit b9324c6f3c
2 changed files with 25 additions and 7 deletions

View File

@ -18,6 +18,7 @@ import (
"errors" "errors"
"os" "os"
"os/exec" "os/exec"
"regexp"
"strings" "strings"
) )
@ -218,7 +219,11 @@ func parseLine(line string) (key string, value string, err error) {
key = strings.Trim(key, " ") key = strings.Trim(key, " ")
// Parse the value // Parse the value
value = splitString[1] value = parseValue(splitString[1])
return
}
func parseValue(value string) string {
// trim // trim
value = strings.Trim(value, " ") value = strings.Trim(value, " ")
@ -230,15 +235,23 @@ func parseLine(line string) (key string, value string, err error) {
if first == last && strings.ContainsAny(first, `"'`) { if first == last && strings.ContainsAny(first, `"'`) {
// pull the quotes off the edges // pull the quotes off the edges
value = strings.Trim(value, `"'`) value = strings.Trim(value, `"'`)
// handle escapes
// expand quotes escapeRegex := regexp.MustCompile(`\\.`)
value = strings.Replace(value, `\"`, `"`, -1) value = escapeRegex.ReplaceAllStringFunc(value, func(match string) string {
// expand newlines c := strings.TrimPrefix(match, `\`)
value = strings.Replace(value, `\n`, "\n", -1) switch c {
case "n":
return "\n"
case "r":
return "\r"
default:
return c
}
})
} }
} }
return return value
} }
func isIgnoredLine(line string) bool { func isIgnoredLine(line string) bool {

View File

@ -238,6 +238,11 @@ func TestParsing(t *testing.T) {
parseAndCompare(t, `FOO="ba#r"`, "FOO", "ba#r") parseAndCompare(t, `FOO="ba#r"`, "FOO", "ba#r")
parseAndCompare(t, "FOO='ba#r'", "FOO", "ba#r") parseAndCompare(t, "FOO='ba#r'", "FOO", "ba#r")
//newlines and backslashes should be escaped
parseAndCompare(t, `FOO="bar\n\ b\az"`, "FOO", "bar\n baz")
parseAndCompare(t, `FOO="bar\\\n\ b\az"`, "FOO", "bar\\\n baz")
parseAndCompare(t, `FOO="bar\\r\ b\az"`, "FOO", "bar\\r baz")
// it 'throws an error if line format is incorrect' do // it 'throws an error if line format is incorrect' do
// expect{env('lol$wut')}.to raise_error(Dotenv::FormatError) // expect{env('lol$wut')}.to raise_error(Dotenv::FormatError)
badlyFormattedLine := "lol$wut" badlyFormattedLine := "lol$wut"