Skip to content

Commit 9b3872f

Browse files
spboyerCopilot
andcommitted
fix: lift shellEscaper and validShellKey to package-level vars
Avoids re-allocating strings.NewReplacer and regexp.MustCompile on every call to writeExportedEnv. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 34939fb commit 9b3872f

1 file changed

Lines changed: 17 additions & 13 deletions

File tree

cli/azd/cmd/env.go

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1371,6 +1371,21 @@ func (eg *envGetValuesAction) Run(ctx context.Context) (*actions.ActionResult, e
13711371
return nil, eg.formatter.Format(env.Dotenv(), eg.writer, nil)
13721372
}
13731373

1374+
// shellEscaper escapes characters that are special inside double-quoted
1375+
// shell strings: backslashes, double quotes, dollar signs, backticks,
1376+
// and carriage returns. Built once at package level to avoid re-allocation.
1377+
var shellEscaper = strings.NewReplacer(
1378+
`\`, `\\`,
1379+
`"`, `\"`,
1380+
`$`, `\$`,
1381+
"`", "\\`",
1382+
"\r", `\r`,
1383+
)
1384+
1385+
// validShellKey matches valid POSIX shell identifiers:
1386+
// starts with a letter or underscore, followed by alphanumerics or underscores.
1387+
var validShellKey = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
1388+
13741389
// writeExportedEnv writes environment variables in shell-ready
13751390
// format (export KEY="VALUE") to the given writer. Values are
13761391
// double-quoted with embedded backslashes, double quotes, dollar
@@ -1380,25 +1395,14 @@ func writeExportedEnv(
13801395
values map[string]string,
13811396
writer io.Writer,
13821397
) error {
1383-
escaper := strings.NewReplacer(
1384-
`\`, `\\`,
1385-
`"`, `\"`,
1386-
`$`, `\$`,
1387-
"`", "\\`",
1388-
"\r", `\r`,
1389-
)
1390-
1391-
// Valid shell identifier: starts with letter or underscore, then alphanumerics/underscores
1392-
validKey := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
1393-
13941398
keys := slices.Sorted(maps.Keys(values))
13951399
for _, key := range keys {
1396-
if !validKey.MatchString(key) {
1400+
if !validShellKey.MatchString(key) {
13971401
continue
13981402
}
13991403

14001404
val := values[key]
1401-
escaped := escaper.Replace(val)
1405+
escaped := shellEscaper.Replace(val)
14021406

14031407
// Use $'...' quoting for values containing newlines so \n is
14041408
// interpreted as an actual newline by the shell.

0 commit comments

Comments
 (0)