Skip to content

Commit 78ea005

Browse files
committed
fix: 'package-comments' false positive for CRLF sources
1 parent 9177f50 commit 78ea005

File tree

6 files changed

+42
-1
lines changed

6 files changed

+42
-1
lines changed

lint/file.go

+5
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ func (f *File) Content() []byte {
2929
return f.content
3030
}
3131

32+
// IsCRLFTerminated returns if the file is terminated with CRLF.
33+
func (f *File) IsCRLFTerminated() bool {
34+
return bytes.HasSuffix(f.content, []byte("\r\n"))
35+
}
36+
3237
// NewFile creates a new file
3338
func NewFile(name string, content []byte, pkg *Package) (*File, error) {
3439
f, err := parser.ParseFile(pkg.fset, name, content, parser.ParseComments)

rule/package_comments.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,12 @@ func (l *lintPackageComments) Visit(_ ast.Node) ast.Visitor {
120120
if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) {
121121
endPos := l.file.ToPosition(lastCG.End())
122122
pkgPos := l.file.ToPosition(l.fileAst.Package)
123-
if endPos.Line+1 < pkgPos.Line {
123+
isDetached := endPos.Line+1 < pkgPos.Line
124+
if l.file.IsCRLFTerminated() {
125+
// Workaround for https://github.com/mgechev/revive/issues/607
126+
isDetached = endPos.Line+2 < pkgPos.Line
127+
}
128+
if isDetached {
124129
// There isn't a great place to anchor this error;
125130
// the start of the blank lines between the doc and the package statement
126131
// is at least pointing at the location of the problem.

test/package_comments_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/mgechev/revive/lint"
7+
"github.com/mgechev/revive/rule"
8+
)
9+
10+
func TestPackageCommentsIssue607NotMatch(t *testing.T) {
11+
testRule(t, "package_comments_issue607_not_match", &rule.PackageCommentsRule{}, &lint.RuleConfig{})
12+
}
13+
14+
func TestPackageCommentsIssue607Match(t *testing.T) {
15+
testRule(t, "package_comments_issue607_match", &rule.PackageCommentsRule{}, &lint.RuleConfig{})
16+
}
+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Files in these directory must have Windows line endings
2+
*.* text eol=crlf
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
/*
2+
Package fixtures has a multi-line comment.
3+
Its line endings have a carriage return.
4+
*/
5+
6+
package fixtures
7+
8+
// MATCH:4 /package comment is detached; there should be no blank lines between it and the package statement/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/*
2+
Package fixtures has a multi-line comment.
3+
Its line endings have a carriage return.
4+
*/
5+
package fixtures

0 commit comments

Comments
 (0)