Build source jar with Gradle Kotlin DSL?

With Gradle 5.3.1, this is a little nicer and avoids deprecated API:

tasks {    
    val sourcesJar by creating(Jar::class) {
        archiveClassifier.set("sources")
        from(sourceSets.main.get().allSource)
    }

    val javadocJar by creating(Jar::class) {
        dependsOn.add(javadoc)
        archiveClassifier.set("javadoc")
        from(javadoc)
    }

    artifacts {
        archives(sourcesJar)
        archives(javadocJar)
        archives(jar)
    }
}

Task assemble will create all the artifacts.


The following will work:

val sourcesJar by creating(Jar::class) {
    dependsOn(JavaPlugin.CLASSES_TASK_NAME)
    classifier = "sources"
    from(sourceSets["main"].allSource)
}

val javadocJar by creating(Jar::class) {
    dependsOn(JavaPlugin.JAVADOC_TASK_NAME)
    classifier = "javadoc"
    from(tasks["javadoc"])
}

artifacts {
    add("archives", sourcesJar)
    add("archives", javadocJar)
}

A complete build.gradle.kts would look like this:

plugins {
    kotlin("jvm") version "1.2.71"
}

repositories {
    mavenCentral()
}

dependencies {
}

tasks {
    val sourcesJar by creating(Jar::class) {
        dependsOn(JavaPlugin.CLASSES_TASK_NAME)
        classifier = "sources"
        from(sourceSets["main"].allSource)
    }

    val javadocJar by creating(Jar::class) {
        dependsOn(JavaPlugin.JAVADOC_TASK_NAME)
        classifier = "javadoc"
        from(tasks["javadoc"])
    }

    artifacts {
        add("archives", sourcesJar)
        add("archives", javadocJar)
    }
}

As of Gradle 6.0 this is a much easier and cleaner. All you need to do is:

java {
    withSourcesJar()
    withJavadocJar()
}

Check out the documentation on the java extension, and its functions, withSourcesJar() and withJavadocJar()