Skip to content

Commit

Permalink
Fix bug that caused empty files invalid
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
fernandrone committed May 10, 2020
1 parent 8136e0f commit 81c255e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
8 changes: 7 additions & 1 deletion linter/eof.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
33 changes: 33 additions & 0 deletions linter/eof_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package linter

import (
"fmt"
"testing"
)

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 81c255e

Please sign in to comment.