|
15 | 15 | package keepsorted |
16 | 16 |
|
17 | 17 | import ( |
| 18 | + "fmt" |
18 | 19 | "regexp" |
19 | 20 | "slices" |
20 | 21 | "strings" |
@@ -385,24 +386,23 @@ func handleTrailingComma(lgs []*lineGroup) (trimTrailingComma func([]*lineGroup) |
385 | 386 | } |
386 | 387 | } |
387 | 388 |
|
388 | | - commaLineEnd := regexp.MustCompile("(,)( *)((#|//).*)?$") |
389 | | - commentLineEnd := regexp.MustCompile("( *)((#|//).*)$") |
| 389 | + knownCommentMarkersList := knownCommentMarkers() |
| 390 | + for i, marker := range knownCommentMarkersList { |
| 391 | + // Some comment markers, such as "/*", include regex metacharacters. |
| 392 | + knownCommentMarkersList[i] = regexp.QuoteMeta(marker) |
| 393 | + } |
| 394 | + knownCommentMarkersStr := strings.Join(knownCommentMarkersList, "|") |
| 395 | + |
| 396 | + commaLineEnd := regexp.MustCompile(fmt.Sprintf(",(\\s*(%s).*)?$", knownCommentMarkersStr)) |
| 397 | + lineEnd := regexp.MustCompile(fmt.Sprintf("(\\s*(%s).*)?$", knownCommentMarkersStr)) |
390 | 398 |
|
391 | 399 | if n := len(dataGroups); n > 1 && allMatchSuffix(dataGroups[0:n-1], commaLineEnd) && !dataGroups[n-1].matchesSuffix(commaLineEnd) { |
392 | | - if dataGroups[n-1].matchesSuffix(commentLineEnd) { |
393 | | - dataGroups[n-1].replaceSuffix(commentLineEnd, ", $2") |
394 | | - } else { |
395 | | - dataGroups[n-1].append(",") |
396 | | - } |
| 400 | + dataGroups[n-1].replaceSuffix(lineEnd, ",$1") |
397 | 401 |
|
398 | 402 | return func(lgs []*lineGroup) { |
399 | 403 | for i := len(lgs) - 1; i >= 0; i-- { |
400 | 404 | if len(lgs[i].lines) > 0 { |
401 | | - if lgs[i].matchesSuffix(commentLineEnd) { |
402 | | - lgs[i].replaceSuffix(commaLineEnd, " $3") |
403 | | - } else { |
404 | | - lgs[i].trimSuffix(",") |
405 | | - } |
| 405 | + lgs[i].replaceSuffix(commaLineEnd, "$1") |
406 | 406 | return |
407 | 407 | } |
408 | 408 | } |
|
0 commit comments