HeyAlex
HeyAlex

Reputation: 1746

How to exclude Kotlin files from compiling with Gradle

With Java, we are excluding like this:

java {
    srcDir 'src'
    exclude '**/myTests/**'
}

I want to make the same thing with Kotlin files. Didn't find any documentation related to this.

What I've expected and already tried (and of course without any success):

kotlin {
    srcDir 'src'
    exclude '**/myTests/*.kt'
}

Upvotes: 7

Views: 8468

Answers (4)

Rahul
Rahul

Reputation: 5049

java {
    srcDir 'src'
    exclude '**/myTests/*.kt'
}

There isn't any Kotlin related configuration.

Why I am saying this: I have all the Kotlin files into the kotlin directory and Java files into java directory. But while configuring, I have added:

sourceSets {
   main.java.srcDirs += "src/main/kotlin"
}

This means that with src/main/java, add source files from src/main/kotlin also while compiling.

This should solve your issue.

Upvotes: 6

Ben H
Ben H

Reputation: 31

I came across a way to make this work specifically for Android unit tests (but I'm assuming it's adaptable) using a combination of other solutions here:

def filesToExclude = [
    '**/*TestOne*.kt',
    '**/*TestTwo*.kt',
    ...
]
tasks.withType(org.gradle.api.tasks.SourceTask.class).configureEach {
  it.exclude(filesToExclude)
}
android.sourceSets.test.kotlin.exclude(filesToExclude)

In my particular case, the extra wildcards around the test name were needed due to other generation occurring (specifically, Dagger with kapt).

This seems to be a bit hacky way to approach it, but it works by ensuring the test target is excluded from all tasks that it could actually be excluded from (including both build & kapt tasks). The sourceSets exclusion is still necessary for the file not to be picked up for compilation (I think this is the Kotlin Gradle Plugin doing it, but it might also be the Android Gradle Plugin).

Upvotes: 0

rsobies
rsobies

Reputation: 441

If you use a Kotlin Gradle project, try this:

tasks.withType<KotlinCompile> {
exclude("**/packageToExlude/**")}

In my case, a non-Android project.

Upvotes: 4

DA_123
DA_123

Reputation: 385

Android (likely need improvement, seems flaky):

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile.class).configureEach {
    it.exclude('**/TestExcludeKotlinClass.kt')
}

Upvotes: 7

Related Questions