From 81c255e99d8a989176bda4195847a5b169d1abf9 Mon Sep 17 00:00:00 2001 From: Fernando Barbosa Date: Sat, 9 May 2020 21:06:55 -0300 Subject: [PATCH] Fix bug that caused empty files invalid Now EndOfFileRule will not fail on empty files neither on files consisting of a single newline. It will however fail on files consisting of nothing but newlines, if SingleNewLine option is active. --- linter/eof.go | 8 +++++++- linter/eof_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/linter/eof.go b/linter/eof.go index 36b671a..11ccd9e 100644 --- a/linter/eof.go +++ b/linter/eof.go @@ -30,7 +30,13 @@ func NewEndOfFileRule(config Config) Linter { // Lint implements the Lint interface func (rule EndOfFileRule) Lint(b []byte) (valid bool, fix []byte) { - if rule.SingleNewLine { + + // for empty files + if len(b) < 1 { + return true, nil + } + + if rule.SingleNewLine && len(b) > 1 { valid = regexp.MustCompile(`[^\n]\n\z`).Match(b) } else { valid = regexp.MustCompile(`\n\z`).Match(b) diff --git a/linter/eof_test.go b/linter/eof_test.go index 3739d69..fe9e55c 100644 --- a/linter/eof_test.go +++ b/linter/eof_test.go @@ -1,6 +1,7 @@ package linter import ( + "fmt" "testing" ) @@ -52,6 +53,38 @@ func TestEOFLint_TextWithoutNewLine(t *testing.T) { } } +func TestEOFLint_EmptyString(t *testing.T) { + + // empty files are valid + got, _ := NewEndOfFileRule(autofixTestConf).Lint([]byte("")) + + if got != true { + t.Errorf("NewEndOfFileRule(autofixTestConf).Lint(emptyFileText):\n\tExpected %v, got %v", true, got) + } +} + +func TestEOFLint_StringWithOneNewline(t *testing.T) { + // files with a single newline char are also valid + got, _ := NewEndOfFileRule(autofixTestConf).Lint([]byte(fmt.Sprintf("\n"))) + + if got != true { + t.Errorf("NewEndOfFileRule(autofixTestConf).Lint(emptyFileText):\n\tExpected %v, got %v", true, got) + } +} + +func TestEOFLint_StringWithTwoNewlines(t *testing.T) { + // files with a two newlines should be reduced to one newline if singleNewLineRule is set + got, fixed := NewEndOfFileRule(autofixTestConf).Lint([]byte(fmt.Sprintf("\n\n"))) + + if string(fixed) != string(fmt.Sprintf("\n")) { + t.Errorf("NewEndOfFileRule(autofixTestConf).Lint(textWithoutNewLine): autofix did not work\n\tExpected:\n%q\n\tGot:\n%q", fmt.Sprintf("\n\n"), string(fixed)) + } + + if got != false { + t.Errorf("NewEndOfFileRule(autofixTestConf).Lint(emptyFileText):\n\tExpected %v, got %v", false, got) + } +} + func TestEOFLint_NotTextFile(t *testing.T) { // the 0xFFFD UTF-8 control character should be ignored, because the Lint method // does not check if the input is a valid Text file or not 'IsText' check fail