Chapter 7. Integration with Gradle

The SonargraphBuild Gradle plugin makes it easy to check the quality of your projects. The plugin is able to automatically download and install SonargraphBuild if your build server has Internet connectivity. You can make the build fail depending on issues detected by SonargraphBuild.

There are two different Gradle "tasks" available for which parameters can be defined in Gradle "extensions" with the same names:

  1. sonargraphReport: Creates a report for an existing system.

  2. sonargraphDynamicReport: Creates a system on-the-fly and creates a report for it. This is currently only available for Java systems.

Prerequisites:

  1. You need at least Gradle 2.9 installed.

  2. The plugin requires at least a Java 8 runtime.

7.1. Gradle Tips and Best Practices

TIP

To enforce certain rules, specify a failSet that lets the build fail based on detected issues. See Section 7.4, “Gradle FailSet Configuration”

NOTE

The attribute "logLevel" affects the logging after the SonargraphBuild engine has been started. Setting it to "debug" and below will generate additional debug information into the XML report.

WARNING

Setting the attribute "reportType" to "standard" only generates metric values for "system" and "module" levels. "full" generates values for all element levels, but results in a significant larger report!

The splitting of the HTML report into different files is controlled by the attribute "elementCountToSplit​HtmlReport". The resulting detail pages contain tables of issues / resolutions of a specific issue type. The maximum number of items shown is limited by the parameter "maxElementCountFor​HtmlDetailsPage".

WARNING

The attribute "qualityModelFile" can be used to apply a fixed set of scripts, architecture files and analyzer configurations across several systems.

The reported issues are most likely very different from the results of analyzing the system with the Sonargraph application. If you specify a "qualityModelFile", it is advisable to specify the "Parser" virtual model, since resolutions e.g. for architecture violations probably will not match.

7.2. Parameters of Task "sonargraphReport"

The following table lists all parameters that are available to create a report for an existing Sonargraph system. The build can be marked as failed based on a failSet. See Section 7.4, “Gradle FailSet Configuration”.

Attribute Mandatory Description Default
sonargraphBuildVersion No Allows you to use a specific or restricted version of SonargraphBuild. Can be used in combination with 'autoUpdate'. As an example, if you specify '8.7' the newest available version starting with '8.7' will be used. If you specify '8.7.0.361' you are locked on that specific version of SonargraphBuild. There are two special values: "same" and "newest". If "same" is defined the version of SonargraphBuild must be the same as the version of the Maven plugin. If "newest" is defined the plugin will always try to use the newest version of SonargraphBuild. same
skip No Skip SonargraphBuild. false
autoUpdate No If the plugin is configured to download SonargraphBuild automatically, this parameter decides if it also should be updated automatically if a new version becomes available. false
useHttpProxyHost No If true, the proxy configuration of the Gradle settings is used. The plugin will use this proxy for all HTTP communication. Check the Gradle online documentation for details. false
installationDirectory No Installation directory of SonargraphBuild. If unspecified the plugin will automatically download SonargraphBuild. The version to be downloaded can be controlled by the parameter 'sonargraphBuildVersion'. No default
activationCode No Sonargraph license activation code. If this parameter is not specified, you must specify a license file parameter (see below). No default
licenseServerPort No Port of license server to be used. This parameter is ignored if licenseServerHost is not set. 8080
licenseServerHost No Host name or IP address of license server. If this parameter is not specified, the web-based hello2morrow license server will be used for activation code based licenses. No default
licenseFile No Sonargraph license file location. If this parameter is not specified, you must specify the activation code parameter (see above). No default
languages No The languages that should be initialized, separated by ",". The fewer languages are specified the faster the startup of SonargraphBuild. Possible values: Java, CSharp, CPlusPlus. Java
logFile No Path of the log file to be used for SonargraphBuild. ${project.buildDir}/sonargraph_build.log
logLevel No Level of logging detail. One of: off, error, warn, info, debug, trace, all info
compilerDefinitionPath No

The path to the active compiler definition file to be used for parsing a C/C++ system. If a built-in or automatically generated definition should be used, prefix the definition with "CPlusPlus:", e.g. CPlusPlus:GnuCpp.cdef.

NOTE: If the standalone Sonargraph application is used on the same machine with the same user and this parameter is empty, the active definition specified with the standalone application will be used.

