1/* 2Copyright 2017 The Kubernetes Authors. 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package util 18 19import ( 20 "bufio" 21 "bytes" 22 "fmt" 23 "os" 24 "strings" 25 "unicode" 26 "unicode/utf8" 27 28 "k8s.io/apimachinery/pkg/util/validation" 29) 30 31var utf8bom = []byte{0xEF, 0xBB, 0xBF} 32 33// processEnvFileLine returns a blank key if the line is empty or a comment. 34// The value will be retrieved from the environment if necessary. 35func processEnvFileLine(line []byte, filePath string, 36 currentLine int) (key, value string, err error) { 37 38 if !utf8.Valid(line) { 39 return ``, ``, fmt.Errorf("env file %s contains invalid utf8 bytes at line %d: %v", 40 filePath, currentLine+1, line) 41 } 42 43 // We trim UTF8 BOM from the first line of the file but no others 44 if currentLine == 0 { 45 line = bytes.TrimPrefix(line, utf8bom) 46 } 47 48 // trim the line from all leading whitespace first 49 line = bytes.TrimLeftFunc(line, unicode.IsSpace) 50 51 // If the line is empty or a comment, we return a blank key/value pair. 52 if len(line) == 0 || line[0] == '#' { 53 return ``, ``, nil 54 } 55 56 data := strings.SplitN(string(line), "=", 2) 57 key = data[0] 58 if errs := validation.IsEnvVarName(key); len(errs) != 0 { 59 return ``, ``, fmt.Errorf("%q is not a valid key name: %s", key, strings.Join(errs, ";")) 60 } 61 62 if len(data) == 2 { 63 value = data[1] 64 } else { 65 // No value (no `=` in the line) is a signal to obtain the value 66 // from the environment. 67 value = os.Getenv(key) 68 } 69 return 70} 71 72// AddFromEnvFile processes an env file allows a generic addTo to handle the 73// collection of key value pairs or returns an error. 74func AddFromEnvFile(filePath string, addTo func(key, value string) error) error { 75 f, err := os.Open(filePath) 76 if err != nil { 77 return err 78 } 79 defer f.Close() 80 81 scanner := bufio.NewScanner(f) 82 currentLine := 0 83 for scanner.Scan() { 84 // Process the current line, retrieving a key/value pair if 85 // possible. 86 scannedBytes := scanner.Bytes() 87 key, value, err := processEnvFileLine(scannedBytes, filePath, currentLine) 88 if err != nil { 89 return err 90 } 91 currentLine++ 92 93 if len(key) == 0 { 94 // no key means line was empty or a comment 95 continue 96 } 97 98 if err = addTo(key, value); err != nil { 99 return err 100 } 101 } 102 return nil 103} 104