Info |
---|
SQ Official Doc Link: https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+Gradle |
By SonarSource – GNU LGPL 3 – Issue Tracker – Sources SonarQube Scanner for Gradle 2.6.1 – Compatible with SonarQube 5.6+ (LTS) |
Panel | ||||||
---|---|---|---|---|---|---|
| ||||||
Table of Contents
|
기능
SonarQube Scanner for Gradle를 사용하면 손쉽게 Gradle 프로젝트를 분석할 수 있습니다.
일반적인 Gradle task에서 SonarQube 분석을 수행할 수 있기 때문에, gradle을 사용할 수 있는 모든 환경(개발 빌드, CI server 등)에서 별도의 수작업(다운로드, 셋업, SonarQube Scanner 설치 등) 없이 분석이 가능합니다. Gradle 빌드에서 생성되는 정보들로 SonarQube 분석을 수행하기에 충분합니다. 해당 정보들을 기반으로 분석을 위한 설정 작업을 수행하기 때문에, 수작업을 통한 환경 설정이 현저하게 줄어듭니다.
호환성
h1.
Compatibility
The SonarQube Scanner for Gradle version 2.x is compatible with Gradle versions 1Gradle v2.x는 Gradle v1.12+ and 및 SonarQube versions 5v5.6+과 호환됩니다.
Bytecode created by javac
compilation is required for Java analysis, including Android projects.
Java 프로젝트 및 Android 프로젝트를 분석하는 경우, javac로 컴파일 된 바이트코드가 필요합니다.
Warning | ||
---|---|---|
|
| |
unicity를 보장하기 위해 SonarQube Scanner for gradle v2.0에서 모듈 키 생성 정책을 변경하였습니다(SONARGRADL-12 - Avoid duplicate module keys CLOSED |
참조). |
v1.x에서 v2.x로 업그레드하는 경우, 모든 이슈들이 "new"로 다시 식별될 수 있습니다. 다음 워크플로우를 따라 해당 현상을 방지할 수 있습니다:
|
|
|
사전 조건
Prerequisites
- SonarQube is already installed
- At least the minimal version of Java supported by your SonarQube server is in use
- The language plugins for each of the languages you wish to analyze are installed
- You have read Analyzing Code Source.
Configure the Scanner
Installation is automatic, but certain global properties should still be configured. A good place to configure global properties is- SonarQube 서버를 설치합니다.
- SonarQube 서버가 사용할 Java 버전을 하나 이상 설치합니다.
- 분석 언어 플러그인을 설치합니다.
- 소스 코드 분석하기를 숙지합니다.
스캐너 설정
설치는 자동 수행되지만, 몇가지 글로벌 속성은 사용자가 직접 설정해야 합니다. 글로벌 속성은 ~/.gradle/gradle.properties. Be aware that we are using System properties so all properties should be prefixed by systemProp.
properties에서 설정할 수 있습니다. 모든 속성은 System 속성이므로, systemProp prefix를 사용해야 합니다.
Code Block | ||
---|---|---|
| ||
systemProp.sonar.host.url=http://localhost:9000 |
#----- Security (when 'sonar.forceAuthentication' is set to 'true') |
systemProp.sonar.login=<token> |
Analysis
1 - Activate the scanner in your build
For Gradle 2.1+:
build.gradle
plugins { id "org.sonarqube" version "2.6" } |
More details on https://plugins.gradle.org/plugin/org.sonarqube
Assuming a local SonarQube server with out-of-the-box settings is up and running, no further mandatory configuration is required.
2 - Run analysis
Execute gradle sonarqube
and wait until the build has completed, then open the web page indicated at the bottom of the console output. You should now be able to browse the analysis results.
Configure analysis properties
The SonarQube Scanner for Gradle leverages information contained in Gradle's object model to provide smart defaults for many of the standard SonarQube properties. The defaults are summarized in the tables below.
Gradle defaults for standard SonarQube properties
Property | Gradle default |
sonar.projectKey | [
|
sonar.projectName | ${project.name} |
sonar.projectDescription | ${project.description} |
sonar.projectVersion | ${project.version} |
sonar.projectBaseDir | ${project.projectDir} |
sonar.working.directory | ${project.buildDir}/sonar |
java-base
or java
plugin applied:
Additional defaults for Java
projects
Property | Gradle default |
sonar.sourceEncoding | ${project.compileJava.options.encoding} |
sonar.java.source | ${project.sourceCompatibility} |
sonar.java.target | ${project.targetCompatibility} |
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.java.binaries | ${sourceSets.main.output.classesDir} |
sonar.java.libraries | ${sourceSets.main.compileClasspath} (filtering to only include files; rt.jar and jfxrt.jar added if necessary) |
sonar.java.test.binaries | ${sourceSets.test.output.classeDir} |
sonar.java.test.libraries | ${sourceSets.test.compileClasspath} (filtering to only include files; rt.jar and jfxrt.jar added if necessary) |
sonar.junit.reportPaths | ${test.testResultsDir} (if the directory exists) |
Additional defaults for Groovy projects
sonar.groovy.binaries
${sourceSets.main.output.classesDir}
Additional defaults when JaCoCo plugin is applied
sonar.jacoco.reportPaths
${jacoco.destinationFile}
sonar.groovy.jacoco.reportPath
${jacoco.destinationFile}
Additional defaults for Android projects (com.android.application, com.android.library or com.android.test)
build.gradle
sonarqube { androidVariant 'fullDebug' } |
sonar.sources
(for non test variants)
${variant.sourcesets.map}
(ManifestFile/CDirectories/AidlDirectories/AssetsDirectories/CppDirectories/JavaDirectories/RenderscriptDirectories/ResDirectories/ResourcesDirectories)sonar.tests
(for test variants)
${variant.sourcesets.map}
(ManifestFile/CDirectories/AidlDirectories/AssetsDirectories/CppDirectories/JavaDirectories/RenderscriptDirectories/ResDirectories/ResourcesDirectories)sonar.java[.test].binaries
${variant.destinationDir}
sonar.java[.test].libraries
${variant.javaCompile.classpath}
+ ${bootclasspath}
sonar.java.source
${variant.javaCompile.sourceCompatibility}
sonar.java.target
${variant.javaCompile.targetCompatibility}
Passing manual properties / overriding defaults
The SonarQube Scanner for Gradle adds a SonarQubeExtension
extension to project and its subprojects, which allows you to configure/override the analysis properties.
sonarqube { properties { property "sonar.exclusions" , "**/*Generated.java" } } |
Alternatively, SonarQube properties can be set from the command line. See "Configuring properties from the command line" for more information.
Analyzing Multi-Project Builds
To analyze a project hierarchy, apply the SonarQube 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 has to be configured in the sonarqube
block of this project. Any properties set on the command line also apply to this project.
Global configuration settings
build.gradlesonarqube { properties { property "sonar.sourceEncoding" , "UTF-8" } } |
Shared configuration settings
Configuration shared between subprojects can be configured in a subprojects
block.
subprojects { sonarqube { properties { property "sonar.sources" , "src" } } } |
Individual configuration settings
Project-specific information is configured in thesonarqube
block of the corresponding project.build.gradle
project( ":project1" ) { sonarqube { properties { property "sonar.branch" , "Foo" } }} |
Skipping analysis of a project
To skip SonarQube analysis for a particular subproject, set sonarqube.skipProject
to true
.
build.gradle
project( ":project2" ) { sonarqube { skipProject = true } } |
Analyzing Custom Source Sets
By default, the SonarQube Scanner for Gradle 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.
Analyzing custom source sets
build.gradlesonarqube { properties { properties[ "sonar.sources" ] += sourceSets.custom.allSource.srcDirs properties[ "sonar.tests" ] += sourceSets.integTest.allSource.srcDirs } } |
More on configuring SonarQube properties
Let's take a closer look at the sonarqube.properties {}
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.
Setting properties from the Command Line
SonarQube properties can also be set from the command line, by setting a system property named exactly like the SonarQube property in question. This can be useful when dealing with sensitive information (e.g. credentials), environment information, or for ad-hoc configuration.
gradle sonarqube -Dsonar.host.url=http://sonar.mycompany.com -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 SonarQube 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 be taken into account.
Task dependencies
Before executing the sonarqube
task, all tasks producing output to be included in the SonarQube analysis 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 sonarqube
on test
if the java
plugin is applied. Further task dependencies can be added as needed. For example:
project.tasks[ "sonarqube" ].dependsOn "anotherTask" |