gpt4 book ai didi

inheritance - 如何在gradle任务之间共享代码?

转载 作者:行者123 更新时间:2023-12-03 03:57:21 24 4
gpt4 key购买 nike

所以我有一些gradle任务可以和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}"
}

这是很多不必要的代码重复,我想将其重构为更薄的东西。

我确实尝试过
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}"
}

但这失败了

Execution failed for task ':startGlassfish'.

> execCommand == null!



因此,我显然误会了一些东西。

我该如何工作?

最佳答案

编写自定义任务类时,建议先检查原始任务的代码。执行任务的@TaskAction是exec()方法,可以看到in AbstractExecTask class

您可以使用以下代码;

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}"]
}

关于inheritance - 如何在gradle任务之间共享代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54954344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com