Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Gradle Sonar plug-in


May 25, 2021 Gradle


Table of contents


Sonar plug-in

You may want to replace the current plug-in with the new Sonar Runner plug-in. T his is especially because only the Sonar Runner plug-in supports Sonar 3.4 and higher.

The Sonar plug-in provides integration into Sonar, a web-based code quality monitoring platform. T he plug-in adds the sonarAnalyze task to analyze which plug-in is applied to both a project and a sub-project. T he results of the analysis are stored in the Sonar database. The plug-in is based on Sonar Runner and requires a version of Sonar 2.11 or higher.

SonarAnalyze task is a stand-alone task that needs to be performed explicitly and does not depend on any other task. I n addition to the source code, the task analyzes class files and test results files, if any. F or best results, it is recommended that you run a complete build before the analysis. In a typical setting, the analysis runs once a day on the build server.

Usage

The minimum requirement is that the Sonar plug-in must be configured to be applied to the project.

The configuration uses the Sonar plug-in

build.gradle

apply plugin: "sonar"  

Unless Sonar is running locally and has a default configuration, it is necessary to configure the connection settings for the Sonar server and database.

Configure the Sonar connection settings

build.gradle

sonar
    server {
        url = "http://my.server.com"
    }
    database {
        url = "jdbc:mysql://my.server.com/sonar"
        driverClassName = "com.mysql.jdbc.Driver"
        username = "Fred Flintstone"
        password = "very clever"
    }
}  

Alternatively, some or all of the connection settings can be set from the command line.

Project settings determine how the project will be analyzed. The default configuration is ideal for analyzing standard Java projects and can be customized in many ways.

Configure the Sonar project settings

build.gradle

sonar
    project
        coberturaReportPath = file("$buildDir/cobertura.xml")
    }
}  

In the example above, the sonar, server, database, and project blocks are configured with objects of the SonarRootModel, Sonar Server, Sonar Database, and SonarProject types, respectively. You can check their API documentation for more information.

Analyze multi-project builds

The Sonar plug-in is able to analyze the hierarchy of the entire project at once. I t generates a hierarchical graph on Sonar's web interface that contains comprehensive metrics and drills down into sub-projects. At the same time, it's faster than analyzing each project individually.

To analyze the hierarchy of a project, you need to apply the Sonar plug-in to the top-level project of the hierarchy. U sually (but not necessarily) it will be the root project. T he sonar block in the project is configured with an Object of the SonarRootModel type. It has all the global configurations, the most important server and database connection settings.

Global configuration in a multi-project build

build.gradle

apply plugin: "sonar"
sonar {
    server {
        url = "http://my.server.com"
    }
    database {
        url = "jdbc:mysql://my.server.com/sonar"
        driverClassName = "com.mysql.jdbc.Driver"
        username = "Fred Flintstone"
        password = "very clever"
    }
}   

Each item in the hierarchy has its own project configuration. Common values can be set in the parent build script.

Common project configuration in multi-project builds

build.gradle

subprojects {
    sonar
        project
            sourceEncoding = "UTF-8"
        }
    }
}  

The sonar block in the subproject is configured as an Object of the SonarProjectModel type.

These Projects can also be configured separately. F or example, set the skip property to true to prevent an item (and its sub-projects) from being analyzed. Skipped items will not appear in Sonar's web interface.

Individual project configurations in multi-project builds

build.gradle

project
    sonar
        project
            skip = true
        }
    }
}  

Another typical individual project configuration is to configure the programming language to analyze. Note that Sonar can only analyze one language per project.

Configure language analysis

build.gradle

project
    sonar
        project
            language = "groovy"
        }
    }
}  

When only one property is set at a time, the syntax of the equivalent property is more concise:

Use the property syntax

build.gradle

project(":project2").sonar.project.language = "groovy"  

Analyze custom Source Sets

By default, the Sonar plug-in analyzes the production source files in the main source set, as well as the test source files in the test source. I ts analysis is independent of the project's source directory layout. You can add additional source sets as needed.

Analyze custom Source Sets

build.gradle

sonar.project {
    sourceDirs += sourceSets.custom.allSource.srcDirs
    testDirs += sourceSets.integTest.allSource.srcDirs
}  

Analyze non-Java languages

To analyze code written in a non-Java language, install the appropriate Sonar plug-in and set sonar.project.language accordingly:

Analyze non-Java languages

build.gradle

sonar.project {
    language = "grvy" // set language to Groovy
}  

As of Sonar 3.4, only one language can be analyzed per project. However, in a multi-project build, you can set up different languages for different projects.

Set a custom Sonar property

Eventually, most configurations are passed to Sonar's code analyzer as a key-value pair called the Sonar property. T he SonarProperty annotations in the API documentation show how the properties of the plug-in's object model are mapped to the appropriate Sonar properties. T he Sonar plug-in provides hooks for post-processing before the Sonar property is passed to the code analyzer. The same hook can be used to add additional properties and is not overwritten by the plug-in's object model.

For global Sonar properties, you can use the withGlobalProperties hook on SonarRootModel:

Set custom global properties

build.gradle

sonar.withGlobalProperties { props ->
    props["some.global.property"] = "some value"
    // non-String values are automatically converted to Strings
    props["other.global.property"] = ["foo", "bar", "baz"]
}  

For the Sonar property for each project, use the withProjectProperties hook on SonarProject:

Set custom project properties

build.gradle

sonar.project.withProjectProperties { props ->
    props["some.project.property"] = "some value"
    // non-String values are automatically converted to Strings
    props["other.global.property"] = ["foo", "bar", "baz"]
}  

A list of available properties for Sonar can be found in the Sonar document. N ote that for most of these properties, the object model of the Sonar plug-in has equivalent properties, and there is no need to use hooks from with GlobalProperties or WithProjectProperties. For the configuration of third-party Sonar plug-ins, see the plug-in's documentation.

Configure Sonar's settings from the command line

The following properties can either be set from the command line or as task parameters for the sonarAnalyze task. The task parameters override any corresponding values set in the build script.

  • server.url
  • database.url
  • database.driverClassName
  • database.username
  • database.password
  • showSql
  • showSqlResults
  • verbose
  • forceAnalysis

Here's a complete example:

gradle sonarAnalyze --server.url=http://sonar.mycompany.com --database.password=myPassword --verbose  

If you need to set additional properties from the command line, you can do so using system properties:

Implement custom command line properties

build.gradle

sonar.project {
    language = System.getProperty("sonar.language", "java")
}  

However, keep in mind that it is usually best to configure it in a build script and under code control.

Task

The Sonar plug-in adds the following tasks to the project.

Table 35.1. S onar plug-in - task

The name of the task Depends on Type Describe
sonarAnalyze - sonarAnalyze Analyze the project hierarchy and store the results in the Sonar database.