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

标签 groovy closures gradle antbuilder

在一段 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/

相关文章:

与 Actor 一起使用时的 Scala 变量绑定(bind)

swift - 在 UIViewController 中正确使用 present

android-studio - gradle项目同步失败的Android Studio 3.1.2

Gradle 在 TransformClassesWithDexForDebug 上构建缓慢

android - image_picker_android :debugUnitTestRuntimeClasspath

xml - Groovy:使用 GPathResult.appendNode(node) 合并两个 XML 文件不起作用

jenkins - 无法解析类 XmlParser.parseText

java - Gradle 部署失败并显示 "java.io.IOException: The filename, directory name, or volume label syntax is incorrect"

java - 在nifi执行脚本处理器中使用groovy内部的GeorgianCalendar

ios - 处理URLSession时是否总是需要[Weak self]?