Gradle dependency on source set - gradle

I have a project with 3 source sets. One common, and two dependent on it.
sourceSets {
common {}
api {
compileClasspath += common.output
runtimeClasspath += common.output
}
main {
compileClasspath += common.output
runtimeClasspath += common.output
}
}
Also i have some dependencies.
dependencies {
...
commonCompile 'com.google.guava:guava:18.0'
commonCompile 'io.netty:netty-all:4.0.23.Final'
...
compile 'io.dropwizard.metrics:metrics-core:3.1.0'
compile 'io.dropwizard.metrics:metrics-healthchecks:3.1.0'
...
}
Also i have a different project and want to add dependency on api source set from first project.
How can i do such thing?
Thanks.

Related

Include multiple sourcesets in the Jacoco's jacocoTestReport.xml file

I have a custom sourceSet defined in a Gradle based project, like this:
sourceSets {
componentTest {
java {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
srcDir file('src/componentTest/java')
}
}
}
configurations {
componentTestImplementation.extendsFrom testImplementation
}
task componentTest(type: Test) {
dependsOn assemble
testClassesDirs = sourceSets.componentTest.output.classesDirs
classpath = sourceSets.componentTest.runtimeClasspath
outputs.upToDateWhen { false }
testLogging.showStandardStreams = true
mustRunAfter(test)
}
check.dependsOn(componentTest)
The sourceSet contains Cucumber features.
When running Jacoco, the generated jacocoTestReport.xml file doesn't seem to include the coverage generated by the Cucumber tests.
Here is the Jacoco configuration:
jacocoTestReport {
executionData(
file("${project.buildDir}/jacoco/test.exec"),
file("${project.buildDir}/jacoco/componentTest.exec"),
)
}
Is there anything I could do to get the same coverage in the xml file as I get in the exec files?
After further experiments it turns out the xml file includes the coverage from the componentTest sourceSet.
I asked this question because the coverage was not reflected correctly in SonarQube - I could not see the Cucumber tests from the componentTest in SonarQube. But it seems to me now, that the actual coverage values align with what the Jacoco report shows. I just had to exclude the same source classes in SonarQube as in Jacoco.

Spring cloud contracts plugin change sourceset

I've started using Spring Cloud Contracts ('2.0.2.RELEASE') in my project and I have the following structure
src
|
-- main
-- test
-- integrationTest
-- contractTest
When I put my contracts and my base test class in test it was running fine. I want to move the contract tests that I have written into a separate sourceset, the contractTest sources. However, this will not work as the plugin generateContractTests task will still look in the test sourceset when trying to run.
I have made the following changes to my Gradle file
task contractTest(type: Test) {
description = 'Runs contract tests.'
group = 'verification'
testClassesDirs = sourceSets.contractTest.output.classesDirs
classpath = sourceSets.contractTest.runtimeClasspath
shouldRunAfter integrationTest
}
configurations {
contractTestImplementation.extendsFrom implementation
contractTestRuntimeOnly.extendsFrom runtimeOnly
}
sourceSets {
contractTest {
compileClasspath += sourceSets.main.output
runtimeClasspath += sourceSets.main.output
}
}
contracts {
// testFramework = 'JUNIT5'
packageWithBaseClasses = 'com.test.testapi.contracts'
contractsDslDir = new File("${project.rootDir}/src/contractTest/resources/contracts/")
}
contractTestImplementation 'org.codehaus.groovy:groovy-all:2.4.6'
contractTestImplementation 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
contractTestImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api'
contractTestImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-engine'
I think I need to set the contract plugin property contractDependency, however, I am not sure and can't find an example to get the plugin to work with this different sourceset
TLDR; I want to be able to run my contract tests in a different folder
UPDATE - I am not sure but I think that it is not possible as in the Gradle plugin in the "GenerateServerTestsTask.groovy" file has the following which would appear to signify that the sourceSet is hardcoded to test throughout the code
project.sourceSets.test.groovy {
project.logger.
info("Registering ${getConfigProperties().generatedTestSourcesDir} as test source directory")
srcDir getConfigProperties().getGeneratedTestSourcesDir()
}
For future reference, I was able to get it working by creating a custom task to deregister the generated sources from the test sourceset so that they wouldn't be compiled by compileTestJava and could be run via my own contractTests task.
sourceSets {
contractTest {
java {
compileClasspath += sourceSets.main.output + sourceSets.test.output
runtimeClasspath += sourceSets.main.output + sourceSets.test.output
srcDir file('src/contractTest/java')
srcDirs += file("${buildDir}/generated-contract-sources/")
}
resources.srcDir file('src/contractTest/resources')
}
}
task deregisterContractTestSources() {
doLast {
project.sourceSets.test.java {
project.logger.info('Removing any *Spec classes from the test sources')
exclude '**/*Spec*'
}
}
}
compileTestJava.dependsOn deregisterContractTestSources
task contractTests(type: Test) {
description = 'Runs contract tests'
group = 'verification'
testClassesDirs = sourceSets.contractTest.output.classesDirs
classpath = sourceSets.contractTest.runtimeClasspath
}
contracts {
baseClassForTests = 'com'
generatedTestSourcesDir = file("${buildDir}/generated-contract-sources")
generatedTestResourcesDir = file("${buildDir}/generated-contract-resources/")
testFramework = "JUNIT5"
contractsDslDir = new File("${projectDir}/src/contractTest/resources/contracts/")
nameSuffixForTests = 'Spec'
basePackageForTests = 'com'
}

