// 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:])
// If the name is empty, keep the $.
i = j + 1
}
}
+ if buf == nil {
+ return s
+ }
return string(buf) + s[i:]
}