# 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.

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 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. Plugin Status and Compatibility

The Sonar Runner plugin is the successor to the Sonar Plugin. It is currently incubating. The plugin is based on Sonar Runner 2.0, which makes it compatible with Sonar 2.11 and higher. Unlike the Sonar plugin, the Sonar Runner plugin works fine with Sonar 3.4 and higher.

## 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 `SonarRunner` extension to the project, 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"
        }
    }

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

Alternatively, Sonar properties can be set from the command line. See Section 35.6, “Configuring Sonar Settings from the Command Line” for more information.

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)

## 36.4. 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.3. 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.4. 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.5. 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.6. Skipping analysis of a project

`build.gradle`

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

## 36.5. 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.7. Analyzing custom source sets

`build.gradle`

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

## 36.6. 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.8. 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.7. 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.8. 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.

## 36.9. Executing Sonar Runner in a separate process

Depending on project size, the Sonar Runner may require a lot of memory. For this and other (mainly isolation) reasons, it is desirable to execute the Sonar Runner in a separate process. This feature will be provided once Sonar Runner 2.1 has been released and adopted by the Sonar Runner plugin. Until then, the Sonar Runner is executed in the main Gradle process. See Section 20.1, “Configuring the build environment via gradle.properties” for how to manage memory settings for that process.

## 36.10. Tasks

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

Table 36.4. Sonar Runner plugin - tasks

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