【问题标题】:Set the properties in the configuration phase of a task in another task在另一个任务中设置一个任务的配置阶段的属性
【发布时间】:2019-04-09 16:07:18
【问题描述】:

过去几个小时我一直在尝试找到满足我要求的解决方案,但没有运气:

我有一个任务必须在某个路径中运行一些逻辑:

task run(type: MyPlugin) {
    pathForPlugin = myPath //Defined as a property in another gradle file
}

我想在另一个任务中动态设置“pathForPlugin”属性,因为它必须从某个配置文件中读取。

task initPaths(type: PathFinder) {
     configurationFile = 'C:\\myConfig.conf'
}

myConfig.conf 如下所示:

pathForPlugin = 'C:\\Correct\\Path'

问题是“initPaths”必须在“run”的配置阶段之前运行。 我为此尝试了几种方法(GradleBuild 任务、dependsOn、在插件中使用“延迟配置”的属性),但每种方法仅在执行阶段生效,导致“pathForPlugin”始终保持默认值。

有什么方法可以让我意识到这一点,或者我应该在 gradle 构建之外寻找其他解决方案吗?

【问题讨论】:

  • 对不起,没时间像往常一样回复一个例子,但请看here。您需要将路径定义为输出属性。然后在第二个任务中,将其配置为输入。它应该工作。也许我以后会找时间看看。

标签: gradle build properties configuration task


【解决方案1】:

我找到了解决问题的方法:

我没有定义任务“initPaths”,而是直接在构建脚本中使用了 java 类“Pathfinder”:

import mypackage.PathFinder;

new PathFinder(project).run()

您只需确保这部分在使用属性的任务定义之上。

我承认这是一个有点“hacky”的解决方案,但它可以很好地满足我的要求。

【讨论】:

    【解决方案2】:

    你可以这样做:

    ext {
        myPath //use it as a global variable that you can set and get from different gradle tasks and files
    }
    
    task firstTask {
        doLast {
            ext.myPath = "your path"
        }
    }
    
    
    task run(type: MyPlugin) {
       doFirst { //executed on runtime not on task definition
           pathForPlugin = ext.myPath //Defined as a property in another gradle file
       }
    }
    
    //example 2 - create run task dynamic
    task initPath {
        doLast {
            tasks.create(name: "run", type: MyPlugin) {
                 pathForPlugin = ext.myPath
            }
        }
    }
    

    【讨论】:

    • 谢谢,但正如我所描述的,问题是它必须在配置阶段运行,因为“pathForPlugin”是 MyPlugin 的参数。您的示例运行良好,因为一切都在执行阶段运行。
    • 也许你可以在 initPaths 任务的 doLast 方法上创建任务动态。这是一个解决方案吗?
    • 这可能适用于我的示例,是的,谢谢!我选择按照我在回答中描述的方式实现它,因为它背后的真正实现不允许动态创建任务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多