Android 使用 Gradle,如何确保某个文件存在于某个位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22750704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:24:52  来源:igfitidea点击:

Using Gradle, how can I ensure that a file exists at a certain location?

androidintellij-ideagradle

提问by Mendhak

I am starting to use Gradle for an Android application. I would like the build to fail if the developer fails to create a file at a specific location such as ./src/res/values/specialfile.xml

我开始将 Gradle 用于 Android 应用程序。如果开发人员未能在特定位置创建文件,我希望构建失败,例如./src/res/values/specialfile.xml

A bit of searchingled me to believe that a .doFirstwould work

一些搜索让我相信 a.doFirst会起作用

android.doFirst { 
    assert file("./src/res/values/specialfile.txt").exists() 
} 

However, Gradle says "unsupported Gradle DSL method found: 'doFirst()'!"

但是,Gradle 说 “发现不受支持的 Gradle DSL 方法:'doFirst()'!”

What can I do to assert a file's existence?

我能做些什么来断言文件的存在?

回答by Xavier Ducrohet

doFirst only exists on tasks object. androidis not a task.

doFirst 仅存在于任务对象上。android不是任务。

If would want this test to always be done even if the developer doesn't try to build (for example when running the taskstask), you should simply put in your build.gradle

如果即使开发人员不尝试构建(例如在运行tasks任务时)也希望始终完成此测试,您应该简单地输入您的build.gradle

assert file("./src/res/values/specialfile.txt").exists() 

However this is really not recommended as this would be executed even for non build tasks, or even when the model is built for IDE integration.

然而,这真的是不推荐的,因为即使对于非构建任务,或者甚至在为 IDE 集成构建模型时,也会执行此操作。

There is a task called preBuildthat is executed before anything in the android build, so you can hook your test to it, either through another task or through doFirst:

有一个任务preBuild在 android 构建中的任何事情之前执行,因此您可以通过另一个任务或通过doFirst以下方式将测试挂钩到它:

preBuild.doFirst { 
    assert file("./src/res/values/specialfile.txt").exists() 
}