2014-02-17 00:24:22 +00:00
|
|
|
package opts
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2014-03-06 22:49:47 +00:00
|
|
|
"fmt"
|
2014-02-17 00:24:22 +00:00
|
|
|
"os"
|
2015-07-12 08:33:30 +00:00
|
|
|
"regexp"
|
2014-03-06 22:49:47 +00:00
|
|
|
"strings"
|
2014-02-17 00:24:22 +00:00
|
|
|
)
|
|
|
|
|
2015-07-12 08:33:30 +00:00
|
|
|
var (
|
|
|
|
// EnvironmentVariableRegexp A regexp to validate correct environment variables
|
|
|
|
// Environment variables set by the user must have a name consisting solely of
|
|
|
|
// alphabetics, numerics, and underscores - the first of which must not be numeric.
|
|
|
|
EnvironmentVariableRegexp = regexp.MustCompile("^[[:alpha:]_][[:alpha:][:digit:]_]*$")
|
|
|
|
)
|
|
|
|
|
|
|
|
// ParseEnvFile Read in a line delimited file with environment variables enumerated
|
2014-02-17 00:24:22 +00:00
|
|
|
func ParseEnvFile(filename string) ([]string, error) {
|
|
|
|
fh, err := os.Open(filename)
|
|
|
|
if err != nil {
|
|
|
|
return []string{}, err
|
|
|
|
}
|
2014-02-20 20:34:45 +00:00
|
|
|
defer fh.Close()
|
2014-02-18 19:22:46 +00:00
|
|
|
|
2014-03-06 22:49:47 +00:00
|
|
|
lines := []string{}
|
|
|
|
scanner := bufio.NewScanner(fh)
|
|
|
|
for scanner.Scan() {
|
2015-08-21 20:28:01 +00:00
|
|
|
// trim the line from all leading whitespace first
|
|
|
|
line := strings.TrimLeft(scanner.Text(), whiteSpaces)
|
2014-03-06 22:49:47 +00:00
|
|
|
// line is not empty, and not starting with '#'
|
2014-03-11 20:22:58 +00:00
|
|
|
if len(line) > 0 && !strings.HasPrefix(line, "#") {
|
2015-07-12 08:33:30 +00:00
|
|
|
data := strings.SplitN(line, "=", 2)
|
2015-08-21 20:28:01 +00:00
|
|
|
variable := data[0]
|
2015-07-12 08:33:30 +00:00
|
|
|
|
|
|
|
if !EnvironmentVariableRegexp.MatchString(variable) {
|
|
|
|
return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' is not a valid environment variable", variable)}
|
|
|
|
}
|
|
|
|
if len(data) > 1 {
|
2014-03-17 21:11:27 +00:00
|
|
|
|
|
|
|
// pass the value through, no trimming
|
|
|
|
lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1]))
|
2014-03-11 20:22:58 +00:00
|
|
|
} else {
|
2014-03-17 21:11:27 +00:00
|
|
|
// if only a pass-through variable is given, clean it up.
|
|
|
|
lines = append(lines, fmt.Sprintf("%s=%s", strings.TrimSpace(line), os.Getenv(line)))
|
2014-03-06 22:49:47 +00:00
|
|
|
}
|
2014-02-17 00:24:22 +00:00
|
|
|
}
|
|
|
|
}
|
2015-07-01 14:54:20 +00:00
|
|
|
return lines, scanner.Err()
|
2014-02-17 00:24:22 +00:00
|
|
|
}
|
2014-03-17 21:11:27 +00:00
|
|
|
|
|
|
|
var whiteSpaces = " \t"
|
|
|
|
|
2015-07-12 08:33:30 +00:00
|
|
|
// ErrBadEnvVariable typed error for bad environment variable
|
2014-03-17 21:11:27 +00:00
|
|
|
type ErrBadEnvVariable struct {
|
|
|
|
msg string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e ErrBadEnvVariable) Error() string {
|
|
|
|
return fmt.Sprintf("poorly formatted environment: %s", e.msg)
|
|
|
|
}
|