github.com/hernad/nomad@v1.6.112/helper/args/args.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package args
     5  
     6  import "regexp"
     7  
     8  var (
     9  	envRe = regexp.MustCompile(`\${[a-zA-Z0-9_\-\.]+}`)
    10  )
    11  
    12  // ReplaceEnv takes an arg and replaces all occurrences of environment variables.
    13  // If the variable is found in the passed map it is replaced, otherwise the
    14  // original string is returned.
    15  func ReplaceEnv(arg string, environments ...map[string]string) string {
    16  	return envRe.ReplaceAllStringFunc(arg, func(arg string) string {
    17  		stripped := arg[2 : len(arg)-1]
    18  		for _, env := range environments {
    19  			if value, ok := env[stripped]; ok {
    20  				return value
    21  			}
    22  		}
    23  
    24  		return arg
    25  	})
    26  }
    27  
    28  // ReplaceEnvWithPlaceHolder replaces all occurrences of environment variables with the placeholder string.
    29  func ReplaceEnvWithPlaceHolder(arg string, placeholder string) string {
    30  	return envRe.ReplaceAllString(arg, placeholder)
    31  }
    32  
    33  // ContainsEnv takes an arg and returns true if if contains an environment variable reference
    34  func ContainsEnv(arg string) bool {
    35  	return envRe.MatchString(arg)
    36  }