From 9001b882504d2b1f4a46940cca3cad15190a6cea Mon Sep 17 00:00:00 2001 From: "John Barton (joho)" Date: Wed, 31 Jul 2013 12:37:08 +1000 Subject: [PATCH] Ignore comment lines and lines full o' whitespace. --- godotenv.go | 13 ++++++++++--- godotenv_test.go | 23 ++++++++++++++++++++--- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/godotenv.go b/godotenv.go index bd7fcda..2a3c4fc 100644 --- a/godotenv.go +++ b/godotenv.go @@ -42,10 +42,12 @@ func loadFile(filename string) (err error) { } for _, fullLine := range lines { - key, value, err := parseLine(fullLine) + if !isIgnoredLine(fullLine) { + key, value, err := parseLine(fullLine) - if err == nil { - os.Setenv(key, value) + if err == nil { + os.Setenv(key, value) + } } } @@ -116,3 +118,8 @@ func parseLine(line string) (key string, value string, err error) { return } + +func isIgnoredLine(line string) bool { + trimmedLine := strings.Trim(line, " \n\t") + return len(trimmedLine) == 0 || strings.HasPrefix(trimmedLine, "#") +} diff --git a/godotenv_test.go b/godotenv_test.go index 47acbc2..933595c 100644 --- a/godotenv_test.go +++ b/godotenv_test.go @@ -92,9 +92,6 @@ func TestParsing(t *testing.T) { parseAndCompare(t, "FOO='bar#baz' # comment", "FOO", "bar#baz") parseAndCompare(t, "FOO=\"bar#baz#bang\" # comment", "FOO", "bar#baz#bang") - // it 'ignores comment lines' do - // expect(env("\n\n\n # HERE GOES FOO \nfoo=bar")).to eql('foo' => 'bar') - // it 'parses # in quoted values' do // expect(env('foo="ba#r"')).to eql('foo' => 'ba#r') // expect(env("foo='ba#r'")).to eql('foo' => 'ba#r') @@ -108,7 +105,27 @@ func TestParsing(t *testing.T) { if err == nil { t.Errorf("Expected \"%v\" to return error, but it didn't", badlyFormattedLine) } +} +func TestLinesToIgnore(t *testing.T) { // it 'ignores empty lines' do // expect(env("\n \t \nfoo=bar\n \nfizz=buzz")).to eql('foo' => 'bar', 'fizz' => 'buzz') + if !isIgnoredLine("\n") { + t.Error("Line with nothing but line break wasn't ignored") + } + + if !isIgnoredLine("\t\t ") { + t.Error("Line full of whitespace wasn't ignored") + } + + // it 'ignores comment lines' do + // expect(env("\n\n\n # HERE GOES FOO \nfoo=bar")).to eql('foo' => 'bar') + if !isIgnoredLine("# comment") { + t.Error("Comment wasn't ignored") + } + + if !isIgnoredLine("\t#comment") { + t.Error("Indented comment wasn't ignored") + } + }