Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: SonarSource/sonar-scanner-gradle
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 2.7.1
Choose a base ref
...
head repository: SonarSource/sonar-scanner-gradle
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: 2.8
Choose a head ref
  • 10 commits
  • 5 files changed
  • 4 contributors

Commits on May 10, 2019

  1. Verified

    This commit was signed with the committer’s verified signature. The key has expired.
    xen0n WÁNG Xuěruì
    Copy the full SHA
    378a826 View commit details

Commits on Jun 12, 2019

  1. DOC init docs file

    ganncamp authored Jun 12, 2019

    Verified

    This commit was signed with the committer’s verified signature. The key has expired.
    xen0n WÁNG Xuěruì
    Copy the full SHA
    3c183c1 View commit details

Commits on Jun 13, 2019

  1. DOC init docs file

    ganncamp authored Jun 13, 2019

    Verified

    This commit was signed with the committer’s verified signature. The key has expired.
    xen0n WÁNG Xuěruì
    Copy the full SHA
    38c0fc0 View commit details

Commits on Jun 25, 2019

  1. Build with Java 11

    dbmeneses committed Jun 25, 2019

    Verified

    This commit was signed with the committer’s verified signature. The key has expired.
    xen0n WÁNG Xuěruì
    Copy the full SHA
    9d1c181 View commit details

Commits on Jun 26, 2019

  1. Build with openjdk11

    dbmeneses committed Jun 26, 2019

    Verified

    This commit was signed with the committer’s verified signature. The key has expired.
    xen0n WÁNG Xuěruì
    Copy the full SHA
    0613b99 View commit details

Commits on Jun 28, 2019

  1. Verified

    This commit was signed with the committer’s verified signature. The key has expired.
    xen0n WÁNG Xuěruì
    Copy the full SHA
    b078541 View commit details
  2. Build with openjdk8

    dbmeneses committed Jun 28, 2019

    Verified

    This commit was signed with the committer’s verified signature. The key has expired.
    xen0n WÁNG Xuěruì
    Copy the full SHA
    34903b5 View commit details

