How to build sources jar with gradle?
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
}
If you're using Android:
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
task javadoc(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives javadocJar
archives sourcesJar
}
from here
Solution as of Gradle 6.0
Assuming that you use the java
/java-library
plugin with Gradle 6.0 or later, you can get a sourcesJar
task using the following configuration:
java {
withSourcesJar()
// and/or analogously use “withJavadocJar()” to get a “javadocJar” task
}
If you additionally use the maven-publish
/ivy-publish
plugin (recommended nowadays), then this will also publish a *-sources.jar
artifact along with your main Java publication.
See also the Gradle docs.
If you wish to add the sources to the compiled classes JAR file, which you also said would be acceptable, you can do that easily enough. Just add the following to your build file. You can see that, in theory, it is quite like the solution for putting sources into a separate JAR:
jar {
from sourceSets.main.allSource
}
The difference is that you are adding it to the main JAR file by saying "jar" in lieu of sourcesJar.