aboutsummaryrefslogtreecommitdiff
path: root/libgo/go/os/env.go
diff options
context:
space:
mode:
Diffstat (limited to 'libgo/go/os/env.go')
-rw-r--r--libgo/go/os/env.go24
1 files changed, 21 insertions, 3 deletions
diff --git a/libgo/go/os/env.go b/libgo/go/os/env.go
index 4e0171f..330297b 100644
--- a/libgo/go/os/env.go
+++ b/libgo/go/os/env.go
@@ -14,18 +14,33 @@ import (
// Expand replaces ${var} or $var in the string based on the mapping function.
// For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).
func Expand(s string, mapping func(string) string) string {
- buf := make([]byte, 0, 2*len(s))
+ var buf []byte
// ${} is all ASCII, so bytes are fine for this operation.
i := 0
for j := 0; j < len(s); j++ {
if s[j] == '$' && j+1 < len(s) {
+ if buf == nil {
+ buf = make([]byte, 0, 2*len(s))
+ }
buf = append(buf, s[i:j]...)
name, w := getShellName(s[j+1:])
- buf = append(buf, mapping(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)...)
+ }
j += w
i = j + 1
}
}
+ if buf == nil {
+ return s
+ }
return string(buf) + s[i:]
}
@@ -63,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
}