Gradle Gradle 命令行的基本使用


本文整理自网络,侵删。

Gradle 命令行的基本使用

本章介绍了命令行的基本使用。正如在前面的章节里你所见到的调用 gradle 命令来完成一些功能。

多任务调用

你可以以列表的形式在命令行中一次调用多个任务。例如 gradle compile test 命令会依次调用,并且每个任务仅会被调用一次。compile 和 test 任务以及它们的依赖任务。无论它们是否被包含在脚本中:即无论是以命令行的形式定义的任务还是依赖于其它任务都会被调用执行。来看下面的例子。

下面定义了四个任务。dist 和 test 都依赖于 compile,只用当 compile 被调用之后才会调用 gradle dist test 任务。

任务依赖

多任务调用

build.gradle

task compile << {
    println 'compiling source'
}
task compileTest(dependsOn: compile) << {
    println 'compiling unit tests'
}
task test(dependsOn: [compile, compileTest]) << {
    println 'running unit tests'
}
task dist(dependsOn: [compile, test]) << {
    println 'building the distribution'
}

gradle dist test 的输出结果。

\> gradle dist test
:compile
compiling source
:compileTest
compiling unit tests
:test
running unit tests
:dist
building the distribution
BUILD SUCCESSFUL
Total time: 1 secs

由于每个任务仅会被调用一次,所以调用 gradle test test 与调用 gradle test 效果是相同的。

排除任务

你可以用命令行选项 -x 来排除某些任务,让我们用上面的例子来示范一下。

排除任务

gradle dist -x test 的输出结果。

\> gradle dist -x test
:compile
compiling source
:dist
building the distribution
BUILD SUCCESSFUL
Total time: 1 secs

可以看到,test 任务并没有被调用,即使他是 dist 任务的依赖。同时 test 任务的依赖任务 compileTest 也没有被调用,而像 compile 被 test 和其它任务同时依赖的任务仍然会被调用。

失败后继续执行

默认情况下只要有任务调用失败 Gradle 就是中断执行。这可能会使调用过程更快,但那些后面隐藏的错误不会被发现。所以你可以使用--continue 在一次调用中尽可能多的发现所有问题。

采用了--continue 选项,Gradle会调用每一个任务以及它们依赖的任务。而不是一旦出现错误就会中断执行。所有错误信息都会在最后被列出来。

一旦某个任务执行失败,那么所有依赖于该任务的子任务都不会被调用。例如由于 test 任务依赖于 complie 任务,所以如果 compile 调用出错,test 便不会被直接或间接调用。

简化任务名

当你试图调用某个任务的时候,无需输入任务的全名。只需提供足够的可以唯一区分出该任务的字符即可。例如,上面的例子你也可以这么写。用 gradle di 来直接调用 dist 任务。

简化任务名

gradle di 的输出结果

\> gradle di
:compile
compiling source
:compileTest
compiling unit tests
:test
running unit tests
:dist
building the distribution
BUILD SUCCESSFUL
Total time: 1 secs

你也可以用驼峰命名的任务中每个单词的首字母进行调用。例如,可以执行 gradle compTest or even gradle cT 来调用 compileTest 任务。

简化驼峰任务名

gradle cT 的输出结果。

\> gradle cT
:compile
compiling source
:compileTest
compiling unit tests
BUILD SUCCESSFUL
Total time: 1 secs

简化后你仍然可以使用 -x 参数。

选择构建位置

调用 gradle 时,默认情况下总是会构建当前目录下的文件,可以使用-b 参数选择构建的文件,并且当你使用此参数时settings。gradle 将不会生效,看下面的例子:

选择文件构建

subdir/myproject.gradle

task hello << {
    println "using build file '$buildFile.name' in '$buildFile.parentFile.name'."
}

gradle -q -b subdir/myproject.gradle hello 的输出结果

Output of gradle -q -b subdir/myproject.gradle hello
\> gradle -q -b subdir/myproject.gradle hello
using build file 'myproject.gradle' in 'subdir'.

另外,你可以使用 -p 参数来指定构建的目录,例如在多项目构建中你可以用 -p 来替代 -b 参数。

选择构建目录

gradle -q -p subdir hello 的输出结果

\> gradle -q -p subdir hello
using build file 'build.gradle' in 'subdir'.

获取构建信息

Gradle 提供了许多内置任务来收集构建信息。这些内置任务对于了解依赖结构以及解决问题都是很有帮助的。

阅读剩余部分

相关阅读 >>

Gradle 依赖管理基础

Gradle scala 插件

Gradle checkstyle 插件

Gradle 安装

Gradle 任务详述

Gradle 简介

Gradle ear 插件

Gradle 构建基础

Gradle sonar 插件

Gradle Gradle 守护进程

更多相关阅读请进入《Gradle》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...