如何扩展gradle的清除任务以删除文件?

时间:2015-04-23 03:34:57

标签: gradle build.gradle

到目前为止,我已将以下内容添加到我的build.gradle

apply plugin: 'base' 
clean << {
    delete '${rootDir}/api-library/auto-generated-classes/'
    println '${rootDir}/api-library/auto-generated-classes/'
}

但是,不仅我的文件没有被删除,而且print语句显示${rootDir}没有被转换为我项目的根目录。为什么要赢得这项工作,我缺少哪些概念?

5 个答案:

答案 0 :(得分:55)

你只需要使用双引号。另外,如果您计划在执行期间执行删除操作,请删除<<并使用doFirst。像这样:

clean.doFirst {
    delete "${rootDir}/api-library/auto-generated-classes/"
    println "${rootDir}/api-library/auto-generated-classes/"
}

Gradle构建脚本是用Groovy DSL编写的。在Groovy中,您需要使用双引号进行字符串插值(当您使用${}作为占位符时)。看看here

答案 1 :(得分:39)

<<clean.doLast相同。 doFirstdoLast正在执行阶段对操作进行排序, 这与删除操作很少相关。

在这种情况下,您不需要其中任何一个。 base的clean任务是Delete类型, 所以你只需要传递一个闭包,告诉它在配置时间执行时要删除的内容:

clean {
    delete 'someFile'
}

AS mushfek0001在答案中正确指出了它,你应该使用双引号进行变量插值:

clean {
    delete "${buildDir}/someFile"
}

你需要至少应用这个基本插件才能工作,大多数其他插件,比如Java插件要么应用base还是声明自己的插件 clean任务类型为delete Delete任务。如果没有这个错误,您将得到的错误是缺少clean方法。

apply plugin: 'base'

答案 2 :(得分:16)

In order to extend the clean task, you can use

clean.doFirst {}

or

clean.doLast {}

These will allow you to inject your own actions into the clean process. In order to delete files and directories you can use the "file" API which doesn't require any additional plugins.

Here is an example that will delete both a file and a directory as the last step in the clean task:

clean.doLast {
    file('src/main/someFile.txt').delete()
    file('src/main/libs').deleteDir()
}

答案 3 :(得分:1)

下面一个对我有用(我更喜欢使用dependsOn

task customCleanUp(type:Delete) {
   delete "your_folder", "your_file"
}

tasks.clean.dependsOn(tasks.customCleanUp)

答案 4 :(得分:0)

Gradle Kotlin脚本类似物:

tasks {
    getByName<Delete>("clean") {
        delete.add("logs") // add accepts argument with Any type
    }
}