If empty, the default compiler definition for the build server's operating system is used: GnuCpp.cdef (Linux), CLang.cdef (Mac), VisualCpp*.cdef (Windows, generated definition for the latest Visual Studio installation)
systemDirectory No Directory of the Sonargraph System (xyz.sonargraph) ${project.buildDir}/${project.group}​.sonargraph
overrideSonargraphWorkspace No If true the output directories defined in the Sonargraph system will be overridden by the ones provided by the client. true
includeTestCode No If true the workspace will also contain the test source and test class file directories. false
includeEmptyModules No If true the workspace will also contain empty modules (without any source and class file directories). false
productionSourceSets No Comma separated list of source set names that contain production code. This parameter is only needed when you are not using the gradle default "main". main
testSourceSets No Comma separated list of source set names that contain test code. This parameter is only needed when you are not using the gradle default "test". test
virtualModel No The virtual model to be used when checking for issues. This parameter overrides the default virtual model that is set when the system is opened. The default virtual model is "Modifiable.vm", if virtual models are licensed, "Parser" if not licensed. Parameter can only be used with Sonargraph Architect license. No default
qualityModelFile No The path to the quality model file (xyz.sgqm) that should be applied for the report creation. Built-in quality models are the language-independent "Sonargraph:Default.sgqm" and language-specific "Sonargraph:Java.sgqm", "Sonargraph:CSharp.sgqm" and "Sonargraph:CPlusPlus.sgqm". NOTE: All scripts, analyzer configurations and architecture files present in the system are ignored! No default
snapshotDirectory No Target directory for the created snapshot. Only if either this parameter or snapshotFileName is provided, a snapshot will be generated. Parameter can only be used with Sonargraph Architect license. ${project.buildDir}
snapshotFileName No The target file name (without extension). Only if either this parameter or snapshotDirectory is provided, a snapshot will be generated. Parameter can only be used with Sonargraph Architect license. <system-name>_<timestamp>
reportDirectory No Target directory for the created report ${project.buildDir}/sonargraph
reportFileName No The target file name (without extension) <system-name>_<timestamp>
reportType No "standard" only creates metric information of system and module level. "full" creates metric information of all levels. standard
reportFormat No "xml", "html" or "xml, html" html

elementCountToSplit
HtmlReport

No Issue and resolution tables might contain too many items making it impossible to open the HTML report in a browser. This parameter controls the lower limit of items that will cause separate files being generated per issue type. Possible values are: -1 (never split), 0 (use default value), 1 (always split), positive number > 1 (threshold for split) 1000

maxElementCountFor
HtmlDetailsPage

No If HTML report is split because of too many issues and/or resolutions, detail tables might contain too many items making it impossible to open the page in a browser. This parameter controls the upper limit of elements shown in the table. Possible values are: -1 (no limit), 0 (use default limit), positive number > 1 (maximum number of elements contained in page) 2000
splitByModule No If set to 'true', individual HTML reports are created per module. false
baselineReportPath No Path of the baseline XML report that the current report is compared against No default
deltaReportPath No Path of the output file that the delta info is written to. This log file is only generated if a baselineReportPath has been specified. <reportDirectory>/<reportFileName>​_delta.log
prepareForSonarQube No Creates an XML report and stores it at ${basedir}/${target}/sonargraph/sonargraph-sonarqube-report.xml, where the SonarQube Sonargraph plugin expects it. false
Table 7.1. Configuration for Task/Extension "sonargraphReport"


Related topics:

7.3. Configuration for Task "sonargraphDynamicReport"

The following table lists all parameters that are available to create a report for a Java project where no Sonargraph system has been defined. A Sonargraph system is created on the fly based on the workspace information contained in the Gradle project setup. The build can be marked as failed based on a failSet. See Section 7.4, “Gradle FailSet Configuration”.

