2014-02-16 19:24:22 -05:00
|
|
|
package opts
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2014-03-06 17:49:47 -05:00
|
|
|
"fmt"
|
2014-02-16 19:24:22 -05:00
|
|
|
"os"
|
2014-03-06 17:49:47 -05:00
|
|
|
"strings"
|
2014-02-16 19:24:22 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
/*
|
|
|
|
Read in a line delimited file with environment variables enumerated
|
|
|
|
*/
|
|
|
|
func ParseEnvFile(filename string) ([]string, error) {
|
|
|
|
fh, err := os.Open(filename)
|
|
|
|
if err != nil {
|
|
|
|
return []string{}, err
|
|
|
|
}
|
2014-02-20 15:34:45 -05:00
|
|
|
defer fh.Close()
|
2014-02-18 14:22:46 -05:00
|
|
|
|
2014-03-06 17:49:47 -05:00
|
|
|
lines := []string{}
|
|
|
|
scanner := bufio.NewScanner(fh)
|
|
|
|
for scanner.Scan() {
|
|
|
|
line := scanner.Text()
|
|
|
|
// line is not empty, and not starting with '#'
|
2014-03-11 16:22:58 -04:00
|
|
|
if len(line) > 0 && !strings.HasPrefix(line, "#") {
|
|
|
|
if strings.Contains(line, "=") {
|
|
|
|
data := strings.SplitN(line, "=", 2)
|
2014-03-17 17:11:27 -04:00
|
|
|
|
|
|
|
// trim the front of a variable, but nothing else
|
|
|
|
variable := strings.TrimLeft(data[0], whiteSpaces)
|
|
|
|
if strings.ContainsAny(variable, whiteSpaces) {
|
|
|
|
return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' has white spaces", variable)}
|
|
|
|
}
|
|
|
|
|
|
|
|
// pass the value through, no trimming
|
|
|
|
lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1]))
|
2014-03-11 16:22:58 -04:00
|
|
|
} else {
|
2014-03-17 17:11:27 -04: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 17:49:47 -05:00
|
|
|
}
|
2014-02-16 19:24:22 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return lines, nil
|
|
|
|
}
|
2014-03-17 17:11:27 -04:00
|
|
|
|
|
|
|
var whiteSpaces = " \t"
|
|
|
|
|
|
|
|
type ErrBadEnvVariable struct {
|
|
|
|
msg string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e ErrBadEnvVariable) Error() string {
|
|
|
|
return fmt.Sprintf("poorly formatted environment: %s", e.msg)
|
|
|
|
}
|