| 1 |
// Copyright (c) 2018, Daniel Martà <[email protected]> |
| 2 |
// See LICENSE for licensing information |
| 3 |
|
| 4 |
package shell |
| 5 |
|
| 6 |
import ( |
| 7 |
"os" |
| 8 |
"strings" |
| 9 |
|
| 10 |
"mvdan.cc/sh/v3/expand" |
| 11 |
"mvdan.cc/sh/v3/syntax" |
| 12 |
) |
| 13 |
|
| 14 |
// Expand performs shell expansion on s as if it were within double quotes, |
| 15 |
// using env to resolve variables. This includes parameter expansion, arithmetic |
| 16 |
// expansion, and quote removal. |
| 17 |
// |
| 18 |
// If env is nil, the current environment variables are used. Empty variables |
| 19 |
// are treated as unset; to support variables which are set but empty, use the |
| 20 |
// [expand] package directly. |
| 21 |
// |
| 22 |
// Other forms of expansion are not supported in this simple API, such as |
| 23 |
// command substitutions like $(echo foo). To support them, use the [expand] package. |
| 24 |
// |
| 25 |
// An error will be reported if the input string had invalid syntax. |
| 26 |
func Expand(s string, env func(string) string) (string, error) { |
| 27 |
p := syntax.NewParser() |
| 28 |
word, err := p.Document(strings.NewReader(s)) |
| 29 |
if err != nil { |
| 30 |
return "", err |
| 31 |
} |
| 32 |
if env == nil { |
| 33 |
env = os.Getenv |
| 34 |
} |
| 35 |
cfg := &expand.Config{Env: expand.FuncEnviron(env)} |
| 36 |
return expand.Document(cfg, word) |
| 37 |
} |
| 38 |
|
| 39 |
// Fields performs shell expansion on s as if it were a command's arguments, |
| 40 |
// using env to resolve variables. It is similar to Expand, but includes brace |
| 41 |
// expansion, tilde expansion, and word splitting. |
| 42 |
// |
| 43 |
// If env is nil, the current environment variables are used. Empty variables |
| 44 |
// are treated as unset; to support variables which are set but empty, use the |
| 45 |
// [expand] package directly. |
| 46 |
// |
| 47 |
// Other forms of expansion are not supported in this simple API, such as |
| 48 |
// globbing and command substitutions like $(echo foo). |
| 49 |
// To support them, use the [expand] package. |
| 50 |
// |
| 51 |
// An error will be reported if the input string had invalid syntax. |
| 52 |
func Fields(s string, env func(string) string) ([]string, error) { |
| 53 |
p := syntax.NewParser() |
| 54 |
var words []*syntax.Word |
| 55 |
for w, err := range p.WordsSeq(strings.NewReader(s)) { |
| 56 |
if err != nil { |
| 57 |
return nil, err |
| 58 |
} |
| 59 |
words = append(words, w) |
| 60 |
} |
| 61 |
if env == nil { |
| 62 |
env = os.Getenv |
| 63 |
} |
| 64 |
cfg := &expand.Config{Env: expand.FuncEnviron(env)} |
| 65 |
return expand.Fields(cfg, words...) |
| 66 |
} |