Skip to content

Commit 6bb2693

Browse files
SONARJAVA-5983 Do not raise S1220 on compact source files (#5417)
1 parent 0ce8f72 commit 6bb2693

3 files changed

Lines changed: 22 additions & 1 deletion

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
void main() {
2+
System.out.println("Hello from compact source!");
3+
}
4+
5+
int value = 1;
6+
7+
void helper() {}

java-checks/src/main/java/org/sonar/java/checks/DefaultPackageCheck.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
import org.sonar.plugins.java.api.JavaFileScanner;
2121
import org.sonar.plugins.java.api.JavaFileScannerContext;
2222
import org.sonar.plugins.java.api.tree.CompilationUnitTree;
23+
import org.sonar.plugins.java.api.tree.Tree;
24+
25+
import java.util.List;
2326

2427
@Rule(key = "S1220")
2528
public class DefaultPackageCheck implements JavaFileScanner {
@@ -28,10 +31,14 @@ public class DefaultPackageCheck implements JavaFileScanner {
2831
public void scanFile(JavaFileScannerContext context) {
2932
if (context.fileParsed()) {
3033
CompilationUnitTree cut = context.getTree();
31-
if (cut.moduleDeclaration() == null && cut.packageDeclaration() == null) {
34+
if (cut.moduleDeclaration() == null && cut.packageDeclaration() == null && !isCompactSource(cut)) {
3235
context.addIssueOnFile(this, "Move this file to a named package.");
3336
}
3437
}
3538
}
3639

40+
private static boolean isCompactSource(CompilationUnitTree cu) {
41+
List<Tree> types = cu.types();
42+
return types.size() == 1 && types.get(0).is(Tree.Kind.IMPLICIT_CLASS);
43+
}
3744
}

java-checks/src/test/java/org/sonar/java/checks/DefaultPackageCheckTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,11 @@ void with_module() {
4747
.verifyNoIssues();
4848
}
4949

50+
@Test
51+
void compact_source() {
52+
CheckVerifier.newVerifier()
53+
.onFile(mainCodeSourcesPath("checks/DefaultPackageCheckCompactSample.java"))
54+
.withCheck(new DefaultPackageCheck())
55+
.verifyNoIssues();
56+
}
5057
}

0 commit comments

Comments
 (0)