Gradle任务差异 [英] Gradle Tasks Difference

查看:199
本文介绍了Gradle任务差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个代码片段有什么区别?



第一:

 任务copyFiles(类型:复制)<< {
fromfolder / from
intodest / folder
}

第二:

 任务copyFiles(类型:复制){
fromfolder / from
到dest / folder
}


解决方案

简而言之,第一个代码段出错了,第二个代码段是正确的。

Gradle构建分三个阶段进行:初始化,配置,和执行。像 配置任务的方法,因此需要在配置阶段。但是,<< (这是 doLast 的快捷方式)添加了任务操作 - 它指示任务如果和执行时执行什么操作。换句话说,第一个代码片段在执行阶段配置了任务,甚至更糟糕的是,在其主(复制)操作之后执行了它。因此,配置不会有任何影响。



通常,任务是类型(已经带来任务操作) a << (用于特设任务)。有两种方法合理的用例(在任务的主要工作之后做了一些自定义工作),但更常见的是,这不是任务配置得太迟的错误。



我通常建议使用 doLast 而不是 <<<$ code>,因为它的含义较少,更容易发现这些错误。 (一旦理解了这些概念,很明显,任务copyFiles(type:Copy){doLast {from ...}} 是错误的。)


What's the difference between the following two code snippets?

First:

task copyFiles(type: Copy) << {
  from "folder/from"
  into "dest/folder"
}

Second:

task copyFiles(type: Copy) {
  from "folder/from"
  into "dest/folder"
}

解决方案

In short, the first snippet is getting it wrong, and the second one is getting it right.

A Gradle build proceeds in three phases: initialization, configuration, and execution. Methods like from and into configure a task, hence they need to be invoked in the configuration phase. However, << (which is a shortcut for doLast) adds a task action - it instructs the task what to do if and when it gets executed. In other words, the first snippet configures the task in the execution phase, and even worse, after its main (copy) action has been executed. Hence the configuration won't have any effect.

Typically, a task has either a type (which already brings along a task action) or a << (for an ad-hoc task). There are legitimate uses cases for having both (doing a bit of custom work after the task's "main" work), but more often that not, it's a mistake where the task gets configured too late.

I generally recommend to use doLast instead of <<, because it's less cryptic and makes it easier to spot such mistakes. (Once you understand the concepts, it's kind of obvious that task copyFiles(type: Copy) { doLast { from ... } } is wrong.)

这篇关于Gradle任务差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