Skip to content

Commit a41abfe

Browse files
authored
Merge pull request #5312 from sarankumar1325/fix/env-file-utf8-bom
fix: strip UTF-8 BOM from env files
2 parents 94bc03d + c3b3336 commit a41abfe

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

‎pkg/flagutil/flagutil.go‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
6969
return results
7070
}
7171

72+
// utf8BOM is the UTF-8 encoded byte order mark.
73+
const utf8BOM = "\ufeff"
74+
7275
func parseEnvVars(paths []string) ([]string, error) {
7376
vars := make([]string, 0)
7477
for _, path := range paths {
@@ -79,8 +82,16 @@ func parseEnvVars(paths []string) ([]string, error) {
7982
defer f.Close()
8083

8184
sc := bufio.NewScanner(f)
85+
firstLine := true
8286
for sc.Scan() {
83-
line := strings.TrimSpace(sc.Text())
87+
text := sc.Text()
88+
if firstLine {
89+
// Editors on Windows often save files with a UTF-8 byte order mark.
90+
// Strip it like Docker does, so it does not end up in the first variable name.
91+
text = strings.TrimPrefix(text, utf8BOM)
92+
firstLine = false
93+
}
94+
line := strings.TrimSpace(text)
8495
// skip comment lines and empty line
8596
if len(line) == 0 || strings.HasPrefix(line, "#") {
8697
continue

‎pkg/flagutil/flagutil_test.go‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,16 @@ and_underscore=working too`
133133
}
134134
}
135135

136+
// Test TestParseEnvFileWithBOM for an env file that starts with a UTF-8 byte order mark.
137+
func TestParseEnvFileWithBOM(t *testing.T) {
138+
tmpFile := tmpFileWithContent(t, "\ufefffoo=bar\nbaz=quux\n")
139+
tmpFile2 := tmpFileWithContent(t, "\ufeff# comment\nqux=quuz\n")
140+
141+
lines, err := parseEnvVars([]string{tmpFile, tmpFile2})
142+
assert.NilError(t, err)
143+
assert.DeepEqual(t, lines, []string{"foo=bar", "baz=quux", "qux=quuz"})
144+
}
145+
136146
// Test TestParseEnvFileEmptyFile for an empty file.
137147
func TestParseEnvFileEmptyFile(t *testing.T) {
138148
tmpFile := tmpFileWithContent(t, "")

0 commit comments

Comments
 (0)