From 555f37af0a67a1b12037851ace9a9ab837f6c537 Mon Sep 17 00:00:00 2001 From: Kevin Burke Date: Thu, 30 Aug 2018 12:02:32 -0600 Subject: [PATCH] Correctly parse files without trailing newline If the file did not have a newline character as the last character, parseKV() would panic with an NPE. Handle the parser changes better. Fixes #21. --- config_test.go | 16 ++++++++++++++++ parser.go | 3 +++ testdata/config-no-ending-newline | 3 +++ 3 files changed, 22 insertions(+) create mode 100644 testdata/config-no-ending-newline diff --git a/config_test.go b/config_test.go index b9122f7..f11fe38 100644 --- a/config_test.go +++ b/config_test.go @@ -362,3 +362,19 @@ func TestDosLinesEndingsDecode(t *testing.T) { t.Errorf("expected HostName to be %q, got %q", "8.8.8.8", host) } } + +func TestNoTrailingNewline(t *testing.T) { + us := &UserSettings{ + userConfigFinder: testConfigFinder("testdata/config-no-ending-newline"), + systemConfigFinder: nullConfigFinder, + } + + port, err := us.GetStrict("example", "Port") + if err != nil { + t.Fatal(err) + } + + if port != "4242" { + t.Errorf("wrong port: got %q want 4242", port) + } +} diff --git a/parser.go b/parser.go index b99ef7d..02745b4 100644 --- a/parser.go +++ b/parser.go @@ -96,6 +96,9 @@ func (p *sshParser) parseKV() sshParserStateFn { } comment := "" tok := p.peek() + if tok == nil { + tok = &token{typ: tokenEOF} + } if tok.typ == tokenComment && tok.Position.Line == val.Position.Line { tok = p.getToken() comment = tok.val diff --git a/testdata/config-no-ending-newline b/testdata/config-no-ending-newline new file mode 100644 index 0000000..74347a4 --- /dev/null +++ b/testdata/config-no-ending-newline @@ -0,0 +1,3 @@ +Host example + HostName example.com + Port 4242 \ No newline at end of file