2

在一段 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') }
        }
    }
}

我将如何实现这一目标?

4

1 回答 1

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()
        }
    }
}
于 2013-11-05T18:00:08.067 回答