Skip to content

Commit

Permalink
SONARGO-71 Extend "code-style-convention" to optionally support Go, a…
Browse files Browse the repository at this point in the history
…dd to common Gradle modules (#45)
  • Loading branch information
petertrr authored Dec 16, 2024
1 parent 9e1a9d1 commit b14081c
Show file tree
Hide file tree
Showing 49 changed files with 134 additions and 167 deletions.
15 changes: 0 additions & 15 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ plugins {
id 'com.jfrog.artifactory' version '4.28.2'
id 'org.sonarqube' version '6.0.1.5171'
id 'de.thetaphi.forbiddenapis' version '3.0' apply false
id 'com.diffplug.spotless' version '6.15.0'
}

allprojects {
Expand Down Expand Up @@ -51,8 +50,6 @@ subprojects {
// do not publish to Artifactory by default
artifactoryPublish.skip = true

apply plugin: 'com.diffplug.spotless'

configurations {
// include compileOnly dependencies during test
testCompile.extendsFrom compileOnly
Expand All @@ -68,18 +65,6 @@ subprojects {
}
}

// license updater
spotless {
java {
targetExclude "**/src/test/resources/**", "**/build/**", "its/sources/**", "its/plugin/projects/**"
licenseHeaderFile(rootProject.file("LICENSE_HEADER")).updateYearWithLatest(true)
}
format("javaMisc") {
target("src/**/package-info.java")
licenseHeaderFile(rootProject.file("LICENSE_HEADER"), "(@javax.annotation|@ParametersAreNonnullByDefault)").updateYearWithLatest(true)
}
}

publishing {
publications {
mavenJava(MavenPublication) {
Expand Down
1 change: 1 addition & 0 deletions its/plugin/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
plugins {
id("org.sonarsource.cloud-native.java-conventions")
id("org.sonarsource.cloud-native.code-style-conventions")
id("org.sonarsource.cloud-native.integration-test")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,12 @@
package org.sonarsource.slang;

import com.sonar.orchestrator.build.SonarScanner;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;

public class CoverageTest extends TestBase {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,10 @@
package org.sonarsource.slang;

import com.sonar.orchestrator.build.SonarScanner;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Rule;
Expand All @@ -33,6 +31,7 @@

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;

public class ExternalReportTest extends TestBase {

private static final String BASE_DIRECTORY = "projects/externalreport/";
Expand Down Expand Up @@ -74,8 +73,7 @@ public void golint() {
"pivot.go|external_golint:Names|MAJOR|5min|line:11|don't use underscores in Go names; var ascii_lowercase should be asciiLowercase\n" +
"pivot.go|external_golint:Names|MAJOR|5min|line:12|don't use underscores in Go names; var ascii_uppercase_len should be asciiUppercaseLen\n" +
"pivot.go|external_golint:Names|MAJOR|5min|line:13|don't use underscores in Go names; var ascii_lowercase_len should be asciiLowercaseLen\n" +
"pivot.go|external_golint:Names|MAJOR|5min|line:14|don't use underscores in Go names; var ascii_allowed should be asciiAllowed"
);
"pivot.go|external_golint:Names|MAJOR|5min|line:14|don't use underscores in Go names; var ascii_allowed should be asciiAllowed");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@
*/
package org.sonarsource.slang;

import java.util.List;
import org.junit.Test;
import org.sonarqube.ws.Issues;

import static org.assertj.core.api.Assertions.assertThat;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.assertj.core.groups.Tuple;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -98,9 +97,8 @@ public static void stop() {
public void test_go() throws Exception {
ClientInputFile inputFile = prepareInputFile(
"package main\n"
+ "func empty() {\n" // go:S1186 (empty function)
+ "}\n"
);
+ "func empty() {\n" // go:S1186 (empty function)
+ "}\n");

assertIssues(analyzeWithSonarLint(inputFile),
tuple("go:S1186", 2, inputFile.getPath(), IssueSeverity.CRITICAL));
Expand All @@ -110,9 +108,8 @@ public void test_go() throws Exception {
public void test_go_nosonar() throws Exception {
ClientInputFile goInputFile = prepareInputFile(
"package main\n"
+ "func empty() { // NOSONAR\n" // skipped go:S1186 (empty function)
+ "}\n"
);
+ "func empty() { // NOSONAR\n" // skipped go:S1186 (empty function)
+ "}\n");
assertThat(analyzeWithSonarLint(goInputFile)).isEmpty();
}

Expand Down Expand Up @@ -163,7 +160,6 @@ public Charset getCharset() {
return StandardCharsets.UTF_8;
}


@Override
public <G> G getClientObject() {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,8 @@
import com.sonar.orchestrator.Orchestrator;
import com.sonar.orchestrator.build.SonarScanner;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.junit.ClassRule;
import org.sonarqube.ws.Issues;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

public class TestReportTest extends TestBase {

private static final Path BASE_DIRECTORY = Paths.get("projects","measures");
private static final Path BASE_DIRECTORY = Paths.get("projects", "measures");

@ClassRule
public static Orchestrator orchestrator = Tests.ORCHESTRATOR;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import com.sonar.orchestrator.locator.Location;
import com.sonar.orchestrator.locator.MavenLocation;
import java.io.File;

import org.apache.commons.lang.StringUtils;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
Expand Down
1 change: 1 addition & 0 deletions its/ruling/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
plugins {
id("org.sonarsource.cloud-native.java-conventions")
id("org.sonarsource.cloud-native.code-style-conventions")
id("org.sonarsource.cloud-native.integration-test")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.apache.commons.lang.StringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
Expand All @@ -48,7 +47,6 @@ public class GoRulingTest {
private static Orchestrator orchestrator;
private static boolean keepSonarqubeRunning = "true".equals(System.getProperty("keepSonarqubeRunning"));


@BeforeClass
public static void setUp() {
OrchestratorBuilder builder = Orchestrator.builderEnv()
Expand Down
1 change: 1 addition & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pluginManagement {

plugins {
id("com.gradle.develocity") version "3.18.2"
id("com.diffplug.blowdryerSetup") version "1.7.1"
}

develocity {
Expand Down
19 changes: 14 additions & 5 deletions sonar-go-plugin/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import java.text.SimpleDateFormat
import java.util.HashSet
import java.util.Date
import java.util.HashSet
import java.util.jar.JarInputStream

plugins {
id("org.sonarsource.cloud-native.java-conventions")
id("org.sonarsource.cloud-native.code-style-conventions")
id("com.github.johnrengelman.shadow") version "7.1.0"
}

Expand Down Expand Up @@ -39,8 +40,12 @@ dependencies {
tasks.jar {
manifest {
val displayVersion =
if (!project.hasProperty("buildNumber")) project.version else project.version.toString()
.substring(0, project.version.toString().lastIndexOf(".")) + " (build ${project.property("buildNumber")})"
if (!project.hasProperty("buildNumber")) {
project.version
} else {
project.version.toString()
.substring(0, project.version.toString().lastIndexOf(".")) + " (build ${project.property("buildNumber")})"
}
val buildDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(Date())
val commitHash = providers.exec {
commandLine("git", "rev-parse", "HEAD")
Expand Down Expand Up @@ -68,7 +73,7 @@ tasks.jar {
"Sonar-Version" to "6.7",
"SonarLint-Supported" to "true",
"Version" to "${project.version}",
"Jre-Min-Version" to "11",
"Jre-Min-Version" to "11"
)
)
}
Expand Down Expand Up @@ -109,7 +114,11 @@ publishing {
}
}

fun enforceJarSizeAndCheckContent(file: File, minSize: Long, maxSize: Long) {
fun enforceJarSizeAndCheckContent(
file: File,
minSize: Long,
maxSize: Long,
) {
val size = file.length()
if (size < minSize) {
throw GradleException("${file.path} size ($size) too small. Min is $minSize")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ public class CodeAfterJumpGoCheck extends CodeAfterJumpCheck {
@Override
protected boolean isValidAfterJump(Tree tree) {
return tree instanceof NativeTree &&
((NativeTree) tree).nativeKind().toString().contains(LABEL);
((NativeTree) tree).nativeKind().toString().contains(LABEL);
}

@Override
protected boolean shouldIgnore(Tree tree) {
return tree instanceof NativeTree &&
((NativeTree) tree).nativeKind().toString().equals(SEMICOLON);
((NativeTree) tree).nativeKind().toString().equals(SEMICOLON);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public class DuplicateBranchGoCheck extends DuplicateBranchCheck {
@Override
protected void checkConditionalStructure(CheckContext ctx, Tree tree, ConditionalStructure conditional) {
/*
If we enter a type switch, we may find branches with similar ASTs but different semantics.
In this case, we stop exploring the conditional structure to avoid raising FPs.
* If we enter a type switch, we may find branches with similar ASTs but different semantics.
* In this case, we stop exploring the conditional structure to avoid raising FPs.
*/
if (tree instanceof MatchTree && isTypeSwitch((MatchTree) tree)) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ public class OneStatementPerLineGoCheck extends OneStatementPerLineCheck {
@Override
protected boolean shouldIgnore(Tree tree) {
return tree instanceof NativeTree &&
((NativeTree) tree).nativeKind().toString().equals(SEMICOLON);
((NativeTree) tree).nativeKind().toString().equals(SEMICOLON);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,5 @@
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
@ParametersAreNonnullByDefault
@javax.annotation.ParametersAreNonnullByDefault
package org.sonar.go.checks;

import javax.annotation.ParametersAreNonnullByDefault;
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


class ExternalProcessStreamConsumer {

private static final Logger LOG = LoggerFactory.getLogger(ExternalProcessStreamConsumer.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ static boolean fileMatch(File dest, byte[] expectedContent) throws IOException {

static byte[] getBytesFromResource(String executable) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try(InputStream in = GoConverter.class.getClassLoader().getResourceAsStream(executable)) {
try (InputStream in = GoConverter.class.getClassLoader().getResourceAsStream(executable)) {
if (in == null) {
throw new IllegalStateException(executable + " binary not found on class path");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,5 @@
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
@ParametersAreNonnullByDefault
@javax.annotation.ParametersAreNonnullByDefault
package org.sonar.go.converter;

import javax.annotation.ParametersAreNonnullByDefault;
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,9 @@ static Stream<Path> getReportPaths(SensorContext sensorContext) {
Configuration config = sensorContext.config();
Path baseDir = sensorContext.fileSystem().baseDir().toPath();
String[] reportPaths = config.getStringArray(REPORT_PATH_KEY);
return Arrays.stream(reportPaths).flatMap(reportPath ->
isWildcard(reportPath)
? getPatternPaths(baseDir, reportPath)
: getRegularPath(baseDir, reportPath));
return Arrays.stream(reportPaths).flatMap(reportPath -> isWildcard(reportPath)
? getPatternPaths(baseDir, reportPath)
: getRegularPath(baseDir, reportPath));
}

private static Stream<Path> getRegularPath(Path baseDir, String reportPath) {
Expand Down Expand Up @@ -245,14 +244,14 @@ private void add(CoverageStat coverage) {
for (int line = startLine; line <= endLine; line++) {
if (!isEmpty(line - 1)) {
lineMap.computeIfAbsent(line, key -> new LineCoverage())
.add(coverage);
.add(coverage);
}
}
}

private boolean isEmpty(int line) {
return lines != null &&
lines.get(line).trim().isEmpty();
lines.get(line).trim().isEmpty();
}

int findStartIgnoringBrace(CoverageStat coverage) {
Expand Down Expand Up @@ -307,7 +306,7 @@ void add(CoverageStat coverage) {
if (sum > Integer.MAX_VALUE) {
hits = Integer.MAX_VALUE;
} else {
hits = (int) sum;
hits = (int) sum;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,10 @@ String concat(String parentPath, String childPath) {
* See {@link GoCoverSensor#findInputFile(String, FileSystem)}
*/
public String resolve(String filePath) {
return resolvedPaths.computeIfAbsent(filePath, path ->
getAbsolutePathForOldGoVersions(path)
.orElseGet(() -> getAbsolutePath(path)
return resolvedPaths.computeIfAbsent(filePath, path -> getAbsolutePathForOldGoVersions(path)
.orElseGet(() -> getAbsolutePath(path)
.orElseGet(() -> prefixByFirstValidGoPath(path)
.orElseGet(() -> prefixByFirstGoPath(path)))));
.orElseGet(() -> prefixByFirstGoPath(path)))));
}

/**
Expand All @@ -88,7 +87,7 @@ public String resolve(String filePath) {
* unix: "_/mnt/c/src..." vs "/mnt/c/src..."
* windows: "_\c_\src..." vs "c:\src..."
*/
private static Optional<String> getAbsolutePathForOldGoVersions(String path){
private static Optional<String> getAbsolutePathForOldGoVersions(String path) {
if (path.startsWith(LINUX_ABSOLUTE_OLD_PREFIX)) {
return Optional.of(path.substring(1));
} else if (path.startsWith(WINDOWS_ABSOLUTE_OLD_PREFIX)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,5 @@
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
@ParametersAreNonnullByDefault
@javax.annotation.ParametersAreNonnullByDefault
package org.sonar.go.coverage;

import javax.annotation.ParametersAreNonnullByDefault;
Loading

0 comments on commit b14081c

Please sign in to comment.