Kotlin Add Integration Tests Module

I am trying to add another module to my Kotlin project specifically for integration tests - living alongside the standard test module creating by the kotlin plugin. Here is my current configuration to add the sourceset:
sourceSets {
testIntegration {
java.srcDir 'src/testIntegration/java'
kotlin.srcDir 'src/testIntegration/kotlin'
resources.srcDir 'src/testIntegration/resources'
compileClasspath += main.output
runtimeClasspath += main.output
}
}
configurations {
provided
testCompile.extendsFrom provided
testIntegrationCompile.extendsFrom testCompile
testIntegrationRuntime.extendsFrom testRuntime
}
task testIntegration(type: Test) {
testClassesDirs = sourceSets.testIntegration.output.classesDirs
classpath = sourceSets.testIntegration.runtimeClasspath
}
This seems to work, however IntelliJ does not pick up the new source set as a test module. I can manually mark it, but it resets every time Gradle runs. This also means that Intellij fills in the Output Path and not the Test Output Path fields in the project structure settings.
To fix that the below configuration works:
apply plugin: 'idea'
idea {
module {
testSourceDirs += project.sourceSets.testIntegration.java.srcDirs
testSourceDirs += project.sourceSets.testIntegration.kotlin.srcDirs
testSourceDirs += project.sourceSets.testIntegration.resources.srcDirs
}
}
However, this seems to instruct IntelliJ that the Test Output Path is \out\test\classes which is the same as the standard 'test' module and causes conflict issues. I want it to keep the output path as the original \out\testIntegration\classes which would have otherwise been used.
Is there any way to instruct IntelliJ to pick up this new test source set correctly and fill in the right output path?
If you'd like to configure the idea gradle plugin with your custom test sourceSets in a kotlin gradle build script you can do it like that:
val testIntegrationSrcDirName = "testIntegration"
sourceSets {
...
create(testIntegrationSrcDirName) {
compileClasspath += sourceSets.main.get().output + sourceSets.test.get().output // take also unit test source and resources
runtimeClasspath += sourceSets.main.get().output + sourceSets.test.get().output // take also unit test source and resources
}
}
...
idea {
module {
testSourceDirs = testSourceDirs + sourceSets[testIntegrationSrcDirName].allSource.srcDirs
}
}
val testIntegrationImplementation: Configuration by configurations.getting {
extendsFrom(configurations.implementation.get())
}
configurations["${testIntegrationSrcDirName}RuntimeOnly"].extendsFrom(configurations.runtimeOnly.get())
...

How to build Google protocol buffers and Kotlin using Gradle?

