Gradle / Kotlin-覆盖子项目中的额外属性以控制常见项目任务

时间:2020-03-25 14:11:55

标签: gradle gradle-kotlin-dsl

关于此还有很多其他相关问题,但我无法在这里进行任何工作。

我在子项目的子集中使用shadowjar来产生一个远的jar。一个子项目产生两个jar(不同的主类)。我正在尝试消除每个子项目中的样板。

我已经尝试了一些方法,但是使用“额外”似乎是到目前为止我尝试过的最经典的方法。但是,它不起作用。

在根中,我有:

subprojects {

    afterEvaluate {

        val jarFiles by project.extra(listOf<String>())
        val mainClasses by project.extra(listOf<String>())

        if (jarFiles != null && jarFiles.isNotEmpty()) {
            jarFiles.forEachIndexed { idx, jarName ->
                tasks.create<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>(jarName) {
                    isZip64 = true
                    archiveBaseName.set(jarName)
                    mergeServiceFiles()
                    manifest {
                        attributes(mapOf("Main-Class" to mainClasses!![idx]))
                    }
                    minimize()
                }

                tasks.build {
                    dependsOn(jarName)
                }
            }
        }
    }

然后在我尝试过的子项目中:

extra["jarFiles"] = listOf("myproject")
extra["mainClasses"] = listOf("com.foo.Application")

val jarFiles by extra(listOf("internal", "external"))
val mainClasses by extra(listOf("com.fooInternalApplication", "com.foo.ExternalApplication"))

但是,它并没有被解雇。我应该关闭还是应该采用完全不同的方法?

1 个答案:

答案 0 :(得分:0)

工作解决方案:

subprojects { 

    // this is needed so that the subproject can )optionally) set it
    extra["jars"] = null

    afterEvaluate {
        // this may have been set by the subproject
        val jars = extra["jars"] as Map<String, String>?

        jars?.forEach { jar, className ->
            tasks.create<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>(jar) {
                isZip64 = true
                archiveBaseName.set(jar)
                mergeServiceFiles()
                manifest {
                    attributes(mapOf("Main-Class" to className))
                }
                exclude("META-INF/INDEX.LIST", "META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
                minimize()
                configurations = listOf(project.configurations.default.get())
                // TODO see https://github.com/johnrengelman/shadow/blob/master/src/main/groovy/com/github/jengelman/gradle/plugins/shadow/ShadowJavaPlugin.groovy#L38
                // should be able to refer to something along the lines of "conventions"
                from("./build/classes/kotlin/main")
            }

            tasks.build {
                dependsOn(jar)
            }
        }
    }
}

然后,在每个需要构建一个或多个jar的子项目中:

extra["jars"] = mapOf(project.name to "com.foo.MainApplication")

extra["jars"] = mapOf("internal" to "com.foo.InternalApplication",
                      "external" to "com.foo.ExternalApplication")