Attribute Mandatory Description Default
sonargraphBuildVersion No Allows you to use a specific or restricted version of SonargraphBuild. Can be used in combination with 'autoUpdate'. As an example, if you specify '8.7' the newest available version starting with '8.7' will be used. If you specify '8.7.0.361' you are locked on that specific version of SonargraphBuild. There are two special values: "same" and "newest". If "same" is defined the version of SonargraphBuild must be the same as the version of the Maven plugin. If "newest" is defined the plugin will always try to use the newest version of SonargraphBuild. same
skip No Skip SonargraphBuild. false
autoUpdate No If the plugin is configured to download SonargraphBuild automatically, this parameter decides if it also should be updated automatically if a new version becomes available. false
useHttpProxyHost No If true, the proxy configuration of the Gradle settings is used. The plugin will use this proxy for all HTTP communication. Check the Gradle online documentation for details. false
installationDirectory No Installation directory of SonargraphBuild. If unspecified the plugin will automatically download SonargraphBuild. The version to be downloaded can be controlled by the parameter 'sonargraphBuildVersion'. No default
activationCode No Sonargraph license activation code. If this parameter is not specified, you must specify a license file parameter (see below). No default
licenseServerPort No Port of license server to be used. This parameter is ignored if licenseServerHost is not set. 8080
licenseServerHost No Host name or IP address of license server. If this parameter is not specified, the web-based hello2morrow license server will be used for activation code based licenses. No default
licenseFile No Sonargraph license file location. If this parameter is not specified, you must specify the activation code parameter (see above). No default
languages No The languages that should be initialized, separated by ",". The fewer languages are specified the faster the startup of SonargraphBuild. Possible values: Java, CSharp, CPlusPlus. Java
logFile No Path of the log file to be used for SonargraphBuild. ${project.buildDir}/sonargraph_build.log
logLevel No Level of logging detail. One of: off, error, warn, info, debug, trace, all info
systemBaseDirectory No The directory where the Sonargraph System (${artifactId}.sonargraph) is created. ${project.buildDir}
systemId No A system id should stay constant over the lifetime of a software system and should be also unique with respect to other systems. If you anticipate that the the group id or artifact id of the root pom might change you should assign a value to this parameter. ${project.group}_${project.name}
useGroupIdInModuleName No If true the module names will use group id and artifact id as their name, separated by an underscore. By default only the artifact id is used as the module name. false
includeTestCode No If true the workspace will also contain the test source and test class file directories. false
includeEmptyModules No If true the workspace will also contain empty modules (without any source and class file directories). false
productionSourceSets No Comma separated list of source set names that contain production code. This parameter is only needed when you are not using the gradle default "main". main
testSourceSets No Comma separated list of source set names that contain test code. This parameter is only needed when you are not using the gradle default "test". test
virtualModel No The virtual model to be used when checking for issues. This parameter overrides the default virtual model that is set when the system is opened. The default virtual model is "Modifiable.vm", if virtual models are licensed, "Parser" if not licensed. Parameter can only be used with Sonargraph Architect license. No default
qualityModelFile No The path to the quality model file (xyz.sgqm) that should be applied for the report creation. Built-in quality models are the language-independent "Sonargraph:Default.sgqm" and language-specific "Sonargraph:Java.sgqm", "Sonargraph:CSharp.sgqm" and "Sonargraph:CPlusPlus.sgqm". NOTE: All scripts, analyzer configurations and architecture files present in the system are ignored! No default
snapshotDirectory No Target directory for the created snapshot. Only if either this parameter or snapshotFileName is provided, a snapshot will be generated. Parameter can only be used with Sonargraph Architect license. ${project.buildDir}
snapshotFileName No The target file name (without extension). Only if either this parameter or snapshotDirectory is provided, a snapshot will be generated. Parameter can only be used with Sonargraph Architect license. <system-name>_<timestamp>
reportDirectory No Target directory for the created report ${project.buildDir}/sonargraph
reportFileName No The target file name (without extension) <system-name>_<timestamp>
reportType No "standard" only creates metric information of system and module level. "full" creates metric information of all levels. standard
reportFormat No "xml", "html" or "xml, html" html

elementCountToSplit
HtmlReport

No Issue and resolution tables might contain too many items making it impossible to open the HTML report in a browser. This parameter controls the lower limit of items that will cause separate files being generated per issue type. Possible values are: -1 (never split), 0 (use default value), 1 (always split), positive number > 1 (threshold for split) 1000

maxElementCountFor
HtmlDetailsPage

