SonarScanner for Gradle
The SonarScanner for Gradle provides an easy way to start SonarQube Cloud analysis of a Gradle project.
The ability to execute the SonarQube Cloud analysis via a regular Gradle task makes it available anywhere Gradle is available (CI service, etc.), without the need to manually download, setup, and maintain a SonarScanner installation. The Gradle build already has much of the information needed for SonarQube Cloud to successfully analyze a project. By configuring the analysis based on that information, the need for manual configuration is reduced significantly.
Prerequisites
- Gradle 7.3+
- Java 17
Bytecode created by javac
compilation is required for Java analysis, including Android projects.
See also Scanner environment.
Configure the scanner
Installation is automatic, but certain global properties should still be configured. A good place to configure global properties is ~/.gradle/gradle.properties
. Be aware that the scanner uses system properties so all properties should be prefixed by systemProp
.
Analyzing
The first step in the process is to activate the scanner in your build. Kotlin DSL is now the default choice for new Gradle builds. However, Groovy is still used by some developers. Apply the SonarQube Server plugin dependency to your build.gradle.kts
file below:
Apply the SonarQube Cloud plugin dependency to your build.gradle.kts
file:
If you use Groovy DSL, it is still supported for Gradle 2.1+. In that case, apply the SonarQube plugin dependency to your build.gradle
file:
Ensure that you declare the plugins in the correct sequence required by Gradle, that is, after the buildscript
block in your build.gradle
file. More details on https://plugins.gradle.org/plugin/org.sonarqube.
Execute gradle build sonar
and wait until the build has been completed, then open the web page indicated at the bottom of the console output. You should now be able to browse the analysis results.
Analyzing multi-project builds
To analyze a project hierarchy, apply the SonarQube Server plugin to the root project of the hierarchy. Typically (but not necessarily) this will be the root project of the Gradle build. Information pertaining to the analysis as a whole has to be configured in the sonar block of this project. Any properties set on the command line also apply to this project.
Configuration settings shared between subprojects can be specified in a subprojects block.
Project-specific information is configured in the sonar
block of the corresponding project.
To skip analysis for a particular subproject, set sonar.skipProject
to true.
Task dependencies
All tasks that produce output that should be included in the analysis need to be executed before the sonar
task runs. Typically, these are compile tasks, test tasks, and code coverage tasks. To meet these needs, the plugin adds a task dependency from sonar
on test
if the Java plugin is applied. Further task dependencies can be added as needed. For example:
Sample project
A simple working example is available at this URL so you can check everything is correctly configured in your environment: https://github.com/SonarSource/sonar-scanning-examples/tree/master/sonar-scanner-gradle
Adjusting the analysis scope
The analysis scope of a project determines the source and test files to be analyzed.
An initial analysis scope is set by default. With the SonarScanner for Gradle, the initial analysis scope is:
- For source files: all the files stored under
src/main/java
(in the root or module directories). - For test files: all the files stored under
src/test/java
(in the root or module directories).
Since SonarScanner for Gradle also supports Groovy and Kotlin, the initial scope will also include src/main/kotlin
or src/main/groovy
for source and test files, depending on the type of project.
To adjust the analysis scope, you can:
- Adjust the initial scope: see below.
- And/or exclude specific files from the initial scope: see Analysis scope.
Adjusting the initial scope
The initial scope is set through the sonar.sources
property (for source files) and the sonar.tests
property (for test files). See Analysis parameters for more information.
To adjust the initial scope, you can do one of the following:
- Override these properties by setting them explicitly in your build like any other relevant gradle property: see Analysis scope.
- Use the scanAll option to extend the initial scope to non-JVM-related files. See below.
Using the scanAll option to include non-JVM-related files
You may want to analyze not only the JVM main files but also files related to configuration, infrastructure, etc. An easy way to do that is to enable the scanAll option (By default, this option is disabled.)
If the scanAll option is enabled, then the initial analysis scope of source files will be:
- The files stored in
src/main/java
(andsrc/main/kotlin
orsrc/main/groovy
, depending on the type of project). - The non-JVM-related files stored in the root directory of your project.
Warning: The scanAll option is disabled if the sonar.sources
property is overridden.
To enable the scanAll option:
- Set the
sonar.gradle.scanAll
property toTrue
.
Analysis property defaults
The SonarScanner for Gradle uses information contained in Gradle's object model to provide smart defaults for most of the standard analysis parameters, as listed below. Note that additional defaults are provided depending on the projects.
Gradle defaults for standard SonarQube Cloud properties
Property | Gradle default |
---|---|
sonar.projectKey | [${project.group}:]${project.name} for root module; <root module key>:<module path> for submodules |
sonar.projectName | ${project.name} |
sonar.projectDescription | ${project.description} |
sonar.projectVersion | ${project.version} Do not use your build number as sonar.projectVersion |
sonar.projectBaseDir | ${project.projectDir} |
sonar.working.directory | ${project.buildDir}/sonar |
Additional defaults for projects with the base or Java plugins applied
Property | Gradle default |
---|---|
sonar.sourceEncoding | ${project.compileJava.options.encoding} |
sonar.java.source | ${project.sourceCompatibility} |
sonar.java.target | ${project.targetCompatibility} |
sonar.sources | ${sourceSets.main.allSource.srcDirs} (filtered to only include existing directories) |
sonar.tests | ${sourceSets.test.allSource.srcDirs} (filtered to only include existing directories) |
sonar.java.binaries | ${sourceSets.main.output.classesDir} |
sonar.java.libraries | ${sourceSets.main.compileClasspath} (filtering to only include files; rt.jar and jfxrt.jar added if necessary) |
sonar.java.test.binaries | ${sourceSets.test.output.classeDir} |
sonar.java.test.libraries | ${sourceSets.test.compileClasspath} (filtering to only include files; rt.jar and jfxrt.jar added if necessary) |
sonar.junit.reportPaths | ${test.testResultsDir} (if the directory exists) |
Additional default for Groovy projects
Property | Gradle default |
---|---|
sonar.groovy.binaries | ${sourceSets.main.output.classesDir} |
Additional defaults for Android projects
More default properties apply to Android projects (com.android.application
, com.android.library
, or com.android.test
). By default, the first variant of type debug
will be used to configure the analysis. You can override the name of the variant to be used using the parameter androidVariant
:
Property | Gradle default |
---|---|
sonar.sources (for non-test variants) | ${variant.sourcesets.map} (ManifestFile/CDirectories/AidlDirectories/AssetsDirectories/CppDirectories/JavaDirectories/RenderscriptDirectories/ResDirectories/ResourcesDirectories ) |
sonar.tests (for test variants) | ${variant.sourcesets.map} (ManifestFile/CDirectories/AidlDirectories/AssetsDirectories/CppDirectories/JavaDirectories/RenderscriptDirectories/ResDirectories/ResourcesDirectories ) |
sonar.java[.test].binaries | ${variant.destinationDir} |
sonar.java[.test].libraries | ${variant.javaCompile.classpath} + ${bootclasspath} |
sonar.java.source | ${variant.javaCompile.sourceCompatibility} |
sonar.java.target | ${variant.javaCompile.targetCompatibility} |
Passing manual properties / overriding defaults
The SonarScanner for Gradle adds a SonarQubeExtension extension to a project and its subprojects, which allows you to configure or override the analysis properties.
SonarQube Cloud properties can also be set from the command line, or by setting a system property named exactly like the SonarQube Cloud property in question. This can be useful when dealing with sensitive information (e.g. credentials), environment information, or for ad-hoc configuration.
gradle sonar -Dsonar.verbose=true
While certainly useful at times, we recommend keeping the bulk of the configuration in a (versioned) build script, readily available to everyone. A SonarQube Cloud property value set via a system property overrides any value set in a build script (for the same property). When analyzing a project hierarchy, values set via system properties apply to the root project of the analyzed hierarchy. Every system property starting with sonar
will be taken into account.
Analyzing custom source sets
By default, the SonarScanner for Gradle passes on the project's main source set as production sources, and the project's test source set as test sources. This works regardless of the project's source directory layout. Additional source sets can be added as needed.
More on configuring properties
Let's take a closer look at the sonar.properties
{}
block. As we have already seen in the examples, the property()
method allows you to set new properties or override existing ones. Furthermore, all properties that have been configured up to this point, including all properties preconfigured by Gradle, are available via the properties accessor.
Entries in the properties map can be read and written with the usual Groovy syntax. To facilitate their manipulation, values still have their “idiomatic” type (File, List, etc.). After the sonar properties
block has been evaluated, values are converted to Strings as follows: Collection values are (recursively) converted to comma-separated Strings, and all other values are converted by calling their toString()
methods.
Because the sonar properties
block is evaluated lazily, properties of Gradle's object model can be safely referenced from within the block, without fear that they have not yet been set.
Troubleshooting
If you get a java.lang.OutOfMemoryError
With SonarScanner for Gradle version 6.0 or later
Configure the sonar task in the build.gradle
file:
Or set the SONAR_SCANNER_JAVA_OPTS environment variable, like this in Unix environments:
In Windows environments, avoid the double quotes, since they get misinterpreted.
With SonarScanner for Gradle version 5.1 or earlier
Increase the java heap size in your gradle.properties
file:
If you get a java.lang.OutOfMemoryError: Metaspace
With SonarScanner for Gradle version 6.0 or later
Configure the sonar task in the build.gradle
file:
Or set the SONAR_SCANNER_JAVA_OPTS environment variable, like this in Unix environments.
In Windows environments, avoid the double quotes, since they get misinterpreted.
With SonarScanner for Gradle version 5.1 or earlier
Increase the java heap size in your gradle.properties
file:
Was this page helpful?