Skip to content

Commit cee7b81

Browse files
committed
Ensure comment groups are sorted
1 parent 9f07f21 commit cee7b81

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

testdata/src/default_config/remove_whitespace.go

+14
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,20 @@ func RemoveWhiteSpaceWithhComments() { // want "block should not start with a wh
6161
// This comment should be kept as well
6262
} // want "block should not end with a whitespace"
6363

64+
func MultipleCommentsAreSorted() {
65+
switch 1 {
66+
case 1: // want "block should not start with a whitespace"
67+
// Comment
68+
69+
// Comment
70+
fmt.Println("1")
71+
case 2: // want "block should not start with a whitespace"
72+
// Comment
73+
74+
// Comment
75+
fmt.Println("2")
76+
}
77+
}
6478

6579
func ExampleT() {
6680
fmt.Println("output")

testdata/src/default_config/remove_whitespace.go.golden

+13
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,19 @@ func RemoveWhiteSpaceWithhComments() { // want "block should not start with a wh
4545
// This comment should be kept as well
4646
} // want "block should not end with a whitespace"
4747

48+
func MultipleCommentsAreSorted() {
49+
switch 1 {
50+
case 1: // want "block should not start with a whitespace"
51+
// Comment
52+
// Comment
53+
fmt.Println("1")
54+
case 2: // want "block should not start with a whitespace"
55+
// Comment
56+
// Comment
57+
fmt.Println("2")
58+
}
59+
}
60+
4861
func ExampleT() {
4962
fmt.Println("output")
5063

wsl.go

+13
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"go/ast"
66
"go/token"
77
"reflect"
8+
"sort"
89
"strings"
910
)
1011

@@ -1107,6 +1108,18 @@ func (p *processor) findLeadingAndTrailingWhitespaces(ident *ast.Ident, stmt, ne
11071108
}
11081109
}
11091110
}
1111+
1112+
// Since the comments come from a map they might not be ordered meaning
1113+
// that the last and first comment groups can be in the wrong order. We
1114+
// fix this by sorting all comments by pos after adding them all to the
1115+
// slice.
1116+
sort.Slice(firstStatementCommentGroups, func(i, j int) bool {
1117+
return firstStatementCommentGroups[i].Pos() < firstStatementCommentGroups[j].Pos()
1118+
})
1119+
1120+
sort.Slice(lastStatementCommentGroups, func(i, j int) bool {
1121+
return lastStatementCommentGroups[i].Pos() < lastStatementCommentGroups[j].Pos()
1122+
})
11101123
}
11111124

11121125
for _, commentGroup := range firstStatementCommentGroups {

0 commit comments

Comments
 (0)