inheritance - How do you share code between gradle tasks?
问题描述
So I have some gradle tasks to interact with glassfish ...
task startGlassfish(type:Exec){
workingDir "${glassfishHome}${File.separator}bin"
if (System.properties['os.name'].toLowerCase().contains('windows')) {
commandLine 'cmd', '/c', 'asadmin.bat'
} else {
commandLine "./asadmin"
}
args "start-domain", "${glassfishDomain}"
}
task stopGlassfish(type:Exec){
workingDir "${glassfishHome}${File.separator}bin"
if (System.properties['os.name'].toLowerCase().contains('windows')) {
commandLine 'cmd', '/c', 'asadmin.bat'
} else {
commandLine "./asadmin"
}
args "stop-domain", "${glassfishDomain}"
}
task deploy(dependsOn: 'war', type:Exec) {
workingDir "${glassfishHome}${File.separator}bin"
if (System.properties['os.name'].toLowerCase().contains('windows')) {
commandLine 'cmd', '/c', 'asadmin.bat'
} else {
commandLine "./asadmin"
}
args "deploy", "--force=true", "${war.archivePath}"
}
That's a lot of unnecessary code duplication and I'd like to refactor it into something slimmer.
I did try
class GlassfishAsadminTask extends Exec{
@TaskAction
def run() {
workingDir "${glassfishHome}${File.separator}bin"
if (System.properties['os.name'].toLowerCase().contains('windows')) {
commandLine 'cmd', '/c', 'asadmin.bat'
} else {
commandLine "./asadmin"
}
}
}
task startGlassfish(type:GlassfishAsadminTask){
args "start-domain", "${glassfishDomain}"
}
but that fails with
Execution failed for task ':startGlassfish'.
> execCommand == null!
So I'm obviously misunderstanding something.
How do I get this to work?
解决方案
When writing custom task classes I suggest first checking the original task's code. Exec task's @TaskAction is exec() method as can be seen in AbstractExecTask class
You can use the following code;
class GlassfishAsadminTask extends Exec{
// arguments that tasks will pass (defined as array)
@Input
String[] cmdArguments
@TaskAction
public void exec() {
// access properties with project.proppertyName
workingDir "${project.glassfishHome}${File.separator}bin"
if (System.properties['os.name'].toLowerCase().contains('windows')) {
commandLine 'cmd', '/c', 'asadmin.bat'
} else {
commandLine "./asadmin"
}
// set args that is set by the task
args cmdArguments
super.exec()
}
}
// A sample task
task startGlassfish(type: GlassfishAsadminTask) {
cmdArguments = ["start-domain", "${glassfishDomain}"]
}
推荐阅读
- robotframework - 机器人框架:如何多次运行所有测试用例
- android - 如何为默认的 android 小部件充气?
- regex - Atom 中的新语法/语法突出显示
- css - 将 GRID 中最后一行的剩余项目居中 (1fr 1fr)
- ftp - FireZilla:没有可用的受支持的身份验证方法(服务器发送:公钥)
- java - 如何完成我的编码和解码程序?
- huawei-mobile-services - Android 10及以上的后台定位界面是否支持连续获取位置信息?
- python-3.x - pyshark中的decryption_key过滤器
- testing - 如何测试 GitLab CI/CD 管道
- c - Makefile 没有创建目录