github.com/huiliang/nomad@v0.2.1-0.20151124023127-7a8b664699ff/client/driver/args/args.go (about)

     1  package args
     2  
     3  import "regexp"
     4  
     5  var (
     6  	envRe = regexp.MustCompile(`\$({[a-zA-Z0-9_]+}|[a-zA-Z0-9_]+)`)
     7  )
     8  
     9  // ParseAndReplace takes the user supplied args and a map of environment
    10  // variables. It replaces any instance of an environment variable in the args
    11  // with the actual value.
    12  func ParseAndReplace(args []string, env map[string]string) []string {
    13  	replaced := make([]string, len(args))
    14  	for i, arg := range args {
    15  		replaced[i] = ReplaceEnv(arg, env)
    16  	}
    17  
    18  	return replaced
    19  }
    20  
    21  // ReplaceEnv takes an arg and replaces all occurences of environment variables.
    22  // If the variable is found in the passed map it is replaced, otherwise the
    23  // original string is returned.
    24  func ReplaceEnv(arg string, env map[string]string) string {
    25  	return envRe.ReplaceAllStringFunc(arg, func(arg string) string {
    26  		stripped := arg[1:]
    27  		if stripped[0] == '{' {
    28  			stripped = stripped[1 : len(stripped)-1]
    29  		}
    30  
    31  		if value, ok := env[stripped]; ok {
    32  			return value
    33  		}
    34  
    35  		return arg
    36  	})
    37  }