Skip to content

Commit a94a390

Browse files
committed
os: treat "${}" in Expand like in Go 1.10
CL 103055 made it so that invalid parameter expansions, like "$|", did not make the dollar sign silently disappear. A few edge cases were not taken into account, such as "${}" and "${", which were now printing just "$". For consistency and to not break existing programs, go back to eating up the characters when invalid syntax is encountered. For completeness, add a "$" test case too, even though its behavior is unchanged by this CL. Fixes #26135. Change-Id: I5d25db9a8356dc6047a8502e318355113a99b247 Reviewed-on: https://go-review.googlesource.com/121636 Run-TryBot: Daniel Martí <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]>
1 parent a5f8128 commit a94a390

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/os/env.go

+10-3
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,12 @@ func Expand(s string, mapping func(string) string) string {
2424
}
2525
buf = append(buf, s[i:j]...)
2626
name, w := getShellName(s[j+1:])
27-
// If the name is empty, keep the $.
28-
if name == "" {
27+
if name == "" && w > 0 {
28+
// Encountered invalid syntax; eat the
29+
// characters.
30+
} else if name == "" {
31+
// Valid syntax, but $ was not followed by a
32+
// name. Leave the dollar character untouched.
2933
buf = append(buf, s[j])
3034
} else {
3135
buf = append(buf, mapping(name)...)
@@ -74,10 +78,13 @@ func getShellName(s string) (string, int) {
7478
// Scan to closing brace
7579
for i := 1; i < len(s); i++ {
7680
if s[i] == '}' {
81+
if i == 1 {
82+
return "", 2 // Bad syntax; eat "${}"
83+
}
7784
return s[1:i], i + 1
7885
}
7986
}
80-
return "", 1 // Bad syntax; just eat the brace.
87+
return "", 1 // Bad syntax; eat "${"
8188
case isShellSpecialVar(s[0]):
8289
return s[0:1], 1
8390
}

src/os/env_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ var expandTests = []struct {
5151
{"A$$$#$1$H$home_1*B", "APIDNARGSARGUMENT1(Value of H)/usr/foo*B"},
5252
{"start$+middle$^end$", "start$+middle$^end$"},
5353
{"mixed$|bag$$$", "mixed$|bagPID$"},
54+
{"$", "$"},
55+
{"$}", "$}"},
56+
{"${", ""}, // invalid syntax; eat up the characters
57+
{"${}", ""}, // invalid syntax; eat up the characters
5458
}
5559

5660
func TestExpand(t *testing.T) {

0 commit comments

Comments
 (0)