Commit a94a390e authored by Daniel Martí's avatar Daniel Martí

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í <mvdan@mvdan.cc>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Reviewed-by: 's avatarIan Lance Taylor <iant@golang.org>
parent a5f8128e
......@@ -24,8 +24,12 @@ func Expand(s string, mapping func(string) string) string {
}
buf = append(buf, s[i:j]...)
name, w := getShellName(s[j+1:])
// If the name is empty, keep the $.
if name == "" {
if name == "" && w > 0 {
// Encountered invalid syntax; eat the
// characters.
} else if name == "" {
// Valid syntax, but $ was not followed by a
// name. Leave the dollar character untouched.
buf = append(buf, s[j])
} else {
buf = append(buf, mapping(name)...)
......@@ -74,10 +78,13 @@ func getShellName(s string) (string, int) {
// Scan to closing brace
for i := 1; i < len(s); i++ {
if s[i] == '}' {
if i == 1 {
return "", 2 // Bad syntax; eat "${}"
}
return s[1:i], i + 1
}
}
return "", 1 // Bad syntax; just eat the brace.
return "", 1 // Bad syntax; eat "${"
case isShellSpecialVar(s[0]):
return s[0:1], 1
}
......
......@@ -51,6 +51,10 @@ var expandTests = []struct {
{"A$$$#$1$H$home_1*B", "APIDNARGSARGUMENT1(Value of H)/usr/foo*B"},
{"start$+middle$^end$", "start$+middle$^end$"},
{"mixed$|bag$$$", "mixed$|bagPID$"},
{"$", "$"},
{"$}", "$}"},
{"${", ""}, // invalid syntax; eat up the characters
{"${}", ""}, // invalid syntax; eat up the characters
}
func TestExpand(t *testing.T) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment