github.com/mheon/docker@v0.11.2-0.20150922122814-44f47903a831/opts/envfile.go (about)

     1  package opts
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"os"
     7  	"regexp"
     8  	"strings"
     9  )
    10  
    11  var (
    12  	// EnvironmentVariableRegexp is a regexp to validate correct environment variables
    13  	// Environment variables set by the user must have a name consisting solely of
    14  	// alphabetics, numerics, and underscores - the first of which must not be numeric.
    15  	EnvironmentVariableRegexp = regexp.MustCompile("^[[:alpha:]_][[:alpha:][:digit:]_]*$")
    16  )
    17  
    18  // ParseEnvFile reads a file with environment variables enumerated by lines
    19  func ParseEnvFile(filename string) ([]string, error) {
    20  	fh, err := os.Open(filename)
    21  	if err != nil {
    22  		return []string{}, err
    23  	}
    24  	defer fh.Close()
    25  
    26  	lines := []string{}
    27  	scanner := bufio.NewScanner(fh)
    28  	for scanner.Scan() {
    29  		// trim the line from all leading whitespace first
    30  		line := strings.TrimLeft(scanner.Text(), whiteSpaces)
    31  		// line is not empty, and not starting with '#'
    32  		if len(line) > 0 && !strings.HasPrefix(line, "#") {
    33  			data := strings.SplitN(line, "=", 2)
    34  			variable := data[0]
    35  
    36  			if !EnvironmentVariableRegexp.MatchString(variable) {
    37  				return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' is not a valid environment variable", variable)}
    38  			}
    39  			if len(data) > 1 {
    40  
    41  				// pass the value through, no trimming
    42  				lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1]))
    43  			} else {
    44  				// if only a pass-through variable is given, clean it up.
    45  				lines = append(lines, fmt.Sprintf("%s=%s", strings.TrimSpace(line), os.Getenv(line)))
    46  			}
    47  		}
    48  	}
    49  	return lines, scanner.Err()
    50  }
    51  
    52  var whiteSpaces = " \t"
    53  
    54  // ErrBadEnvVariable typed error for bad environment variable
    55  type ErrBadEnvVariable struct {
    56  	msg string
    57  }
    58  
    59  func (e ErrBadEnvVariable) Error() string {
    60  	return fmt.Sprintf("poorly formatted environment: %s", e.msg)
    61  }