SonarScanner for Gradle (2024)

The SonarScanner for Gradle provides an easy way to start the scan of a Gradle project.

The ability to execute the SonarScanner analysis via a regular Gradle task makes it available anywhere Gradle is available (developer build, CI server, etc.), without the need to manually download, setup, and maintain a SonarScanner CLI installation. The Gradle build already has much of the information needed for the SonarScanner to successfully analyze a project. By preconfiguring 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 the general requirements on the 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 bysystemProp.

# gradle.propertiessystemProp.sonar.host.url=http://localhost:9000

Analyzing

First, you need to activate the scanner in your build. Kotlin DSL is the default choice for new Gradle builds.

Apply the SonarQube plugin dependency to your build.gradle.kts file:

plugins { id("org.sonarqube") version "versionNumber" // Replace with latest scanner version number}sonar { properties { property("sonar.projectKey", "myProjectKey") property("sonar.organization", "myOrganization") property("sonar.host.url", "myHostUrl") }}

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:

plugins { id "org.sonarqube" version "versionNumber" // Replace with latest scanner version number}sonar { properties { property "sonar.projectKey", "myProjectKey" property "sonar.organization", "myOrganization" property "sonar.host.url", "myHostUrl" }}

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 Gradle - Plugin: org.sonarqube.

Assuming a local SonarQube server with out-of-the-box settings is up and running, no further configuration is required.

You need to pass anauthentication tokenusing one of the following options:

  • Use thesonar.tokenproperty in your command line: Executegradle sonar -Dsonar.token=yourAuthenticationTokenand wait until the build has completed.
  • Create theSONAR_TOKENenvironment variable and set the token as its value before you run the analysis.

Once passing your token and running an analysis, open the web page indicated at the bottom of the console output. Your analysis results should be available shortly after the CI-side analysis is complete.

Analyzing multi-project builds

To analyze a project hierarchy, apply the SonarQube 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.

A configuration shared between subprojects can be configured in a subprojects block.

// build.gradlesubprojects { sonar { properties { property "sonar.sources", "src" } }}

Project-specific information is configured in thesonarblock of the corresponding project.

// build.gradleproject(":project1") { sonar { properties { property "sonar.branch.name", "Foo" } }}

To skip SonarScanner analysis for a particular subproject, set sonarqube.skipProject to true.

// build.gradleproject(":project2") { sonar { isSkipProject = true }}

Task dependencies

All tasks that produce output that should be included in the SonarScanner analysis need to be executed before thesonartask runs. Typically, these are compile tasks, test tasks, andcode coveragetasks.

Starting with v3.0 of the SonarScanner for Gradle, task dependencies are no longer added automatically. Instead, the SonarScanner plugin enforces the correct order of tasks withmustRunAfter. You need to be either manually run the tasks that produce output beforesonarqube, or you can add a dependency to the build script:

// build.gradleproject.tasks["sonar"].dependsOn "anotherTask"

Sample project

A simple working example is available at this URL so you can check everything is correctly configured in your env:
https://github.com/SonarSource/sonar-scanning-examples/tree/master/sonar-scanner-gradle/gradle-basic

Analysis property defaults

The SonarScanner for Gradle uses information contained in Gradle's object model to provide smart defaults for most of the standardanalysis parameters, as listed below. Note that additional defaults are provided depending on the projects.

Gradle defaults for standard Sonar properties

PropertyGradle 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}
sonar.projectBaseDir${project.projectDir}
sonar.working.directory${project.buildDir}/sonar

Additional defaults for projects with Java-base or Java plugin applied

PropertyGradle default
sonar.sourceEncoding${project.compileJava.options.encoding}
sonar.java.source${project.targetCompatibility}
sonar.java.target${project.targetCompatibility}
sonar.sources${sourceSets.main.allJava.srcDirs}(filtered to only include existing directories)
sonar.tests${sourceSets.test.allJava.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.classesDir}
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

PropertyGradle default
sonar.groovy.binaries${sourceSets.main.output.classesDir}

Additional defaults for Android projects

Additional defaults are provided for Android projects (com.android.application,com.android.library, orcom.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:

build.gradlesonar { androidVariant 'fullDebug'}
PropertyGradle 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 sonar extension to the project and its subprojects, which allows you to configure/override the analysis properties.

// in build.gradlesonar { properties { property "sonar.exclusions", "**/*Generated.java" }}

Sonar properties can also be set from the command line, or by setting a system property named exactly like the Sonar 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.host.url=http://sonar.mycompany.com -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 Sonar 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. Each system property starting withsonar.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.

// build.gradlesonar { properties { properties["sonar.sources"] += sourceSets.custom.allSource.srcDirs properties["sonar.tests"] += sourceSets.integTest.allSource.srcDirs }}

Advanced topics

If your SonarQube server is secured

If your SonarQube server is configured with HTTPS and a self-signed certificate then you must add the self-signed certificate to the trusted CA certificates of the SonarScanner. In addition, if mutual TLS is used then you must define the access to the client certificate at the SonarScanner level.

See Managing the TLS certificates on the client side.

More on configuring SonarQube properties

Let's take a closer look at thesonar.propertiesblock. As we have already seen in the examples, thepropertymethod 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 theirtoStringmethods.

Because thesonar.propertiesblock is evaluated lazily, properties of Gradle's object model can be safely referenced from within the block, without having to fear that they have not yet been set.

Troubleshooting

If you get a java.lang.OutOfMemoryError: Metaspace

Increase the metaspace size in your gradle.properties file:

org.gradle.jvmargs=-XX:MetaspaceSize=512M -XX:MaxMetaspaceSize=512M

Task not found in root project

Sometimes Gradle has a difficult time seeing arguments as arguments and instead sees them as tasks to perform. When passing commands on Windows, this can be overcome by passing the parameters inside of quotation marks; use-D “key=value”instead.

For example, the argument-D sonar.projectKey=<your-project>should be passed as-D "sonar.projectKey=<your-project>"

SonarScanner for Gradle (2024)

FAQs

How to use SonarQube with Gradle? ›

Execute gradle sonar -Dsonar. login=yourAuthenticationToken and wait until the build has completed. Once passing your token and running an analysis, open the web page indicated at the bottom of the console output. Your analysis results should be available shortly after the CI-side analysis is complete.

How do you pass arguments to build in Gradle? ›

When we want to pass input arguments from the Gradle CLI, we have two choices:
  1. setting system properties with the -D flag.
  2. setting project properties with the -P flag.
Jan 8, 2024

How do I improve my Gradle build? ›

Improve the Performance of Gradle Builds
  1. Inspect your build.
  2. Update versions.
  3. Enable parallel execution.
  4. Re-enable the Gradle Daemon.
  5. Enable the configuration cache.
  6. Enable incremental build for custom tasks.
  7. Enable the build cache.
  8. Create builds for specific developer workflows.

Are SonarLint and SonarQube the same? ›

1 - SonarQube is a server on which projects are added and analyzed. SonarLint is a plugin that is used in the IDE (Visual Studio, Eclipse, among others). 2 - SonarLint detects errors while writing the code (as a spell checker). SonarQube provides a 360º view of the code status of a project.

Does SonarQube work with Java? ›

Java. The SonarQube server requires Java version 17 and the SonarQube scanners require Java version 11 or 17.

How do I run a test in Gradle project? ›

Run Gradle tests

In your Gradle project, in the editor, create or select a test to run. From the context menu, select Run <test name>. Alternatively, click the icon in the left gutter.

Why is Gradle better than Maven? ›

Gradle shines in administering build infrastructure through its use of wrappers that support auto-provisioning, unlike Maven, which requires an extension for self-provisioning builds. Gradle can configure version-based build environments automatically and allows for custom distributions.

How to pass Gradle properties? ›

Command Line: Using the -D command-line option, you can pass a system property to the JVM, which runs Gradle. The -D option of the gradle command has the same effect as the -D option of the java command. Gradle Properties File: You can also set system properties in gradle.properties files with the prefix systemProp .

Why is Gradle so slow? ›

Make sure you're using the latest version of Gradle. Generally with every new update there is a significant improvement in performance. Note: Java 1.8 is faster than 1.6. Make sure it's updated too.

Is Gradle the best build tool? ›

Gradle is the open source build system of choice for Java, Android, and Kotlin developers. From mobile apps to microservices, from small startups to big enterprises, it helps teams deliver better software, faster.

Do Gradle tasks run in parallel? ›

Gradle provides an API that can split tasks into sections that can be executed in parallel. This allows Gradle to fully utilize the resources available and complete builds faster.

What is the difference between SonarScanner and SonarQube? ›

Sonarqube provides the intelligence to execute a scan. SonarScanner is the scanner developed in-house by Sonar Source the organisation that developed SonarQube too.

What are the top 3 benefits of SonarQube? ›

The Benefits of SonarQube Source Code Coverage
  • Improve quality.
  • Grow developer skills.
  • Continuous quality management.
  • Reduce risk.
  • Scale with ease.
Jun 26, 2023

Is sonar lint good? ›

Also, writing quality and performant code helps your program or website work as expected – which should be every developer's goal. SonarLint is a tool that helps you make sure your code is top-notch. It's like having a friendly guide who checks your code to see if it's well-written and doesn't have mistakes.

How to use JaCoCo plugin in Gradle? ›

How to setup JaCoCo with Gradle?
  1. Generate the project. Navigate to https://start.spring.io/ to generate a project with an appropriate version of build tool (Gradle), language (Java), the default version of spring. ...
  2. Import project into IDE (i.e., Eclipse) ...
  3. Add the JaCoCo configs to build. ...
  4. Generate code coverage report.
Jul 6, 2020

How do I run a Gradle scan? ›

Gradle Build Scans
  1. Step1: Create a Gradle project. ADVERTIsem*nT. Creating a Gradle project is a first step to create a build scan. ...
  2. Step2: Apply the build scan plugin. From Gradle 4.3, we can enable build scans without adding any additional configuration.

How to run sonar with Maven? ›

  1. 5 Steps to Integrate Maven with SonarQube for Effective Quality Assurance. ...
  2. Step 1: Create a Maven Project. ...
  3. Step 2: Set up SonarQube server locally. ...
  4. Step 3: Configure your project in SonarQube. ...
  5. Step 4: Run the Sonar Scanner in your project. ...
  6. Step 5: View your project report in SonarQube.
Dec 24, 2023

References

Top Articles
Latest Posts
Article information

Author: Kieth Sipes

Last Updated:

Views: 6329

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.