用例:在构建应用程序之前,我有一堆图像必须由脚本处理。在makefile中,我可以简单地定义:
processed/%.png: original/%.png
script/process.sh $< $@
我该如何在Gradle中实现呢?具体来说,我希望它像在Makefile中一样工作,仅修改后的原始图像将被再次处理。
最佳答案
您可以使用IncrementalTaskInputs作为其输入参数,将该行为实现为增量任务。该API文档包含一个如何使用它和here is an example in another the documentation的示例。他们俩几乎都能满足您的需求。
在您的任务中,使用exec
任务调用脚本。您的Gradle脚本可能如下所示:
task processRawFiles(type: ProcessRawFiles)
class ProcessRawFiles extends DefaultTask {
@InputDirectory
File inputDir = project.file('src/raw')
@OutputDirectory
File outputDir = project.file('build/processed')
@TaskAction
void execute(IncrementalTaskInputs inputs) {
if (!inputs.incremental)
project.delete(outputDir.listFiles())
inputs.outOfDate { InputFileDetails change ->
File saveTo = new File(outputDir, change.file.name)
project.exec {
commandLine 'script/process.sh', change.file.absolutePath, saveTo.absolutePath
}
}
inputs.removed { InputFileDetails change ->
File toDelete = new File(outputDir, change.file.name)
if (toDelete.exists())
toDelete.delete()
}
}
}
此任务在
src/raw
中查找图像。它将从构建目录中删除文件,并对所有过期或新添加的文件调用脚本。如果图像分散在多个目录中,则您的特定情况可能会更加复杂。在这种情况下,您将不得不使用
@InputFiles
而不是@InputDirectory
。但是增量任务仍然可以工作。