44 "bufio"
55 "bytes"
66 "fmt"
7+ "io"
78 "os"
89 "strings"
910 "unicode"
@@ -21,15 +22,22 @@ func (e ErrBadKey) Error() string {
2122 return fmt .Sprintf ("poorly formatted environment: %s" , e .msg )
2223}
2324
24- func parseKeyValueFile (filename string , emptyFn func (string ) (string , bool )) ([]string , error ) {
25+ func parseKeyValueFile (filename string , lookupFn func (string ) (string , bool )) ([]string , error ) {
2526 fh , err := os .Open (filename )
2627 if err != nil {
2728 return []string {}, err
2829 }
2930 defer fh .Close ()
31+ return ParseKeyValueFile (fh , filename , lookupFn )
32+ }
3033
34+ // ParseKeyValueFile parse a file containing key,value pairs separated by equal sign
35+ // Lines starting with `#` are ignored
36+ // If a key is declared without a value (no equal sign), lookupFn is requested to provide value for the given key
37+ // value is returned as-is, without any kind of parsing but removal of leading whitespace
38+ func ParseKeyValueFile (r io.Reader , filename string , lookupFn func (string ) (string , bool )) ([]string , error ) {
3139 lines := []string {}
32- scanner := bufio .NewScanner (fh )
40+ scanner := bufio .NewScanner (r )
3341 currentLine := 0
3442 utf8bom := []byte {0xEF , 0xBB , 0xBF }
3543 for scanner .Scan () {
@@ -62,8 +70,8 @@ func parseKeyValueFile(filename string, emptyFn func(string) (string, bool)) ([]
6270 lines = append (lines , variable + "=" + value )
6371 } else {
6472 var present bool
65- if emptyFn != nil {
66- value , present = emptyFn (line )
73+ if lookupFn != nil {
74+ value , present = lookupFn (line )
6775 }
6876 if present {
6977 // if only a pass-through variable is given, clean it up.
0 commit comments