2020
2121import static java .util .regex .Pattern .compile ;
2222
23+ import com .google .common .base .CharMatcher ;
2324import com .google .common .base .Splitter ;
2425import java .util .regex .Pattern ;
25- import org .apache .commons .lang3 .StringUtils ;
2626import org .sonar .check .Rule ;
2727import org .sonar .plugins .communitydelphi .api .check .DelphiCheck ;
2828import org .sonar .plugins .communitydelphi .api .check .DelphiCheckContext ;
@@ -36,9 +36,19 @@ public class TrailingWhitespaceCheck extends DelphiCheck {
3636 private static final String MESSAGE = "Remove this trailing whitespace." ;
3737
3838 private static final Pattern NEW_LINE_DELIMITER = compile ("\r \n ?|\n " );
39+ private static final Splitter NEW_LINE_SPLITTER = Splitter .on (NEW_LINE_DELIMITER );
40+ private static final CharMatcher WHITESPACE_MATCHER =
41+ CharMatcher .inRange ((char ) 0x00 , (char ) 0x20 )
42+ .and (CharMatcher .isNot ('\r' ))
43+ .and (CharMatcher .isNot ('\n' ));
3944
4045 @ Override
4146 public void visitToken (DelphiToken token , DelphiCheckContext context ) {
47+ visitWhitespace (token , context );
48+ visitComment (token , context );
49+ }
50+
51+ private static void visitWhitespace (DelphiToken token , DelphiCheckContext context ) {
4252 if (!token .isWhitespace ()) {
4353 return ;
4454 }
@@ -50,8 +60,8 @@ public void visitToken(DelphiToken token, DelphiCheckContext context) {
5060 int line = token .getBeginLine ();
5161 int column = token .getBeginColumn ();
5262
53- String image = StringUtils . stripEnd (token .getImage (), " \t \f " );
54- var parts = Splitter . on ( NEW_LINE_DELIMITER ) .split (image );
63+ String image = WHITESPACE_MATCHER . trimTrailingFrom (token .getImage ());
64+ var parts = NEW_LINE_SPLITTER .split (image );
5565 for (String whitespace : parts ) {
5666 if (!whitespace .isEmpty ()) {
5767 context
@@ -64,4 +74,29 @@ public void visitToken(DelphiToken token, DelphiCheckContext context) {
6474 column = 0 ;
6575 }
6676 }
77+
78+ private static void visitComment (DelphiToken token , DelphiCheckContext context ) {
79+ if (!token .isComment ()) {
80+ return ;
81+ }
82+
83+ var commentLines = NEW_LINE_SPLITTER .splitToList (token .getImage ());
84+
85+ for (int i = 0 ; i < commentLines .size (); ++i ) {
86+ String commentLine = commentLines .get (i );
87+ String trimmedCommentLine = WHITESPACE_MATCHER .trimTrailingFrom (commentLine );
88+ int whitespaceLength = commentLine .length () - trimmedCommentLine .length ();
89+
90+ if (whitespaceLength > 0 ) {
91+ int line = token .getBeginLine () + i ;
92+ int column = trimmedCommentLine .length ();
93+
94+ context
95+ .newIssue ()
96+ .onFilePosition (FilePosition .from (line , column , line , column + whitespaceLength ))
97+ .withMessage (MESSAGE )
98+ .report ();
99+ }
100+ }
101+ }
67102}
0 commit comments