第三十六章. Sonar Runner 插件

Chapter 36. The Sonar Runner Plugin

Sonar runner 插件目前是一个试验性插件。注意,在以后的 Gradle 版本中,其 DSL 和其他配置可能会有变化。
The Sonar runner plugin is currently incubating. Please be aware that the DSL and other configuration may change in later Gradle versions.

Sonar Runner 插件提供了对 Sonar——一个基于 web 的代码质量监控平台的集成。它基于 Sonar Runner,一个分析源代码及构建输出,并将所有收集的信息储存在 Sonar 数据库的 Sonar 客户端组件。相比单独使用 Sonar Runner,Sonar Runner 插件具有以下优势:
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:

自动配置 Sonar Runner
Automatic provisioning of Sonar Runner

可以通过一个常规的 Gradle 任务来执行 Sonar Runner,这使得在任何 Gradle 可用的地方,它都可以用(开发人员构建,CI 服务器等),而无需下载,安装,和维护 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.

通过 Gradle 构建脚本动态配置
Dynamic configuration from Gradle build scripts

可以利用 Gradle 的所有脚本特性根据需要去配置 Sonar Runner。
All of Gradle's scripting features can be leveraged to configure Sonar Runner as needed.

广泛的默认配置
Extensive configuration defaults

Gradle 已经拥有很多 Sonar Runner 成功分析一个项目所需的信息。通过基于这些信息对 Sonar Runner 进行预配置,显著降低了对手动配置的需求。
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. 插件状态和兼容性

36.1. Plugin Status and Compatibility

Sonar Runner 插件是 Sonar 插件的继承者。目前它还在试验性的阶段。该插件基于Sonar Runner 2.0,这使其与 Sonar 2.11及更高版本兼容。与 Sonar 插件不同,Sonar Runner 插件可与 Sonar 3.4 及更高版本配合使用。
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. 入门

36.2. Getting Started

首先,将 Sonar Runner 插件应用于要分析的项目。
To get started, apply the Sonar Runner plugin to the project to be analyzed.

示例 36.1. 配置使用 Sonar Runner 插件 - Example 36.1. Applying the Sonar Runner plugin

build.gradle

apply plugin: "sonar-runner"

假设一个具有开箱即用设置的本地 Sonar 服务器已启动并正在运行,则不需要进一步强制性的配置。执行 gradle sonarRunner 并等待构建完成,然后打开 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.

在执行之前 sonarRunner 任务,所有产生输出以用于 Sonar 分析的任务都需要被执行。通常情况下它们是编译任务,测试任务和代码覆盖任务。为了满足这些需求,如果应用了 java的 插件,Sonar Runner 插件将对 sonarRunner 添加一个对 test 任务的依赖。根据需要,可以添加更多的任务依赖。
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. 配置 Sonar Runner

36.3. Configuring the Sonar Runner

Sonar Runner 插件向项目增加了一个 SonarRunner 扩展,它能够通过被称为 Sonar 属性的键/值对配置 Sonar Runner。一个典型的基线配置包括了 Sonar 服务器和数据库的连接设置。
The Sonar Runner plugin adds a SonarRunner extension to the project, which allows 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.

示例 36.2. 配置 Sonar 连接设置 - 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"
    }
}

有关标准 Sonar 属性的完整列表,请参阅 Sonar 文档。如果你碰巧使用其他 Sonar 插件,请查阅它们的文档。
For a complete list of standard Sonar properties, consult the Sonar documentation. If you happen to use additional Sonar plugins, consult their documentation.

作为选择,也可以从命令行设置 Sonar 属性。更多信息请参见《第35.6节,“从命令行配置声纳设置”》。
Alternatively, Sonar properties can be set from the command line. See Section 35.6, “Configuring Sonar Settings from the Command Line” for more information.

Sonar Runner 插件利用 Gradle 对象模型中包含的信息为许多标准 Sonar 属性提供了智能默认值。下表总结了这些默认值。请注意,应用了 java-basejava 插件的项目,有提供另外的默认值。对于某些属性(特别是服务器和数据库连接设置),确定留给 Sonar Runner 合适的默认值。
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.

表 36.1. 标准 Sonar 属性的 Gradle 默认值 - Table 36.1. Gradle defaults for standard Sonar properties

属性
Property
Gradle 默认值
Gradle default
sonar.projectKey "$project.group:$project.name" (用于已分析的层次结构的根项目,否则留给 Sonar Runner 处理)
"$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"

表 36.2. 应用 java-base 插件时另外添加的默认值 - Table 36.2. Additional defaults when java-base plugin is applied

属性
Property
Gradle 默认值
Gradle default
sonar.java.source project.sourceCompatibility
sonar.java.target project.targetCompatibility

表 36.2. 应用 java 插件时另外添加的默认值 - Table 36.3. Additional defaults when java plugin is applied

