*/
package org.sonar.java.ast.check;
+import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TextBlock;
import org.sonar.squid.recognizer.CodeRecognizer;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import java.util.Set;
*/
@Override
public void leaveFile(DetailAST ast) {
- SourceFile sourceFile = (SourceFile) peekSourceCode();
+ List<Integer> commentedOutCodeLines = Lists.newArrayList();
for (TextBlock comment : comments) {
String[] lines = comment.getText();
for (int i = 0; i < lines.length; i++) {
if (codeRecognizer.isLineOfCode(lines[i])) {
- CheckMessage message = new CheckMessage(this, "This block of commented-out lines of code should be removed.");
- message.setLine(comment.getStartLineNo() + i);
- sourceFile.log(message);
+ // Mark all remaining lines from this comment as a commented out lines of code
+ for (int j = i; j < lines.length; j++) {
+ commentedOutCodeLines.add(comment.getStartLineNo() + j);
+ }
break;
}
}
}
+
+ // Greedy algorithm to split lines on blocks and to report only one violation per block
+ SourceFile sourceFile = (SourceFile) peekSourceCode();
+ Collections.sort(commentedOutCodeLines);
+ int prev = Integer.MIN_VALUE;
+ for (int i = 0; i < commentedOutCodeLines.size(); i++) {
+ int current = commentedOutCodeLines.get(i);
+ if (prev + 1 < current) {
+ CheckMessage message = new CheckMessage(this, "This block of commented-out lines of code should be removed.");
+ message.setLine(current);
+ sourceFile.log(message);
+ }
+ prev = current;
+ }
+
comments = null;
}
CheckMessages checkMessages = new CheckMessages(sourceFile);
checkMessages.assertNext().atLine(32).withMessage("This block of commented-out lines of code should be removed.");
- checkMessages.assertNext().atLine(33);
- checkMessages.assertNext().atLine(34);
-
checkMessages.assertNext().atLine(38);
-
checkMessages.assertNext().atLine(44);
- checkMessages.assertNext().atLine(45);
- checkMessages.assertNext().atLine(46);
-
checkMessages.assertNext().atLine(50);
-
checkMessages.assertNext().atLine(66);
-
checkMessages.assertNext().atLine(75);
checkMessages.assertNoMore();