Skip to content

Commit c6b6ae4

Browse files
committed
Keep comment spacing consistent
Comment spacing in lists is now handled consistently. Comments begin one space character after the comma delimiter, except for the terminal element, which has no comma and instead has two spaces before any comment.
1 parent a5b65f2 commit c6b6ae4

2 files changed

Lines changed: 16 additions & 8 deletions

File tree

goldens/trailing_commas.out

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
Trailing comma except for last
22
keep-sorted-test start
33
1,
4-
2,
5-
3
4+
2,
5+
3
66
keep-sorted-test end
77

88

99
Trailing comma and a comment
1010
TODO: https://github.com/google/keep-sorted/issues/33 - Fix this
1111
keep-sorted-test start
1212
1,
13-
2,
13+
2,
1414
3 # three
1515
keep-sorted-test end
1616

@@ -19,7 +19,7 @@ TODO: https://github.com/google/keep-sorted/issues/33 - Fix this
1919
keep-sorted-test start
2020
1,
2121
2, # two
22-
3
22+
3
2323
keep-sorted-test end
2424

2525
Trailing comma and a comment, last has a comment

keepsorted/block.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -386,12 +386,20 @@ func handleTrailingComma(lgs []*lineGroup) (trimTrailingComma func([]*lineGroup)
386386
}
387387

388388
if n := len(dataGroups); n > 1 && allEndInComma(dataGroups[0:n-1]) && !endInComma(dataGroups[n-1]) {
389-
dataGroups[n-1].replaceSuffix(possibleCommentLineEnd, ", $2")
389+
if dataGroups[n-1].matchesSuffix(commentLineEnd) {
390+
dataGroups[n-1].replaceSuffix(commentLineEnd, ", $2")
391+
} else {
392+
dataGroups[n-1].append(",")
393+
}
390394

391395
return func(lgs []*lineGroup) {
392396
for i := len(lgs) - 1; i >= 0; i-- {
393397
if len(lgs[i].lines) > 0 {
394-
lgs[i].replaceSuffix(commaLineEnd, " $2")
398+
if lgs[i].matchesSuffix(commentLineEnd) {
399+
lgs[i].replaceSuffix(commaLineEnd, " $3")
400+
} else {
401+
lgs[i].trimSuffix(",")
402+
}
395403
return
396404
}
397405
}
@@ -411,8 +419,8 @@ func allEndInComma(lgs []*lineGroup) bool {
411419
}
412420

413421
var (
414-
commaLineEnd = regexp.MustCompile("(,)(\\s*(#|//).*)?$")
415-
possibleCommentLineEnd = regexp.MustCompile("( +)?((#|//).*)?$")
422+
commaLineEnd = regexp.MustCompile("(,)( *)((#|//).*)?$")
423+
commentLineEnd = regexp.MustCompile("( *)((#|//).*)$")
416424
)
417425

418426
func endInComma(lg *lineGroup) bool {

0 commit comments

Comments
 (0)