这是我的:
构建.gradle
task makeDirectoryStructure(type:Exec){
description 'Creates directory structure .'
commandLine 'mkdir'
args '-p' ,'top_dir/sub_dir_1/sub_dir_2'
println "This line is printed in configuration phase."
}
现在,因为我还没有使用过' << ' 或< ' doFirst/doLast ',我希望 mkdir 在配置阶段执行,即编译构建脚本时。例如如果我做
$gradle tasks
我希望 mkdir 在配置阶段运行,即我的目录结构应该形成但没有发生。
但是我得到这个输出:
yogeshwardancharan@yogeshwardancharan-Lenovo-G570:~/android_learning_resources/gradle_resources/ud867/1.01-Exercise-RunYourFirstTask$ gradle tasks
This line is printed in configuration phase.
:tasks
------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------
Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]
Help tasks
----------
components - Displays the components produced by root project '1.01-Exercise-RunYourFirstTask'. [incubating]
dependencies - Displays all dependencies declared in root project '1.01-Exercise-RunYourFirstTask'.
dependencyInsight - Displays the insight into a specific dependency in root project '1.01-Exercise-RunYourFirstTask'.
help - Displays a help message.
model - Displays the configuration model of root project '1.01-Exercise-RunYourFirstTask'. [incubating]
projects - Displays the sub-projects of root project '1.01-Exercise-RunYourFirstTask'.
properties - Displays the properties of root project '1.01-Exercise-RunYourFirstTask'.
tasks - Displays the tasks runnable from root project '1.01-Exercise-RunYourFirstTask'.
Other tasks
-----------
makeDirectoryStructure - Creates directory structure .
现在,在这一行的上面输出打印中
This line is printed in configuration phase.
确认任务确实在配置阶段被处理。
而且,当我发出命令时
$gradle makeDirectoryStructure
以上两行都打印出来,目录结构也形成了。
所以,最后的问题是为什么我的 mkdir 不是在配置阶段运行,或者我是一些非常常见的概念。
最佳答案
请看 AbstractExecTask
来自 Exec
继承。正如你所看到的,有很多 getter 和 setter。配置时发生的事情只是设置这些字段的值,而不是运行它们。所有设置的属性只会在 exec()
时使用用 @TaskAction
注释的方法被调用 - 这发生在运行时。为什么println
作品?它只是一个被调用的方法,和上面提到的setter方法完全一样——println
只是有一个可见的效果,而 setter 只是更改稍后使用的属性。
每个任务都有它的 Action 。不同之处在于,在配置阶段仅配置任务,并且在执行任务操作时使用此配置。
关于Gradle Exec : Why it is not running in configuration phase?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30880773/