属性
Property
Gradle 默认值
Gradle default
sonar.sources sourceSets.main.allSource.srcDirs(过滤为只包含存在的目录)
sourceSets.main.allSource.srcDirs (filtered to only include existing directories)
sonar.tests sourceSets.test.allSource.srcDirs(过滤为只包含存在的目录)
sourceSets.test.allSource.srcDirs (filtered to only include existing directories)
sonar.binaries sourceSets.main.runtimeClasspath (过滤为只包含存在的目录)
sourceSets.main.runtimeClasspath (filtered to only include directories)
sonar.libraries sourceSets.main.runtimeClasspath (过滤为仅包括文件 ;如果有必要会加上 rt.jar
sourceSets.main.runtimeClasspath (filtering to only include files; rt.jar added if necessary)
sonar.surefire.reportsPath test.testResultsDir (如果该目录存在)
test.testResultsDir (if the directory exists)
sonar.junit.reportsPath test.testResultsDir (如果该目录存在)
test.testResultsDir (if the directory exists)

36.4. 分析多项目构建

36.4. Analyzing Multi-Project Builds

Sonar Runner能够立即分析整个项目层次结构。这在 Sonar Web 界面中生成了一个层次图,该层次图包含了综合的指标且能够深入到子项目中。分析一个项目的层次结构也比分别分析每个项目花费的时间更少。
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.

要分析项目层次结构,请将 Sonar Runner 插件应用于层次结构的根项目。通常(但不一定)是 Gradle 构建的根项目。有关整个分析的信息,如服务器和数据库连接设置,必须在这个项目的 sonarRunner 块中进行配置。在命令行上设置的任何 Sonar 属性也会应用到该项目中。
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.

示例 36.3. 全局配置设置 - 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"
    }
}

子项目之间的共享配置可以配置在 subprojects 块中。
Configuration shared between subprojects can be configured in a subprojects block.

示例 36.4. 共享的配置设置 - Example 36.4. Shared configuration settings

build.gradle

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

特定项目的信息在对应项目的 sonarRunner 块中配置。
Project-specific information is configured in the sonarRunner block of the corresponding project.

示例 36.5. 个别配置设置 - Example 36.5. Individual configuration settings

build.gradle

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

对于一个特定的子项目,要跳过 Sonar 分析,可以设置sonarRunner.skipProject
The skip Sonar analysis for a particular subproject, set sonarRunner.skipProject.

示例 36.6. 跳过项目分析 - Example 36.6. Skipping analysis of a project

build.gradle

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

36.5. 分析自定义源集

36.5. Analyzing Custom Source Sets

默认情况下,Sonar Runner 插件会把项目的 main 源集当作生产源,把项目的 test 源集当为测试源。这与项目的源目录布局无关。根据需要,可以添加其他的源集。
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.

示例 36.7. 分析自定义的源集 - 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. 分析 Java 以外的语言

36.6. Analyzing languages other than Java

要分析非 Java 语言编写的代码,请安装相应的 Sonar 插件,并相应地设置 sonar.project.language
To analyze code written in a language other than Java, install the corresponding Sonar plugin, and set sonar.project.language accordingly:

示例 36.8. 分析 Java 以外的语言 - Example 36.8. Analyzing languages other than Java

build.gradle

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

从 Sonar 3.4 开始,每个项目只能分析一种语言。但是,你可以在多项目构建中为每个项目分析不同的语言。
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. 有关配置 Sonar 属性的更多信息

36.7. More on configuring Sonar properties

让我们仔细看看 sonarRunner.sonarProperties {} 块。正如我们在例子中已经看到的那样,property() 方法允许设置新属性或覆盖现有的属性。此外,到目前为止配置的所有属性,包括 Gradle 预先配置的所有属性,都可以通过 properties 访问。
Let's take a closer look at the sonarRunner.sonarProperties {} block. As we have already seen in the examples, the property() method allows 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.

properties map 中的条目可以使用常见的 Groovy 语法来读写。为了方便它们的操纵,这些值仍然有它们的“惯用”类型(FileList等)。在 sonarProperties 块评估之后,值将转换为字符串,如下所示:集合的值会(递归地)转换为以逗号分隔的字符串,其他所有的值则通过调用它们 toString() 方法来转换。
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.

因为 sonarProperties 块的评估是惰性的,Gradle 的对象模型的属性可以在块中安全地引用,而无需担心它们还没有被赋值。
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. 从命令行设置 Sonar 属性。

36.8. Setting Sonar Properties from the Command Line

从命令行上,通过设置与所讨论的 Sonar 属性名称完全相同的系统属性,也可以设置 Sonar 属性。这在处理敏感信息(例如凭证),环境信息或 ad-hoc 配置时会非常有用。
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.

通过系统属性设置的 Sonar 属性值将覆盖构建脚本中设置的任何值(对于同一属性)。分析项目层次结构时,通过系统属性设置的值将应用于所分析的层次结构的根项目。
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. 在一个单独的进程中执行 Sonar Runner

36.9. Executing Sonar Runner in a separate process

根据项目大小,Sonar Runner 可能需要大量内存。出于这个和其他(主要是隔离)的原因,希望在单独的过程中执行 Sonar Runner。一旦 Sonar Runner 2.1 发布并且被 Sonar Runner 插件彩,就会提供此功能。在此之前,Sonar Runner 在主 Gradle 进程中执行。有关如何管理该进程的内存设置,请参阅《第 20.1 节,“通过gradle.properties配置构建环境”》。
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. 任务

36.10. Tasks

Sonar Runner 插件向项目中添加了以下任务。
The Sonar Runner plugin adds the following tasks to the project.

表 36.4. Sonnar Runner 插件——任务 - Table 36.4. Sonar Runner plugin - tasks

任务名称
Task name
依赖于
Depends on
类型
Type
描述
Description
sonarRunner - SonarRunner 分析项目层次结构,并将结果存储在 Sonar 数据库。
Analyzes a project hierarchy and stores the results in the Sonar database.