84 lines
2.5 KiB
Go
84 lines
2.5 KiB
Go
package go_environment
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
// variableExpression is a regular expression for environment variables
|
|
//
|
|
// A match will look like
|
|
// - %<variableName>% (Windows-Notation)
|
|
//
|
|
// or
|
|
// - $(<variableName>) (Unix-Notation)
|
|
variableExpression = regexp.MustCompile(`(%([\w]+)%)|(\$\(([\w]+)\))`)
|
|
)
|
|
|
|
// ReplaceEnvironmentVariablesExt replaces all available
|
|
// environment variables (defined as %<variableName>%) within
|
|
// a string possibly also returning an error if necessary.
|
|
func ReplaceEnvironmentVariablesExt(value string) (string, error) {
|
|
analysable := value
|
|
subStrings := variableExpression.FindStringSubmatch(analysable)
|
|
usedVariables := make(map[string]string)
|
|
missingVariables := make([]string, 0)
|
|
var err error
|
|
if len(subStrings) == 5 {
|
|
for {
|
|
if subStrings[2] != "" {
|
|
variableKey := subStrings[2]
|
|
|
|
variableValue, found := os.LookupEnv(variableKey)
|
|
if found {
|
|
usedVariables[variableKey] = variableValue
|
|
analysable = strings.ReplaceAll(analysable, "%"+variableKey+"%", variableValue)
|
|
} else {
|
|
missingVariables = append(missingVariables, variableKey)
|
|
analysable = strings.ReplaceAll(analysable, "%"+variableKey+"%", variableKey)
|
|
}
|
|
}
|
|
if subStrings[4] != "" {
|
|
variableKey := subStrings[4]
|
|
|
|
variableValue, found := os.LookupEnv(variableKey)
|
|
if found {
|
|
usedVariables[variableKey] = variableValue
|
|
analysable = strings.ReplaceAll(analysable, "$("+variableKey+")", variableValue)
|
|
} else {
|
|
missingVariables = append(missingVariables, variableKey)
|
|
analysable = strings.ReplaceAll(analysable, "$("+variableKey+")", variableKey)
|
|
}
|
|
}
|
|
subStrings = variableExpression.FindStringSubmatch(analysable)
|
|
if len(subStrings) != 5 {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
result := value
|
|
for key, value := range usedVariables {
|
|
result = strings.ReplaceAll(result, "%"+key+"%", value)
|
|
result = strings.ReplaceAll(result, "$("+key+")", value)
|
|
}
|
|
if len(missingVariables) > 0 {
|
|
if len(missingVariables) == 1 {
|
|
err = fmt.Errorf("missing environment variable: %s", missingVariables[0])
|
|
} else {
|
|
err = fmt.Errorf("missing environment variables: %s", strings.Join(missingVariables, ", "))
|
|
}
|
|
}
|
|
return result, err
|
|
}
|
|
|
|
// ReplaceEnvironmentVariablesExt replaces all available
|
|
// environment variables (defined as %<variableName>%) within
|
|
// a string.
|
|
func ReplaceEnvironmentVariables(directoryPath string) string {
|
|
path, _ := ReplaceEnvironmentVariablesExt(directoryPath)
|
|
return path
|
|
}
|