Commits on Sep 27, 2019

  1. Fix repositories URLs (#63)

    * Fix repository URLs
    * Remove repositories already mirrored by repox.jfrog
    jacek-poreda-sonarsource authored Sep 27, 2019

    Verified

    This commit was signed with the committer’s verified signature. The key has expired.
    xen0n WÁNG Xuěruì
    Copy the full SHA
    793a4f2 View commit details
  2. SONARGRADL-66 Make SONAR_HOST_URL environment variable known Gradle S… (

    #62)
    
    * Make SONAR_HOST_URL environment variable known Gradle Scanner
    dbmeneses authored and jacek-poreda-sonarsource committed Sep 27, 2019
    Copy the full SHA
    4d44809 View commit details

Commits on Oct 1, 2019

  1. Copy the full SHA
    6d0240d View commit details
Showing with 239 additions and 13 deletions.
  1. +1 −7 .travis.yml
  2. +18 −5 build.gradle
  3. +1 −1 gradle.properties
  4. +11 −0 integrationTests/src/test/java/org/sonarqube/gradle/GradleTest.java
  5. +208 −0 sonar-docs/analysis/scan/sonarscanner-for-gradle.md
8 changes: 1 addition & 7 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@ script:
- ./travis.sh

jdk:
- oraclejdk8
- openjdk8

before_cache:
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
@@ -24,9 +24,3 @@ notifications:
- secure: "cqHeh2xCY4DbE1Z28NiC/TreEEKoirtWxRbWu6SVtip4VAymL6CX1ys6hxQZ3/zKrA9ciZsiAgIW8YZdo1ycB7ImuqhaIFWfGr95YbxCGsPeKx/7FbZyc+6d729USyvVWzuzTvRZuGwE24ZR3pK5cjuX8fsdWt61iL/n3ciK1oE8PS64pVYPpCJlIGOtwBfe+q1f0Tkf8kGmVzzDtFz+s833UIiDSlJuKO4+Tc2DoteaIEXam9bpGzZKUcL6n5MX8oWQvHQkundqld9xTs47ZojJOdJXg672g16IusP2pd3Dzqpao2l6f/pFpoHk9dKzJDdz6bUKOoeHJWoZFRv8oTvym9GCyRcioTJmH4dAymz56zLKoBvzmfhRjOZNCrUs2pZWWmVUY5kUp2IFTt/CAzyCanpPNYIJp5jS1nrcVQ4SitMyR9a7LP4nQw+MlU252nZP/PnyWfXLjOT+nnxTN17gaUdPcQ9hPVHkgafienL4uwkFGFuy76Px3TuGg0KniqDX4i+sLN1ty8pdwxkjL7dxeEQ/vZ+PhhulkJqSCpzkVwJ0993MAaW2A31Xa8Ht6pkBZ6kr0VfyXoMcOkWNHigsbQ413LJYCVo/UEgpEiZ4odZ0u0NZiBJLymNV63gQW2sH1xOibwt8K1x5dnsk0Rk/Ko2UdPoUjV9BxiyD29E="
on_start: always

addons:
apt:
packages:
# upgrade java 8 as the default version 1.8.0_31 prevents from compiling sources
# https://github.com/travis-ci/travis-ci/issues/4042
- oracle-java8-installer
23 changes: 18 additions & 5 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -45,21 +45,34 @@ if (version.endsWith('-SNAPSHOT') && ext.buildNumber != null) {
version = version.replace('-SNAPSHOT', versionSuffix)
}

ext {
release = project.hasProperty('release') && project.getProperty('release')
official = project.hasProperty('official') && project.getProperty('official')
}

repositories {
jcenter()
mavenLocal()
mavenCentral()
maven {
url "https://maven.google.com"
}
def repository = project.hasProperty('qa') ? 'sonarsource-qa' : 'sonarsource'
maven {
url "https://repox.sonarsource.com/sonarsource"
url "https://repox.jfrog.io/repox/${repository}"
// The environment variables ARTIFACTORY_PRIVATE_USERNAME and ARTIFACTORY_PRIVATE_PASSWORD are used on QA env (Jenkins)
// On local box, please add artifactoryUsername and artifactoryPassword to ~/.gradle/gradle.properties
def artifactoryUsername = System.env.'ARTIFACTORY_PRIVATE_USERNAME' ?: (project.hasProperty('artifactoryUsername') ? project.getProperty('artifactoryUsername') : '')
def artifactoryPassword = System.env.'ARTIFACTORY_PRIVATE_PASSWORD' ?: (project.hasProperty('artifactoryPassword') ? project.getProperty('artifactoryPassword') : '')
if (artifactoryUsername && artifactoryPassword) {
credentials {
username artifactoryUsername
password artifactoryPassword
}
}
}
}

dependencies {
compile gradleApi()
compile 'org.sonarsource.scanner.api:sonar-scanner-api:2.12.0.1661'
compile 'org.sonarsource.scanner.api:sonar-scanner-api:2.14.0.2002'
compileOnly 'com.android.tools.build:gradle:3.1.0'
compileOnly 'com.google.code.findbugs:jsr305:3.0.2'
testCompile localGroovy()
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
version=2.7.1
version=2.8
org.gradle.jvmargs=-XX:MaxPermSize=256M
Original file line number Diff line number Diff line change
@@ -72,6 +72,17 @@ public void testSkip() throws Exception {
assertThat(result.getLog()).contains("SonarQube Scanner analysis skipped");
}

@Test
public void testHostUrlInEnv() throws Exception {
Map<String, String> env = new HashMap<>();
env.put("SONAR_HOST_URL", "http://host-in-env");
RunResult result = runGradlewSonarQubeWithEnvQuietly("/java-gradle-simple", env);

System.out.println(result.getLog());
assertThat(result.getExitValue()).isEqualTo(1);
assertThat(result.getLog()).contains("java.net.UnknownHostException: host-in-env");
}

@Test
public void testCompileOnly() throws Exception {
Properties props = runGradlewSonarQubeSimulationMode("/java-compile-only");
208 changes: 208 additions & 0 deletions sonar-docs/analysis/scan/sonarscanner-for-gradle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
---
title: SonarScanner for Gradle
url: /analysis/scan/sonarscanner-for-gradle/
---

[[info]]
| By [SonarSource](https://www.sonarsource.com/) – GNU LGPL 3 – [Issue Tracker](https://jira.sonarsource.com/browse/SONARGRADL)[Source](https://github.com/SonarSource/sonar-scanner-gradle)
| Current version: **SonarQube Scanner for Gradle 2.7.1**



The SonarScanner for Gradle provides an easy way to start SonarQube analysis of a Gradle project.

The ability to execute the SonarQube analysis via a regular Gradle task makes it available anywhere Gradle is available (developer build, CI server, etc.), without the need to manually download, setup, and maintain a SonarQube Runner installation. The Gradle build already has much of the information needed for SonarQube to successfully analyze a project. By preconfiguring the analysis based on that information, the need for manual configuration is reduced significantly.

## Prerequisites
* Gradle versions 2.14+
* At least the minimal version of Java supported by your SonarQube server is in use

Bytecode created by javac compilation is required for Java analysis, including Android projects.

## Configure the Scanner
Installation is automatic, but certain global properties should still be configured. A good place to configure global properties is `~/.gradle/gradle.properties`. Be aware that the scanner uses system properties so all properties should be prefixed by `systemProp`.

```
# gradle.properties
systemProp.sonar.host.url=http://localhost:9000
#----- Token generated from an account with 'publish analysis' permission
systemProp.sonar.login=<token>
```

## Analyzing
First, activate the scanner in your build. For Gradle 2.1+, in `build.gradle`:
```
plugins {
id "org.sonarqube" version "2.7"
}
```
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 configuration is required.

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.

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

```
// build.gradle
sonarqube {
properties {
property "sonar.sourceEncoding", "UTF-8"
}
}
```

Configuration shared between subprojects can be configured in a subprojects block.
```
// build.gradle
subprojects {
sonarqube {
properties {
property "sonar.sources", "src"
}
}
}
```

Project-specific information is configured in the `sonarqube` block of the corresponding project.
```
// build.gradle
project(":project1") {
sonarqube {
properties {
property "sonar.branch", "Foo"
}
}}
```

To skip SonarQube analysis for a particular subproject, set sonarqube.skipProject to true.
```
// build.gradle
project(":project2") {
sonarqube {
skipProject = true
}
}
```

## Task dependencies
All tasks that produce output that should be included in the SonarQube analysis need to be executed before the `sonarqube` task runs. 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:
```
// build.gradle
project.tasks["sonarqube"].dependsOn "anotherTask"
```

## Sample project

A simple working example is available at this URL so you can check everything is correctly configured in your env:
https://github.com/SonarSource/sonar-scanning-examples/tree/master/sonarqube-scanner-gradle


## Analysis property defaults
The SonarScanner for Gradle uses information contained in Gradle's object model to provide smart defaults for most of the standard [analysis parameters](/analysis/analysis-parameters/), as listed below.

Gradle defaults for standard SonarQube properties:

Property|Gradle default
---|---
`sonar.projectKey`|`[${project.group}:]${project.name}` for root module; `<root module key>:<module path>` for submodules
`sonar.projectName`|`${project.name}`
`sonar.projectDescription`|`${project.description}`
`sonar.projectVersion`|`${project.version}`
`sonar.projectBaseDir`|`${project.projectDir}`
`sonar.working.directory`|`${project.buildDir}/sonar`

Notice that additional defaults are provided for projects that have the java-base or java plugin applied:

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)

Groovy projects get all the Java defaults, plus:

Property|Gradle default
---|---
`sonar.groovy.binaries`|`${sourceSets.main.output.classesDir}`


Additional defaults when JaCoCo plugin is applied

Property|Gradle default
---|---
`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`)
By default the first variant of type "debug" will be used to configure the analysis. You can override the name of the variant to be used using the parameter 'androidVariant':

```
build.gradle
sonarqube {
androidVariant 'fullDebug'
}
```

Property| Gradle default
---|---
`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 SonarScanner for Gradle adds a SonarQubeExtension extension to project and its subprojects, which allows you to configure/override the analysis properties.
```
// in build.gradle
sonarqube {
properties {
property "sonar.exclusions", "**/*Generated.java"
}
}
```
SonarQube properties can also be set from the command line, or 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 recommend keeping 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.



### Analyzing Custom Source Sets
By default, the SonarScanner 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.

```
// build.gradle
sonarqube {
properties {
properties["sonar.sources"] += sourceSets.custom.allSource.srcDirs
properties["sonar.tests"] += sourceSets.integTest.allSource.srcDirs
}
}
```

## Advanced topics
### 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()` methods.

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.