From a94a390e5cf802e54c95afb973c2f51be76f669e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Fri, 29 Jun 2018 16:59:04 +0100 Subject: [PATCH] os: treat "${}" in Expand like in Go 1.10 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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í Run-TryBot: Ian Lance Taylor Reviewed-by: Ian Lance Taylor --- src/os/env.go | 13 ++++++++++--- src/os/env_test.go | 4 ++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/os/env.go b/src/os/env.go index 544c03446f5..330297b36ac 100644 --- a/src/os/env.go +++ b/src/os/env.go @@ -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 } diff --git a/src/os/env_test.go b/src/os/env_test.go index 218205e7c3f..4b860157b4c 100644 --- a/src/os/env_test.go +++ b/src/os/env_test.go @@ -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) {