在单个 build.gradle 文件中多次调用相同的任务 [英] Calling the same task multiple times in a single build.gradle file

查看:114
本文介绍了在单个 build.gradle 文件中多次调用相同的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义 Gradle 插件,可以从模板文件生成 Java 文件.我在不同的位置有几个这样的模板文件,我需要编译"所有这些文件来生成我需要的 Java 文件.一旦我有了这些文件,我想将它们打包成一个 .jar.

I have a custom Gradle plugin that will generate Java files from a template file. I have several such template files in different locations, and I need to "compile" all of them to generate the Java files I need. Once I have the files, I want to package them into a .jar.

我认为可以执行此操作的一种方法是从同一个构建文件中多次调用编译模板"任务.我会在编译位置 A 中的模板文件的任务中调用一次,再次从编译位置 B 中的模板文件的任务中调用一次...等,直到我拥有我需要的所有 Java 文件.

One way I thought I could do this was to call the "compile template" task multiple times from within the same build file. I'd call it once in a task that compiles template files in location A, again from a task that compiles template files from location B... etc., until I have all the Java files I need.

像这样:

task compileFromLocationA <<{
    compileTemplate.execute(A)...
}

task compileFromLocationB
    compileTemplate.execute(B)...

...

packageJar(depends: compileFromLocationA, compileFromLocationB, ...)
    ...

但是,您不能以编程方式从另一个任务中调用一个任务.我想我可以将每个 compileFromLocation_ 任务分解成它自己的 build.gradle 文件,但这似乎有点矫枉过正.在这种情况下,最佳做法"是什么?

However, you can't programmatically call a task from within another task. I suppose I could break each compileFromLocation_ task into it's own build.gradle file, but that seems like overkill. What's the "best practice" in a case like this?

推荐答案

此代码似乎可以在 build.gradle 中使用 tasks.register() - 例如执行多个源代码生成步骤 - 在我的情况下,我需要在两个不同的步骤中加载不同的文件对(XML 架构和生成选项):

This code seems to work in build.gradle by using tasks.register() - e.g. to perform multiple source code generating steps - in my case I needed to load different pairs of files (XML schema and generation options) in two different steps:

plugins {
    id 'java'
    id "com.plugin" version "1.0"
}


sourceSets.main.java.srcDirs += file("${buildDir}/genSrc")
sourceSets.test.java.srcDirs += file("${buildDir}/testGenSrc")

tasks.compileJava {
    dependsOn tasks.named("genMessage")
}

genMessage {
    codesFile = "${projectDir}/src/main/resources/file.xml"
}

def testGenModel1 = tasks.register("testGenModel1", com.plugin.TestGenModelTask.class) {
    schema = "${projectDir}/src/test/resources/file.xsd"
    options = "${projectDir}/src/test/resources/file.xml"
}

def testGenModel2 = tasks.register("testGenModel2", com.plugin.TestGenModelTask.class) {
    schema = "${projectDir}/src/test/resources/file2.xsd"
    options = "${projectDir}/src/test/resources/file2.xml"
}

tasks.compileTestJava {
    dependsOn tasks.named("testGenModel1"), tasks.named("testGenModel2")
}

这篇关于在单个 build.gradle 文件中多次调用相同的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