No If HTML report is split because of too many issues and/or resolutions, detail tables might contain too many items making it impossible to open the page in a browser. This parameter controls the upper limit of elements shown in the table. Possible values are: -1 (no limit), 0 (use default limit), positive number > 1 (maximum number of elements contained in page) 2000
splitByModule No If set to 'true', individual HTML reports are created per module. false
baselineReportPath No Path of the baseline XML report that the current report is compared against No default
deltaReportPath No Path of the output file that the delta info is written to. This log file is only generated if a baselineReportPath has been specified. <reportDirectory>/<reportFileName>​_delta.log
prepareForSonarQube No Creates an XML report and stores it at ${basedir}/${target}/sonargraph/sonargraph-sonarqube-report.xml, where the SonarQube Sonargraph plugin expects it. false
Table 7.2. Configuration for Task/Extension "sonargraphDynamicReport"


Related topics:

7.4. Gradle FailSet Configuration

The following elements allow to mark a build as failed. An example is shown in the next section Section 7.5, “Example Gradle Build File”.

TIP

The issue type that must be specified for include/exclude definitions can be determined via the Properties View of Sonargraph .

TIP

If you want the build to fail only for newly introduced issues, apply resolutions like "Ignore" or "Fix" to the already know issues in Sonargraph and only filter for resolution value "none".

TIP

If you want the build to fail because of certain metric values (e.g. Lines of Code per Source File), define a threshold for that metric in Sonargraph to create issues if files grow too large.

TIP

The include/exclude definitions are applied in the following sequence, regardless of their definition order:

  1. First all include definitions are matched against the set of existing issues.

  2. Then the exclude definitions are applied and the set of previously matched issues is reduced accordingly.

Element Parameter Mandatory Description Default
failSet failOnEmptyWorkspace No Marks the build as failed if modules and root directories are detected but no components are found. Possible values are "true" or "false". true
include/exclude issueType Yes Name of the issue type or "any" for wildcard matching. No default
include/exclude severity No Severity of the issue. Possible values are: error, warning, info, none, any any
include/exclude resolution No The issue's resolution type. Possible values are: task, ignore, any, none none
Table 7.3. Configuration Parameters for Build Failure


7.5. Example Gradle Build File

The following example shows how to integrate the SonargraphBuild Gradle plugin into your project. For multi-project builds it is sufficient to only add the plugin to the root project. It runs as an aggregator after all modules have been compiled. The example project in the installation contains a complete build.gradle file. Typically you would run the plugin with a command-line like the following to ensure that everything is compiled from scratch before the report is created:

gradlew clean build sonargraphReport

The following shows the relevant section of a build.gradle file that demonstrates the configuration of the Sonargraph functionality:

apply plugin: 'com.hello2morrow.sonargraph'

task wrapper(type: Wrapper) 
{
    gradleVersion = '2.11'
}

buildscript
{
    repositories
    {
        mavenLocal()
        mavenCentral()
        maven
        {
            url 'http://maven.hello2morrow.com/repository'
        }
        maven
        {
            url 'http://maven.hello2morrow.com/snapshots'
        }
    }
    
    dependencies
    {
        classpath('com.hello2morrow:sonargraph-gradle-plugin:9.4.6') 
    }
}

sonargraphReport
{
    // This is a activation code for Sonargraph-Explorer Build which you can use for testing.
    // Replace with your own if you have one.
    activationCode = "36E2-0F3E-643F-B4F2"
    failSet 
    {
        failOnEmptyWorkspace = true
        include(issueType: "any", severity: "error", resolution: "none")
        include(issueType: "ArchitectureViolation")
        include(issueType: "any", severity: "warning")
        exclude(issueType: "ScriptCompilationError", resolution: "none")
        exclude(issueType: "ThresholdViolation")
    }
}

sonargraphDynamicReport
{
    activationCode = "36E2-0F3E-643F-B4F2"
    qualityModelFile = "Sonargraph:Java.sgqm" //default Java quality model
    failSet 
    {
        failOnEmptyWorkspace = true
        include(issueType: "any", severity: "error", resolution: "none")
        include(issueType: "ArchitectureViolation")
        include(issueType: "any", severity: "warning")
        exclude(issueType: "ScriptCompilationError", resolution: "none")
        exclude(issueType: "ThresholdViolation")
    }
}

In this example the build will fail if the project contains a package cycle or an architecture violation without a resolution. Since the parameter 'installationDirectory' is not defined, the Gradle plugin will automatically download the newest release of SonargraphBuild and also will keep it updated automatically. Of course this requires that the build server has access to the Internet.

NOTE

The boolean parameters must be set without any quotes.

NOTE

Variable substitution in parameters does not work with single quotes, use double quotes instead.