Skip to content

Commit

Permalink
Ignore variable names starting with numbers
Browse files Browse the repository at this point in the history
Signed-off-by: Ulysses Souza <ulyssessouza@gmail.com>
  • Loading branch information
ulyssessouza committed Jul 12, 2022
1 parent 045c678 commit 55f898e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
1 change: 1 addition & 0 deletions dotenv/fixtures/plain.env
Expand Up @@ -3,6 +3,7 @@ OPTION_B=2
OPTION_C= 3
OPTION_D =4
OPTION_E = 5
456 = ABC
OPTION_F =
OPTION_G=
OPTION_H = my string # Inline comment
27 changes: 14 additions & 13 deletions dotenv/godotenv.go
Expand Up @@ -96,24 +96,27 @@ func load(overload bool, filenames ...string) (err error) {

// ReadWithLookup gets all env vars from the files and/or lookup function and return values as
// a map rather than automatically writing values into env
func ReadWithLookup(lookupFn LookupFn, filenames ...string) (envMap map[string]string, err error) {
func ReadWithLookup(lookupFn LookupFn, filenames ...string) (map[string]string, error) {
filenames = filenamesOrDefault(filenames)
envMap = make(map[string]string)
envMap := make(map[string]string)

for _, filename := range filenames {
individualEnvMap, individualErr := readFile(filename, lookupFn)

if individualErr != nil {
err = individualErr
return // return early on a spazout
return envMap, individualErr
}

for key, value := range individualEnvMap {
r := regexp.MustCompile(`^\s*\d.*`) // Keys starting with numbers are ignored
if r.MatchString(key) {
continue
}
envMap[key] = value
}
}

return
return envMap, nil
}

// Read all env (with same file loading semantics as Load) but return values as
Expand Down Expand Up @@ -235,10 +238,9 @@ var exportRegex = regexp.MustCompile(`^\s*(?:export\s+)?(.*?)\s*$`)
func parseLine(line string, envMap map[string]string) (key string, value string, err error) {
return parseLineWithLookup(line, envMap, nil)
}
func parseLineWithLookup(line string, envMap map[string]string, lookupFn LookupFn) (key string, value string, err error) {
func parseLineWithLookup(line string, envMap map[string]string, lookupFn LookupFn) (string, string, error) {
if len(line) == 0 {
err = errors.New("zero length string")
return
return "", "", errors.New("zero length string")
}

// ditch the comments (but keep quoted hashes)
Expand Down Expand Up @@ -273,14 +275,13 @@ func parseLineWithLookup(line string, envMap map[string]string, lookupFn LookupF
}

if len(splitString) != 2 {
err = errors.New("can't separate key from value")
return
return "", "", errors.New("can't separate key from value")
}
key = exportRegex.ReplaceAllString(splitString[0], "$1")
key := exportRegex.ReplaceAllString(splitString[0], "$1")

// Parse the value
value = parseValue(splitString[1], envMap, lookupFn)
return
value := parseValue(splitString[1], envMap, lookupFn)
return key, value, nil
}

var (
Expand Down

0 comments on commit 55f898e

Please sign in to comment.