Chapter 36. The Sonar Runner Plugin

The Sonar Runner plugin is currently incubating. Please be aware that the DSL and other configuration may change in later Gradle versions.

It is intended that this plugin will replace the older Sonar Plugin in a future Gradle version.

The Sonar Runner plugin provides integration with Sonar, a web-based platform for monitoring code quality. It is based on the Sonar Runner, a Sonar client component that analyzes source code and build outputs, and stores all collected information in the Sonar database. Compared to using the standalone Sonar Runner, the Sonar Runner plugin offers the following benefits:

Automatic provisioning of Sonar Runner

The ability to execute the Sonar Runner 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 Sonar Runner installation.

Dynamic configuration from Gradle build scripts

All of Gradle's scripting features can be leveraged to configure Sonar Runner as needed.

Extensive configuration defaults

Gradle already has much of the information needed for Sonar Runner to successfully analyze a project. By preconfiguring the Sonar Runner based on that information, the need for manual configuration is reduced significantly.

36.1. Sonar Runner version and compatibility

The default version of the Sonar Runner used by the plugin is 2.3, which makes it compatible with Sonar 3.0 and higher. For compatibility with Sonar versions earlier than 3.0, you can configure the use of an earlier Sonar Runner version (see Section 36.4, “Specifying the Sonar Runner version”).

36.2. Getting started

To get started, apply the Sonar Runner plugin to the project to be analyzed.

Example 36.1. Applying the Sonar Runner plugin

build.gradle

apply plugin: "sonar-runner"

Assuming a local Sonar server with out-of-the-box settings is up and running, no further mandatory configuration is required. Execute gradle sonarRunner and wait until the build has completed, then open the web page indicated at the bottom of the Sonar Runner output. You should now be able to browse the analysis results.

Before executing the sonarRunner task, all tasks producing output to be analysed by Sonar need to be executed. Typically, these are compile tasks, test tasks, and code coverage tasks. To meet these needs, the plugins adds a task dependency from sonarRunner on test if the java plugin is applied. Further task dependencies can be added as needed.

36.3. Configuring the Sonar Runner

The Sonar Runner plugin adds a SonarRunnerRootExtension extension to the project and a SonarRunnerExtension extension to its subprojects, which allows you to configure the Sonar Runner via key/value pairs known as Sonar properties. A typical base line configuration includes connection settings for the Sonar server and database.

Example 36.2. Configuring Sonar connection settings

build.gradle

sonarRunner {
    sonarProperties {
        property "sonar.host.url", "http://my.server.com"
        property "sonar.jdbc.url", "jdbc:mysql://my.server.com/sonar"
        property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver"
        property "sonar.jdbc.username", "Fred Flintstone"
        property "sonar.jdbc.password", "very clever"
    }
}

Alternatively, Sonar properties can be set from the command line. See 「コマンドラインでSonarの設定を行う Configuring Sonar Settings from the Command Line for more information.

For a complete list of standard Sonar properties, consult the Sonar documentation. If you happen to use additional Sonar plugins, consult their documentation.

In addition to set Sonar properties, the SonarRunnerRootExtension extension allows the configuration of the Sonar Runner version and the JavaForkOptions of the forked Sonar Runner process.

The Sonar Runner plugin leverages information contained in Gradle's object model to provide smart defaults for many of the standard Sonar properties. The defaults are summarized in the tables below. Notice that additional defaults are provided for projects that have the java-base or java plugin applied. For some properties (notably server and database connection settings), determining a suitable default is left to the Sonar Runner.

Table 36.1. Gradle defaults for standard Sonar properties

Property Gradle default
sonar.projectKey “$project.group:$project.name” (for root project of analysed hierarchy; left to Sonar Runner otherwise)
sonar.projectName project.name
sonar.projectDescription project.description
sonar.projectVersion project.version
sonar.projectBaseDir project.projectDir
sonar.working.directory “$project.buildDir/sonar”
sonar.dynamicAnalysis “reuseReports”

Table 36.2. Additional defaults when java-base plugin is applied

Property Gradle default
sonar.java.source project.sourceCompatibility
sonar.java.target project.targetCompatibility

Table 36.3. Additional defaults when java plugin is applied

Property Gradle default
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.binaries sourceSets.main.runtimeClasspath (filtered to only include directories)
sonar.libraries sourceSets.main.runtimeClasspath (filtering to only include files; rt.jar added if necessary)
sonar.surefire.reportsPath test.testResultsDir (if the directory exists)
sonar.junit.reportsPath test.testResultsDir (if the directory exists)

