1
0
mirror of https://github.com/go-task/task.git synced 2025-01-20 04:59:37 +02:00

64 lines
1.9 KiB
Go
Raw Normal View History

2018-07-22 18:05:13 -03:00
// Copyright (c) 2018, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information
package shell
import (
2018-12-15 15:44:17 -02:00
"os"
2018-07-22 18:05:13 -03:00
"strings"
2018-12-15 15:44:17 -02:00
"mvdan.cc/sh/expand"
2018-07-22 18:05:13 -03:00
"mvdan.cc/sh/syntax"
)
2018-12-15 15:44:17 -02:00
// Expand performs shell expansion on s as if it were within double quotes,
// using env to resolve variables. This includes parameter expansion, arithmetic
// expansion, and quote removal.
2018-07-22 18:05:13 -03:00
//
2018-12-15 15:44:17 -02:00
// If env is nil, the current environment variables are used. Empty variables
// are treated as unset; to support variables which are set but empty, use the
// expand package directly.
2018-07-22 18:05:13 -03:00
//
2018-12-15 15:44:17 -02:00
// Command subsitutions like $(echo foo) aren't supported to avoid running
// arbitrary code. To support those, use an interpreter with the expand package.
//
// An error will be reported if the input string had invalid syntax.
2018-07-22 18:05:13 -03:00
func Expand(s string, env func(string) string) (string, error) {
p := syntax.NewParser()
2018-12-15 15:44:17 -02:00
word, err := p.Document(strings.NewReader(s))
2018-07-22 18:05:13 -03:00
if err != nil {
return "", err
}
2018-12-15 15:44:17 -02:00
if env == nil {
env = os.Getenv
}
cfg := &expand.Config{Env: expand.FuncEnviron(env)}
return expand.Document(cfg, word)
}
// Fields performs shell expansion on s as if it were a command's arguments,
// using env to resolve variables. It is similar to Expand, but includes brace
// expansion, tilde expansion, and globbing.
//
// If env is nil, the current environment variables are used. Empty variables
// are treated as unset; to support variables which are set but empty, use the
// expand package directly.
//
// An error will be reported if the input string had invalid syntax.
func Fields(s string, env func(string) string) ([]string, error) {
p := syntax.NewParser()
var words []*syntax.Word
err := p.Words(strings.NewReader(s), func(w *syntax.Word) bool {
words = append(words, w)
return true
})
if err != nil {
return nil, err
}
if env == nil {
env = os.Getenv
2018-07-22 18:05:13 -03:00
}
2018-12-15 15:44:17 -02:00
cfg := &expand.Config{Env: expand.FuncEnviron(env)}
return expand.Fields(cfg, words...)
2018-07-22 18:05:13 -03:00
}