github.com/lafolle/docker@v1.6.0/opts/envfile.go (about)

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