用Gradle Kotlin DSL构建源jar?

时间:2018-10-01 18:36:14

标签: gradle kotlin gradle-kotlin-dsl

This question询问如何使用Gradle构建SourceJar。如何使用Gradle Kotlin DSL进行相同操作?

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
}

5 个答案:

答案 0 :(得分:8)

Gradle 6.0 起,此操作更加轻松,简洁。您所需要做的就是:

java {
    withSourcesJar()
    withJavadocJar()
}

查看java extension上的文档及其功能withSourcesJar()withJavadocJar()

答案 1 :(得分:4)

以下将起作用:

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

完整的build.gradle.kts如下所示:

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

答案 2 :(得分:1)

使用Gradle 5.3.1会更好一些,并避免使用不推荐使用的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)
    }
}

任务assemble将创建所有工件。

答案 3 :(得分:0)

所有描述的方法均在 6.6级上失败并显示错误:
SourceSet with name 'main' not found

我找到了一种可行的解决方案:

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

    artifacts {
        archives(sourcesJar)
    }
}

答案 4 :(得分:-1)

使用Gradle 5.1,您可以执行以下操作

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