减少Groovy闭包中的代码重复

时间:2013-11-05 17:34:21

标签: 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') }
        }
    }
}

我将如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

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

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()
        }
    }
}