This question asks how to build a SourceJar with Gradle. How can I do the same with the Gradle Kotlin DSL?
The gradle code would be:
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives sourcesJar
archives javadocJar
}
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)
}
}
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.
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()
With Gradle 5.1 you can do something like this
tasks {
val sourcesJar by registering(Jar::class) {
classifier = "sources"
from(sourceSets.main.get().allSource)
dependsOn(classes)
}
val javadocJar by registering(Jar::class) {
classifier = "javadoc"
from(javadoc.get().destinationDir)
dependsOn(javadoc)
}
}