envfile.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package opts
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strings"
  7. )
  8. /*
  9. Read in a line delimited file with environment variables enumerated
  10. */
  11. func ParseEnvFile(filename string) ([]string, error) {
  12. fh, err := os.Open(filename)
  13. if err != nil {
  14. return []string{}, err
  15. }
  16. defer fh.Close()
  17. lines := []string{}
  18. scanner := bufio.NewScanner(fh)
  19. for scanner.Scan() {
  20. line := scanner.Text()
  21. // line is not empty, and not starting with '#'
  22. if len(line) > 0 && !strings.HasPrefix(line, "#") {
  23. if strings.Contains(line, "=") {
  24. data := strings.SplitN(line, "=", 2)
  25. // trim the front of a variable, but nothing else
  26. variable := strings.TrimLeft(data[0], whiteSpaces)
  27. if strings.ContainsAny(variable, whiteSpaces) {
  28. return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' has white spaces", variable)}
  29. }
  30. // pass the value through, no trimming
  31. lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1]))
  32. } else {
  33. // if only a pass-through variable is given, clean it up.
  34. lines = append(lines, fmt.Sprintf("%s=%s", strings.TrimSpace(line), os.Getenv(line)))
  35. }
  36. }
  37. }
  38. return lines, nil
  39. }
  40. var whiteSpaces = " \t"
  41. type ErrBadEnvVariable struct {
  42. msg string
  43. }
  44. func (e ErrBadEnvVariable) Error() string {
  45. return fmt.Sprintf("poorly formatted environment: %s", e.msg)
  46. }