gpt4 book ai didi

groovy - 减少 Groovy 闭包中的代码重复

转载 作者:行者123 更新时间:2023-12-03 03:16:26 25 4
gpt4 key购买 nike

在一段 Gradle 构建脚本中,我重复的代码量正在增加。除了几行之外,所有任务都有很大的共同点:

task copyZipFile() {
doLast {
def remoteBuildProperties = getRemoteBuildProperties(project)
ant {
taskdef(name: 'ftp',
classname: 'org.apache.tools.ant.taskdefs.optional.net.FTP',
classpath: configurations.ftpAntTask.asPath)

ftp(server: remoteBuildProperties['host.name'],
userid: remoteBuildProperties['username'],
password: remoteBuildProperties['password'],
remotedir: 'some-folder', // This value differs from call to call
passive: 'true') {
// The next two lines also are different per case, and might be less or more lines
fileset(dir: rootProject.buildDir) { include(name: 'build.zip') }
fileset(dir: rootProject.projectDir) { include(name: 'build.properties') }
}
}
}
}

我不想重复自己,所以我想将此代码简化为一个新的辅助方法来执行此技巧,以及一个简单的调用者,例如:
task copyZipFile() {
doLast {
def remoteBuildProperties = getRemoteBuildProperties(project)
upload(remoteBuildProperties, 'some-folder') {
fileset(dir: rootProject.buildDir) { include(name: 'build.zip') }
fileset(dir: rootProject.projectDir) { include(name: 'build.properties') }
}
}
}

我将如何实现这一目标?

最佳答案

您可以将内部封闭传递给您的upload方法作为最终参数。将委托(delegate)设置为原始构建器委托(delegate),以便正确处理内部闭包调用。例如:

def upload(remoteBuildProperties, folder, body) {
ant {
taskdef(name: 'ftp',
classname: 'org.apache.tools.ant.taskdefs.optional.net.FTP',
classpath: configurations.ftpAntTask.asPath)

ftp(server: remoteBuildProperties['host.name'],
userid: remoteBuildProperties['username'],
password: remoteBuildProperties['password'],
remotedir: folder,
passive: 'true') {
body.delegate = delegate
body()
}
}
}

关于groovy - 减少 Groovy 闭包中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19795212/

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