github.com/kardianos/nomad@v0.1.3-0.20151022182107-b13df73ee850/client/driver/args/args.go (about)

     1  package args
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  
     7  	"github.com/mattn/go-shellwords"
     8  )
     9  
    10  var (
    11  	envRe = regexp.MustCompile(`\$({[a-zA-Z0-9_]+}|[a-zA-Z0-9_]+)`)
    12  )
    13  
    14  // ParseAndReplace takes the user supplied args and a map of environment
    15  // variables. It replaces any instance of an environment variable in the args
    16  // with the actual value and does correct splitting of the arg list.
    17  func ParseAndReplace(args string, env map[string]string) ([]string, error) {
    18  	// Set up parser.
    19  	p := shellwords.NewParser()
    20  	p.ParseEnv = false
    21  	p.ParseBacktick = false
    22  
    23  	parsed, err := p.Parse(args)
    24  	if err != nil {
    25  		return nil, fmt.Errorf("Couldn't parse args %v: %v", args, err)
    26  	}
    27  
    28  	replaced := make([]string, len(parsed))
    29  	for i, arg := range parsed {
    30  		replaced[i] = replaceEnv(arg, env)
    31  	}
    32  
    33  	return replaced, nil
    34  }
    35  
    36  // replaceEnv takes an arg and replaces all occurences of environment variables.
    37  // If the variable is found in the passed map it is replaced, otherwise the
    38  // original string is returned.
    39  func replaceEnv(arg string, env map[string]string) string {
    40  	return envRe.ReplaceAllStringFunc(arg, func(arg string) string {
    41  		stripped := arg[1:]
    42  		if stripped[0] == '{' {
    43  			stripped = stripped[1 : len(stripped)-1]
    44  		}
    45  
    46  		if value, ok := env[stripped]; ok {
    47  			return value
    48  		}
    49  
    50  		return arg
    51  	})
    52  }