Skip to content
Advertisement

Building a jar with sources included with Gradle using the Kotlin DSL?

I’ve got a small Kotlin library that I’m building with the Gradle Kotlin DSL, so my build.gradle.kts looks something like this:

plugins {
    id("org.jetbrains.kotlin.jvm") version "1.5.31"

    `java-library`
}

group = "foo.bar.api"
version = "1.0"

repositories {
    mavenCentral()
}

dependencies {
    implementation(platform("org.jetbrains.kotlin:kotlin-bom"))
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

    testImplementation("org.jetbrains.kotlin:kotlin-test")

    testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}

I’d like to be able to build a jar that includes both the compiled code and the sources. I know that I can get a separate sources JAR via:

java {
    withSourcesJar()
}

But I haven’t been able to figure out the right incantation to build a JAR that includes both the sources and the compiled code in a single artifact.

Advertisement

Answer

You should probably tweak the jar task, not the Java Plugin extension (the top-level java clause). Try this:

tasks {
    withType<Jar> {
        from(sourceSets["main"].allSource)
        duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    }
}

I tested it quickly in my project and it seems to work, but due to some quirks I need that duplicatesStrategy. It should probably work without that for you.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement