github.com/afein/docker@v1.8.2/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 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 Read in a line delimited file with environment variables enumerated
    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  		line := scanner.Text()
    30  		// line is not empty, and not starting with '#'
    31  		if len(line) > 0 && !strings.HasPrefix(line, "#") {
    32  			data := strings.SplitN(line, "=", 2)
    33  
    34  			// trim the front of a variable, but nothing else
    35  			variable := strings.TrimLeft(data[0], whiteSpaces)
    36  
    37  			if !EnvironmentVariableRegexp.MatchString(variable) {
    38  				return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' is not a valid environment variable", variable)}
    39  			}
    40  			if len(data) > 1 {
    41  
    42  				// pass the value through, no trimming
    43  				lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1]))
    44  			} else {
    45  				// if only a pass-through variable is given, clean it up.
    46  				lines = append(lines, fmt.Sprintf("%s=%s", strings.TrimSpace(line), os.Getenv(line)))
    47  			}
    48  		}
    49  	}
    50  	return lines, scanner.Err()
    51  }
    52  
    53  var whiteSpaces = " \t"
    54  
    55  // ErrBadEnvVariable typed error for bad environment variable
    56  type ErrBadEnvVariable struct {
    57  	msg string
    58  }
    59  
    60  func (e ErrBadEnvVariable) Error() string {
    61  	return fmt.Sprintf("poorly formatted environment: %s", e.msg)
    62  }