I'm trying to build a project that uses both Google protocol buffers and Kotlin using Gradle. I want the proto files to compile into Java source, which is then called from my Kotlin code.
My source files are arranged like this:
src/main/proto/*.proto
src/main/kotlin/*.kt
src/test/kotlin/*.kt
Here's my build.gradle file:
version '1.0-SNAPSHOT'
apply plugin: 'kotlin'
apply plugin: 'java'
apply plugin: 'com.google.protobuf'
repositories {
mavenCentral()
maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.1" }
}
buildscript {
ext.kotlin_version = '1.1-M02'
repositories {
mavenCentral()
maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.1" }
}
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.0.0'
}
}
dependencies {
compile 'com.google.protobuf:protobuf-java:3.0.0'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testCompile 'junit:junit:4.12'
}
When I run ./gradlew assemble I get a bunch of "Unresolved reference" errors during :compileKotlin. Afterwards I can see that there are no Java source files generated, so it appears that the proto compiler is not being invoked at all.
If I remove the apply plugin: 'kotlin' line, then ./gradlew assemble successfully generates the Java source, but of course my Kotlin source is never compiled.
How do I fix my build.gradle so that I can call my protobuf code from Kotlin?
To get protobuf-gradle-plugin and kotlin-gradle-plugin to cooperate, you need to ensure that the Java code is (re)generated before invoking the Kotlin compiler.
For Gradle's default source sets, main and test, you can do that like this:
compileKotlin.dependsOn ':generateProto'
compileTestKotlin.dependsOn ':generateTestProto'
If you are using other source sets, you'll need to make adjustments.
Older versions of protobuf-gradle-plugin also required updating sourceSets, but newer versions do not seem to require this.
// Don't do this with protobuf-gradle-plugin 0.9.0 or higher
sourceSets.main.java.srcDirs += "${protobuf.generatedFilesBaseDir}/main/java"
sourceSets.test.java.srcDirs += "${protobuf.generatedFilesBaseDir}/test/java"
For Kotlin and Android:
android {
sourceSets {
debug.java.srcDirs += 'build/generated/source/proto/debug/java'
release.java.srcDirs += 'build/generated/source/proto/release/java'
}
}
An additional source directory has to be added for every build type. In this sample there are two build types: debug and release.
If you're using grpc, another line has to be added per build type:
android {
sourceSets {
debug.java.srcDirs += 'build/generated/source/proto/debug/java'
debug.java.srcDirs += 'build/generated/source/proto/debug/grpc'
release.java.srcDirs += 'build/generated/source/proto/release/java'
release.java.srcDirs += 'build/generated/source/proto/release/grpc'
}
}
At least with Kotlin 1.0.6, protobuf-gradle-plugin 0.8.0, protobuf 3.2.x and grpc 1.x it's not required to fiddle with the task order.
if you are working with multiple build types and flavors in android and with protobuf-lite use below with kotlin.
for example I have debug and release builds with demo and prod flavors it will create demoDebug, demoRelease and prodDebug and prodRelease variants.
then use
`
android{
sourceSets {
debug.java.srcDirs += 'build/generated/source/proto/demoDebug/javalite'
debug.java.srcDirs += 'build/generated/source/proto/prodDebug/javalite'
release.java.srcDirs += 'build/generated/source/proto/demoRelease/javalite'
release.java.srcDirs += 'build/generated/source/proto/prodRelease/javalite'
}
}
`
tie the different compileKotlin with generateProto
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
if (getName() == 'compileDemoDebugKotlin')
dependsOn(':app:generateDemoDebugProto')
if (getName() == 'compileDemoReleaseKotlin')
dependsOn(':app:generateDemoReleaseProto')
if (getName() == 'compileProdDebugKotlin')
dependsOn(':app:generateProdDebugProto')
if (getName() == 'compileProdReleaseKotlin')
dependsOn(':app:generateProdReleaseProto')
}
For the gradle setup :
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'com.google.protobuf' version "0.8.17"
}
Then at the bottom of the build.gradle
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.10.0"
}
// Generates the java Protobuf-lite code for the Protobufs in this project. See
// https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
// for more information.
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option 'lite'
}
}
}
}
}

Gradle sourceSet depends on another sourceSet

This Question is similar to Make one source set dependent on another
Besides the main SourceSet I also have a testenv SourceSet.
The code in the testenv SourceSet references the main code, therefor I need to add the main SourceSet to the testenvCompile configuration.
sourceSets {
testenv
}
dependencies {
testenvCompile sourceSets.main
}
This does not work, because you cannot directly add sourceSets as dependencies. The recommended way to do this is:
sourceSets {
testenv
}
dependencies {
testenvCompile sourceSets.main.output
}
But this does not work correctly with eclipse, because when I clean the gradle build folder, eclipse can't compile anymore, since it depends on the gradle build.
Also if I change main code I'd have to rebuild the project in gradle for the changes to take effect in eclipse.
How do I declare the dependencies correctly?
EDIT:
This
sourceSets {
testenv
}
dependencies {
testenvCompile files(sourceSets.testenv.java.srcDirs, sourceSets.testenv.resources.srcDirs)
}
works for the main source, but because I now reference the .java files I am missing generated classes from the Annotation-Processor :(
So after all this is the way to go:
sourceSets {
testenv
}
dependencies {
testenvCompile sourceSets.main.output
}
To make it work correctly with eclipse you have to manually exclude all sourceSet outputs from the eclipse classpath.
This is ugly, but it works for me:
Project proj = project
eclipse {
classpath {
file {
whenMerged { cp ->
project.logger.lifecycle "[eclipse] Excluding sourceSet outputs from eclipse dependencies for project '${project.path}'"
cp.entries.grep { it.kind == 'lib' }.each { entry ->
rootProject.allprojects { Project project ->
String buildDirPath = project.buildDir.path.replace('\\', '/') + '/'
String entryPath = entry.path
if (entryPath.startsWith(buildDirPath)) {
cp.entries.remove entry
if (project != proj) {
boolean projectContainsProjectDep = false
for (Configuration cfg : proj.configurations) {
boolean cfgContainsProjectDependency = cfg.allDependencies.withType(ProjectDependency).collect { it.dependencyProject }.contains(project)
if(cfgContainsProjectDependency) {
projectContainsProjectDep = true
break;
}
}
if (!projectContainsProjectDep) {
throw new GradleException("The project '${proj.path}' has a dependency to the outputs of project '${project.path}', but not to the project itself. This is not allowed because it will cause compilation in eclipse to behave differently than in gradle.")
}
}
}
}
}
}
}
}
}

Resources