1717
1818package org .checkstyle .autofix ;
1919
20+ import java .util .ArrayList ;
2021import java .util .List ;
21- import java .util .Objects ;
22- import java .util .stream .Collectors ;
2322
2423import org .openrewrite .ExecutionContext ;
2524import org .openrewrite .Recipe ;
@@ -50,20 +49,30 @@ private static final class ViolationCommentRemover extends JavaIsoVisitor<Execut
5049 @ Override
5150 public Space visitSpace (Space space , Space .Location loc , ExecutionContext ctx ) {
5251 final StringBuilder suffixAccumulator = new StringBuilder ();
52+ final List <Comment > filteredComments = new ArrayList <>();
5353
54- final List <Comment > filteredComments = space .getComments ().stream ()
55- .map (comment -> {
56- Comment result = comment ;
57- if (!comment .isMultiline () && comment instanceof TextComment ) {
58- final TextComment textComment = (TextComment ) comment ;
59- if (textComment .getText ().startsWith ("violation" )) {
60- suffixAccumulator .append (textComment .getSuffix ());
61- result = null ;
62- }
54+ for (Comment comment : space .getComments ()) {
55+ Comment result = comment ;
56+ if (!comment .isMultiline () && comment instanceof TextComment ) {
57+ final TextComment textComment = (TextComment ) comment ;
58+ if (textComment .getText ().matches ("\\ s*(\\ d+\\ s*)?violation.*" )) {
59+ if (!filteredComments .isEmpty ()) {
60+ final int lastIndex = filteredComments .size () - 1 ;
61+ final Comment previousComment = filteredComments .get (lastIndex );
62+ filteredComments .set (lastIndex ,
63+ previousComment .withSuffix (textComment .getSuffix ()));
6364 }
64- return result ; })
65- .filter (Objects ::nonNull )
66- .collect (Collectors .toList ());
65+ else {
66+ suffixAccumulator .append (textComment .getSuffix ());
67+ }
68+ result = null ;
69+ }
70+ }
71+
72+ if (result != null ) {
73+ filteredComments .add (result );
74+ }
75+ }
6776
6877 Space result ;
6978
@@ -73,16 +82,7 @@ public Space visitSpace(Space space, Space.Location loc, ExecutionContext ctx) {
7382 else {
7483 result = space .withComments (filteredComments );
7584 if (!suffixAccumulator .isEmpty ()) {
76- if (filteredComments .isEmpty ()) {
77- result = result .withWhitespace (suffixAccumulator .toString ());
78- }
79- else {
80- final Comment lastComment = filteredComments
81- .get (filteredComments .size () - 1 );
82- filteredComments .set (filteredComments .size () - 1 ,
83- lastComment .withSuffix (suffixAccumulator .toString ()));
84- result = space .withComments (filteredComments );
85- }
85+ result = result .withWhitespace (suffixAccumulator .toString ());
8686 }
8787 }
8888 return super .visitSpace (result , loc , ctx );
0 commit comments