From 19f423199812ff5a9858e597ed02e8170b4b02f4 Mon Sep 17 00:00:00 2001 From: Luis Davim Date: Sat, 21 May 2022 18:57:37 +0100 Subject: [PATCH] refactor: move regexp.MustCompile to globals --- gotenv.go | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/gotenv.go b/gotenv.go index 101fcc9..d53e84f 100644 --- a/gotenv.go +++ b/gotenv.go @@ -143,9 +143,15 @@ func StrictParse(r io.Reader) (Env, error) { return env, nil } +var ( + lineRgx = regexp.MustCompile(linePattern) + quotesRgx = regexp.MustCompile(`\A(['"])(.*)(['"])\z`) + unescapeRgx = regexp.MustCompile(`\\([^$])`) + varRgx = regexp.MustCompile(variablePattern) +) + func parseLine(s string, env Env) error { - rl := regexp.MustCompile(linePattern) - rm := rl.FindStringSubmatch(s) + rm := lineRgx.FindStringSubmatch(s) if len(rm) == 0 { return checkFormat(s, env) @@ -164,24 +170,21 @@ func parseLine(s string, env Env) error { val = strings.Trim(val, " ") // remove quotes '' or "" - rq := regexp.MustCompile(`\A(['"])(.*)(['"])\z`) - val = rq.ReplaceAllString(val, "$2") + val = quotesRgx.ReplaceAllString(val, "$2") if hdq { val = strings.ReplaceAll(val, `\n`, "\n") val = strings.ReplaceAll(val, `\r`, "\r") // Unescape all characters except $ so variables can be escaped properly - re := regexp.MustCompile(`\\([^$])`) - val = re.ReplaceAllString(val, "$1") + val = unescapeRgx.ReplaceAllString(val, "$1") } - rv := regexp.MustCompile(variablePattern) fv := func(s string) string { return varReplacement(s, hsq, env) } - val = rv.ReplaceAllStringFunc(val, fv) + val = varRgx.ReplaceAllStringFunc(val, fv) val = parseVal(val, env, hdq) env[key] = val @@ -202,6 +205,8 @@ func parseExport(st string, env Env) error { return nil } +var varNameRgx = regexp.MustCompile(`(\$)(\{?([A-Z0-9_]+)\}?)`) + func varReplacement(s string, hsq bool, env Env) string { if strings.HasPrefix(s, "\\") { return strings.TrimPrefix(s, "\\") @@ -211,9 +216,7 @@ func varReplacement(s string, hsq bool, env Env) string { return s } - sn := `(\$)(\{?([A-Z0-9_]+)\}?)` - rn := regexp.MustCompile(sn) - mn := rn.FindStringSubmatch(s) + mn := varNameRgx.FindStringSubmatch(s) if len(mn) == 0 { return s