Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build source jar with Gradle Kotlin DSL?

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
}
like image 728
Morgoth Avatar asked Oct 01 '18 18:10

Morgoth


3 Answers

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.

like image 56
Raphael Avatar answered Sep 21 '22 11:09

Raphael


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()

like image 44
Tom Hanley Avatar answered Sep 20 '22 11:09

Tom Hanley


All described methods fail with error on Gradle 6.6:
SourceSet with name 'main' not found

I've found a solution that works:

tasks {
    val sourcesJar by creating(Jar::class) {
        archiveClassifier.set("sources")
        from(android.sourceSets.getByName("main").java.srcDirs)
    }

    artifacts {
        archives(sourcesJar)
    }
}
like image 29
Oleksandr Albul Avatar answered Sep 21 '22 11:09

Oleksandr Albul