如何为新任务类型扩展Gradle任务的行为? [英] How to extend the behavior of a Gradle task for a new task type?

查看:252
本文介绍了如何为新任务类型扩展Gradle任务的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一些测试任务做一些设置.更具体地说,我想添加一些环境变量和一些系统属性,也许还有其他一些东西,例如"dependencies"或"workingDir".通过常规的Test任务,我可以做到

I would like to set a few things for a few test tasks. More specifically, I would like to add a few environment variables and a few system properties, maybe a few other things such as "dependencies" or "workingDir". With the regular Test task I can do this,

task test1(type:Test, dependsOn:[testPrep,testPrep1]){
     workingDir testWorkingPath
     systemProperty 'property','abs'
     environment.find { it.key ==~ /(?i)PATH/ }.value += (System.properties['path.separator'] + myLibPath)
     environment.LD_LIBRARY_PATH = "/usr/lib64:/lib64:${myLibPath}:" + environment.LD_LIBRARY_PATH
 }

task test2(type:Test, dependsOn:[testPrep]){
     workingDir testWorkingPath
     systemProperty 'property','abs'
     environment.find { it.key ==~ /(?i)PATH/ }.value += (System.properties['path.separator'] + myLibPath)
     environment.LD_LIBRARY_PATH = "/usr/lib64:/lib64:${myLibPath}:" + environment.LD_LIBRARY_PATH
     systemPropety 'newProperty','fdsjfkd'
 }

最好有一个新的任务类型MyTestType扩展常规的Test任务类型,并在其中定义公共定义.

It would be nice to have a new task type MyTestType extending the regular Test task type, where the common definition is defined.

task test1(type:MyTestType){
     dependsOn testPrep1
 }

task test2(type:MyTestType){
     systemPropety 'newProperty','fdsjfkd'
 } 

什么是最好的方法?看来execute()方法是最终的,无法扩展.我将需要执行类似doFirst的操作来设置这些属性.我应该在构造函数中添加所有额外的值吗?我还有其他钩子可以使用吗?谢谢.

What would be best way to do this? It seems that the execute() method is final and cannot be extended. I will need to do something like the doFirst to set those properties. Should I add all the extra values in the constructor? Is there any other hook I can use? Thanks.

推荐答案

通常,您可以扩展测试"任务并实现自定义

In general you can extend the 'Test' task and implement your customizations

task test1(type:MyTestType){
}

task test2(type:MyTestType){
     systemProperty 'newProperty','fdsjfkd'
}

class MyTestType extends Test {
    public MyTestType(){
        systemProperty 'property','abs'
    }
}

或者,您可以使用更少的样板配置所有类型为Test的任务:

Alternatively you can configure all tasks of type Test with less boilerplate:

// will apply to all tasks of type test. 
// regardless the task was created before this snippet or after
tasks.withType(Test) {
   systemProperty 'newProperty','fdsjfkd'   
}

这篇关于如何为新任务类型扩展Gradle任务的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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