2015-09-26 22:37:48 +00:00
|
|
|
package args
|
|
|
|
|
2015-11-18 17:41:05 +00:00
|
|
|
import "regexp"
|
2015-09-26 22:37:48 +00:00
|
|
|
|
|
|
|
var (
|
|
|
|
envRe = regexp.MustCompile(`\$({[a-zA-Z0-9_]+}|[a-zA-Z0-9_]+)`)
|
|
|
|
)
|
|
|
|
|
|
|
|
// ParseAndReplace takes the user supplied args and a map of environment
|
|
|
|
// variables. It replaces any instance of an environment variable in the args
|
2015-11-18 17:41:05 +00:00
|
|
|
// with the actual value.
|
2015-11-18 20:40:34 +00:00
|
|
|
func ParseAndReplace(args []string, env map[string]string) []string {
|
2015-11-18 17:41:05 +00:00
|
|
|
replaced := make([]string, len(args))
|
|
|
|
for i, arg := range args {
|
2015-11-06 18:41:42 +00:00
|
|
|
replaced[i] = ReplaceEnv(arg, env)
|
2015-09-26 22:37:48 +00:00
|
|
|
}
|
|
|
|
|
2015-11-18 20:40:34 +00:00
|
|
|
return replaced
|
2015-09-26 22:37:48 +00:00
|
|
|
}
|
|
|
|
|
2015-11-18 17:41:05 +00:00
|
|
|
// ReplaceEnv takes an arg and replaces all occurences of environment variables.
|
2015-09-26 22:37:48 +00:00
|
|
|
// If the variable is found in the passed map it is replaced, otherwise the
|
|
|
|
// original string is returned.
|
2015-11-06 18:41:42 +00:00
|
|
|
func ReplaceEnv(arg string, env map[string]string) string {
|
2015-09-26 22:37:48 +00:00
|
|
|
return envRe.ReplaceAllStringFunc(arg, func(arg string) string {
|
|
|
|
stripped := arg[1:]
|
|
|
|
if stripped[0] == '{' {
|
|
|
|
stripped = stripped[1 : len(stripped)-1]
|
|
|
|
}
|
|
|
|
|
|
|
|
if value, ok := env[stripped]; ok {
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
|
|
|
return arg
|
|
|
|
})
|
|
|
|
}
|