Table 36.4. Additional defaults when jacoco plugin is applied

Property Gradle default
sonar.jacoco.reportPath jacoco.destinationFile

36.4. Specifying the Sonar Runner version

By default, version 2.3 of the Sonar Runner is used. To specify an alternative version, set the SonarRunnerRootExtension.getToolVersion() property of the sonarRunner extension of the project the plugin was applied to to the desired version. This will result in the Sonar Runner dependency org.codehaus.sonar.runner:sonar-runner-dist:«toolVersion» being used as the Sonar Runner.

Example 36.3. Configuring Sonar runner version

build.gradle

sonarRunner {
    toolVersion = '2.3' // default
}

36.5. Analyzing Multi-Project Builds

The Sonar Runner is capable of analyzing whole project hierarchies at once. This yields a hierarchical view in the Sonar web interface, with aggregated metrics and the ability to drill down into subprojects. Analyzing a project hierarchy also takes less time than analyzing each project separately.

To analyze a project hierarchy, apply the Sonar Runner 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, like server and database connections settings, have to be configured in the sonarRunner block of this project. Any Sonar properties set on the command line also apply to this project.

Example 36.4. Global configuration settings

build.gradle

sonarRunner {
    sonarProperties {
        property "sonar.host.url", "http://my.server.com"
        property "sonar.jdbc.url", "jdbc:mysql://my.server.com/sonar"
        property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver"
        property "sonar.jdbc.username", "Fred Flintstone"
        property "sonar.jdbc.password", "very clever"
    }
}

Configuration shared between subprojects can be configured in a subprojects block.

Example 36.5. Shared configuration settings

build.gradle

subprojects {
    sonarRunner {
        sonarProperties {
            property "sonar.sourceEncoding", "UTF-8"
        }
    }
}

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

Example 36.6. Individual configuration settings

build.gradle

project(":project1") {
    sonarRunner {
        sonarProperties {
            property "sonar.language", "grvy"
        }
    }
}

To skip Sonar analysis for a particular subproject, set sonarRunner.skipProject to true.

Example 36.7. Skipping analysis of a project

build.gradle

project(":project2") {
    sonarRunner {
        skipProject = true
    }
}

36.6. Analyzing Custom Source Sets

By default, the Sonar Runner plugin 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.

Example 36.8. Analyzing custom source sets

build.gradle

sonarRunner {
    sonarProperties {
        properties["sonar.sources"] += sourceSets.custom.allSource.srcDirs
        properties["sonar.tests"] += sourceSets.integTest.allSource.srcDirs
    }
}

36.7. Analyzing languages other than Java

To analyze code written in a language other than Java, you'll need to set sonar.project.language accordingly. However, note that your Sonar server has to have the Sonar plugin that handles that programming language.

Example 36.9. Analyzing languages other than Java

build.gradle

sonarRunner {
    sonarProperties {
        property "sonar.language", "grvy" // set language to Groovy
    }
}

As of Sonar 3.4, only one language per project can be analyzed. It is, however, possible to analyze a different language for each project in a multi-project build.

36.8. More on configuring Sonar properties

Let's take a closer look at the sonarRunner.sonarProperties {} 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 sonarProperties 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() method.

Because the sonarProperties block 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.

36.9. Setting Sonar Properties from the Command Line

Sonar Properties can also be set from the command line, 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 sonarRunner -Dsonar.host.url=http://sonar.mycompany.com -Dsonar.jdbc.password=myPassword -Dsonar.verbose=true

While certainly useful at times, we do recommend to keep 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 with ""sonar." will taken into account for the sonar runner setup.

36.10. Controlling the Sonar Runner process

The Sonar Runner is executed in a forked process. This allows fine grained control over memory settings, system properties etc. just for the Sonar Runner process. The forkOptions property of the sonarRunner extension of the project that applies the sonar-runner plugin (Usually the rootProject but not necessarily) allows the process configuration to be specified. This property is not available in the SonarRunnerExtension extension applied to the subprojects.

Example 36.10. setting custom Sonar Runner fork options

build.gradle

sonarRunner {
    forkOptions {
        maxHeapSize = '512m'
    }
}

For a complete reference about the available options, see JavaForkOptions.

36.11. Tasks

The Sonar Runner plugin adds the following tasks to the project.

Table 36.5. Sonar Runner plugin - tasks

Task name Depends on Type Description
sonarRunner - SonarRunner Analyzes a project hierarchy and stores the results in the Sonar database.