Gradle学习笔记之任务

任务入门

先看一个例子:

...... // GradleTest build.gradle

task("Task1") {
    // 任务配置阶段
    println "executing Task1...."

    // 任务的执行阶段
    doFirst {
        println "doFirst in Task1...."
    }

    doLast {
        println "doLast Task1...."
    }
}

Task1为任务的名称,任务体中,配置阶段的代码在配置阶段执行,执行阶段的代码在执行阶段执行。我们在该build.gradle所在的目录执行以下命令:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle Task1

> Configure project :
executing Task1....

> Task :Task1
doFirst in Task1....
doLast Task1....

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

可以清楚地看到,executing Task1....语句在配置时输出,剩下的语句都是在执行阶段输出。

任务行为

上面的doFirstdoLast就是最典型的任务行为,可以定义在任务闭包体内部,或者外部:

task("Task1") {
    println "executing Task1...."

    doFirst {
        println "doFirst in Task1...."
    }

    doLast {
        println "doLast Task1...."
    }
}

Task1.doFirst {
    println "doFirst out in Task1...."
}

Task1.doLast {
    println "doLast out Task1...."
}

输出如下:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle Task1

> Configure project :
executing Task1....

> Task :Task1
doFirst out in Task1....
doFirst in Task1....
doLast Task1....
doLast out Task1....

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

多个doFirst和多个doLast的执行顺序为:新定义的doFirst在旧定义的doFirst之前执行,新定义的doLast在旧定义的doLast之后执行,所有doFirst在所有doLast之前执行。

我们还可以通过映射的方式,定义任务的action行为,此种行为在doFirstdoLast之间执行:

def paramMap = ["action": { // 键名固定,为action
    println("action in map")
}]

task(paramMap, "Task1") {
    println "executing Task1...."

    doFirst {
        println "doFirst in Task1...."
    }

    doLast {
        println "doLast Task1...."
    }
}

Task1.doFirst {
    println "doFirst out in Task1...."
}


Task1.doLast {
    println "doLast out Task1...."
}

执行结果如下:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle Task1

> Configure project :
executing Task1....

> Task :Task1
doFirst out in Task1....
doFirst in Task1....
action in map
doLast Task1....
doLast out Task1....

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

任务的依赖方式

任务间彼此的依赖方式有三种:参数依赖、内部依赖和外部依赖

参数依赖

task("A") {
    doFirst {
        println "do first in A"
    }
}

task("B") {
    doFirst {
        println "do first in B"
    }
}

task "C" (dependsOn: ["A", "B"]) { // 此时任务名不能加括号
    doFirst {
        println "do first in C"
    }
}

上例中,C任务依赖于任务A和B,因此执行脚本后的输出如下:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle C

> Task :A
do first in A

> Task :B
do first in B

> Task :C
do first in C

BUILD SUCCESSFUL in 2s
3 actionable tasks: 3 executed

内部依赖

task "C" {
    dependsOn(["A"])
    doFirst {
        println "do first in C"
    }
}

脚本输出:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle C

> Task :A
do first in A

> Task :C
do first in C

外部依赖

task "C" {
    doFirst {
        println "do first in C"
    }
}

C.dependsOn("B")

脚本输出:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle C

> Task :B
do first in B

> Task :C
do first in C

多种依赖方式的混合

注意,某个任务若同时存在多种依赖方式,执行时则会取所有依赖方式的并集:

task "C" {
    dependsOn(["A"])
    doFirst {
        println "do first in C"
    }
}

C.dependsOn("B")

脚本输出:

14:56:38: Executing task '"C"'...

> Task :A
do first in A

> Task :B
do first in B

> Task :C
do first in C

BUILD SUCCESSFUL in 575ms
3 actionable tasks: 3 executed
14:56:39: Task execution finished '"C"'.

跨项目依赖

也可以跨项目依赖任务,如项目lib2build.gradle中有任务D:

task "D" {
    doFirst {
        println "doFirst in D"
    }
}

在项目GradleTestbuild.gradle中可以这样进行依赖:

task "C" {
    dependsOn([":lib2:D"])
    doFirst {
        println "do first in C"
    }
}

C.dependsOn("B")

脚本输出如下:

14:58:55: Executing task '"C"'...

> Task :B
do first in B

> Task :lib2:D
doFirst in D

> Task :C
do first in C

BUILD SUCCESSFUL in 297ms
3 actionable tasks: 3 executed
14:58:55: Task execution finished '"C"'.

若一个任务依赖于多个任务时,且被依赖的任务之间没有依赖关系,则被依赖任务的执行顺序是随机的。另外,一次任务执行中,被重复依赖的任务只会执行一次,如A->B、C,B->C,但C只会执行一次:

task("A") {
    doFirst {
        println "do first in A"
    }
}

task("B") {
    doFirst {
        println "do first in B"
    }
}

task "C" {
    dependsOn(["A", "B"])
    doFirst {
        println "do first in C"
    }
}

B.dependsOn("A")

任务输出如下:

15:03:15: Executing task '"C"'...

> Task :A
do first in A

> Task :B
do first in B

> Task :C
do first in C

BUILD SUCCESSFUL in 234ms
3 actionable tasks: 3 executed
15:03:16: Task execution finished '"C"'.

任务执行

任务执行语法:

gradle [taskName] [--option-name ...]

gradle中任务分类如下表所示:
在这里插入图片描述
在这里插入图片描述

gradle run命令演示

首先在GradleTest项目的源码里编写Main.java文件:

package com.szc;

public class Main {
    public static void main(String[] args) {
        System.out.println("Main method is executed in class " + Main.class.getCanonicalName());
    }
}

再修改该项目的build.gradle文件:

plugins {
    id 'java'
    id 'application' // 设置application标签
}

................

mainClassName = "com.szc.Main" // 指定启动类

而后在该项目根目录下,执行gradle run

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle run

> Configure project :
executing Task1....

> Task :run
Main method is executed in class com.szc.Main

BUILD SUCCESSFUL in 3s
2 actionable tasks: 2 executed

gradle projects演示

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle projects

> Configure project :
executing Task1....

> Task :projects

------------------------------------------------------------
Root project 'GradleTest'
------------------------------------------------------------

Root project 'GradleTest'
+--- Project ':lib1'
|    +--- Project ':lib1:lib1_1'
|    \--- Project ':lib1:lib1_2'
+--- Project ':lib2'
\--- Project ':lib3'

To see a list of the tasks of a project, run gradle <project-path>:tasks
For example, try running gradle :lib1:tasks

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

gradle tasks演示

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle tasks

> Configure project :
executing Task1....

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'GradleTest'
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'GradleTest'.
dependencies - Displays all dependencies declared in root project 'GradleTest'.
dependencyInsight - Displays the insight into a specific dependency in root project 'GradleTest'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'GradleTest'.
projects - Displays the sub-projects of root project 'GradleTest'.
properties - Displays the properties of root project 'GradleTest'.
tasks - Displays the tasks runnable from root project 'GradleTest' (some of the displayed tasks may belong to subprojects).

Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.

Rules
-----
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

没看到我们的Task1、A、B、C和D,因为没有给它们设置分组。我们可以给A和B加上分组:

task("A") {
    group "demo" // 任务分组
    doFirst {
        println "do first in A"
    }
}

task("B") {
    group "demo"
    doFirst {
        println "do first in B"
    }
}

然后再执行gradle tasks,输出如下:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle tasks

> Configure project :
executing Task1....

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'GradleTest'
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Demo tasks
----------
A
B

Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'GradleTest'.
dependencies - Displays all dependencies declared in root project 'GradleTest'.
dependencyInsight - Displays the insight into a specific dependency in root project 'GradleTest'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'GradleTest'.
projects - Displays the sub-projects of root project 'GradleTest'.
properties - Displays the properties of root project 'GradleTest'.
tasks - Displays the tasks runnable from root project 'GradleTest' (some of the displayed tasks may belong to subprojects).

Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.

Rules
-----
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

可以看到我们的demo任务组下的A任务和B任务了。

gradle tasks --all演示

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle tasks --all

> Configure project :
executing Task1....

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'GradleTest'
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application

Build tasks
-----------
assemble - Assembles the outputs of this project.
lib1:assemble - Assembles the outputs of this project.
lib1:lib1_1:assemble - Assembles the outputs of this project.
lib1:lib1_2:assemble - Assembles the outputs of this project.
lib2:assemble - Assembles the outputs of this project.
lib3:assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
lib1:build - Assembles and tests this project.
lib1:lib1_1:build - Assembles and tests this project.
lib1:lib1_2:build - Assembles and tests this project.
lib2:build - Assembles and tests this project.
lib3:build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
lib1:buildDependents - Assembles and tests this project and all projects that depend on it.
lib1:lib1_1:buildDependents - Assembles and tests this project and all projects that depend on it.
lib1:lib1_2:buildDependents - Assembles and tests this project and all projects that depend on it.
lib2:buildDependents - Assembles and tests this project and all projects that depend on it.
lib3:buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
lib1:buildNeeded - Assembles and tests this project and all projects it depends on.
lib1:lib1_1:buildNeeded - Assembles and tests this project and all projects it depends on.
lib1:lib1_2:buildNeeded - Assembles and tests this project and all projects it depends on.
lib2:buildNeeded - Assembles and tests this project and all projects it depends on.
lib3:buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
lib1:classes - Assembles main classes.
lib1:lib1_1:classes - Assembles main classes.
lib1:lib1_2:classes - Assembles main classes.
lib2:classes - Assembles main classes.
lib3:classes - Assembles main classes.
clean - Deletes the build directory.
lib1:clean - Deletes the build directory.
lib1:lib1_1:clean - Deletes the build directory.
lib1:lib1_2:clean - Deletes the build directory.
lib2:clean - Deletes the build directory.
lib3:clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
lib1:jar - Assembles a jar archive containing the main classes.
lib1:lib1_1:jar - Assembles a jar archive containing the main classes.
lib1:lib1_2:jar - Assembles a jar archive containing the main classes.
lib2:jar - Assembles a jar archive containing the main classes.
lib3:jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.
lib1:testClasses - Assembles test classes.
lib1:lib1_1:testClasses - Assembles test classes.
lib1:lib1_2:testClasses - Assembles test classes.
lib2:testClasses - Assembles test classes.
lib3:testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Demo tasks
----------
A
B

Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.
lib1:javadoc - Generates Javadoc API documentation for the main source code.
lib1:lib1_1:javadoc - Generates Javadoc API documentation for the main source code.
lib1:lib1_2:javadoc - Generates Javadoc API documentation for the main source code.
lib2:javadoc - Generates Javadoc API documentation for the main source code.
lib3:javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'GradleTest'.
lib1:buildEnvironment - Displays all buildscript dependencies declared in project ':lib1'.
lib1:lib1_1:buildEnvironment - Displays all buildscript dependencies declared in project ':lib1:lib1_1'.
lib1:lib1_2:buildEnvironment - Displays all buildscript dependencies declared in project ':lib1:lib1_2'.
lib2:buildEnvironment - Displays all buildscript dependencies declared in project ':lib2'.
lib3:buildEnvironment - Displays all buildscript dependencies declared in project ':lib3'.
dependencies - Displays all dependencies declared in root project 'GradleTest'.
lib1:dependencies - Displays all dependencies declared in project ':lib1'.
lib1:lib1_1:dependencies - Displays all dependencies declared in project ':lib1:lib1_1'.
lib1:lib1_2:dependencies - Displays all dependencies declared in project ':lib1:lib1_2'.
lib2:dependencies - Displays all dependencies declared in project ':lib2'.
lib3:dependencies - Displays all dependencies declared in project ':lib3'.
dependencyInsight - Displays the insight into a specific dependency in root project 'GradleTest'.
lib1:dependencyInsight - Displays the insight into a specific dependency in project ':lib1'.
lib1:lib1_1:dependencyInsight - Displays the insight into a specific dependency in project ':lib1:lib1_1'.
lib1:lib1_2:dependencyInsight - Displays the insight into a specific dependency in project ':lib1:lib1_2'.
lib2:dependencyInsight - Displays the insight into a specific dependency in project ':lib2'.
lib3:dependencyInsight - Displays the insight into a specific dependency in project ':lib3'.
help - Displays a help message.
lib1:help - Displays a help message.
lib1:lib1_1:help - Displays a help message.
lib1:lib1_2:help - Displays a help message.
lib2:help - Displays a help message.
lib3:help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
lib1:javaToolchains - Displays the detected java toolchains.
lib1:lib1_1:javaToolchains - Displays the detected java toolchains.
lib1:lib1_2:javaToolchains - Displays the detected java toolchains.
lib2:javaToolchains - Displays the detected java toolchains.
lib3:javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'GradleTest'.
lib1:outgoingVariants - Displays the outgoing variants of project ':lib1'.
lib1:lib1_1:outgoingVariants - Displays the outgoing variants of project ':lib1:lib1_1'.
lib1:lib1_2:outgoingVariants - Displays the outgoing variants of project ':lib1:lib1_2'.
lib2:outgoingVariants - Displays the outgoing variants of project ':lib2'.
lib3:outgoingVariants - Displays the outgoing variants of project ':lib3'.
projects - Displays the sub-projects of root project 'GradleTest'.
lib1:projects - Displays the sub-projects of project ':lib1'.
lib1:lib1_1:projects - Displays the sub-projects of project ':lib1:lib1_1'.
lib1:lib1_2:projects - Displays the sub-projects of project ':lib1:lib1_2'.
lib2:projects - Displays the sub-projects of project ':lib2'.
lib3:projects - Displays the sub-projects of project ':lib3'.
properties - Displays the properties of root project 'GradleTest'.
lib1:properties - Displays the properties of project ':lib1'.
lib1:lib1_1:properties - Displays the properties of project ':lib1:lib1_1'.
lib1:lib1_2:properties - Displays the properties of project ':lib1:lib1_2'.
lib2:properties - Displays the properties of project ':lib2'.
lib3:properties - Displays the properties of project ':lib3'.
tasks - Displays the tasks runnable from root project 'GradleTest' (some of the displayed tasks may belong to subprojects).
lib1:tasks - Displays the tasks runnable from project ':lib1' (some of the displayed tasks may belong to subprojects).
lib1:lib1_1:tasks - Displays the tasks runnable from project ':lib1:lib1_1'.
lib1:lib1_2:tasks - Displays the tasks runnable from project ':lib1:lib1_2'.
lib2:tasks - Displays the tasks runnable from project ':lib2'.
lib3:tasks - Displays the tasks runnable from project ':lib3'.

Verification tasks
------------------
check - Runs all checks.
lib1:check - Runs all checks.
lib1:lib1_1:check - Runs all checks.
lib1:lib1_2:check - Runs all checks.
lib2:check - Runs all checks.
lib3:check - Runs all checks.
test - Runs the unit tests.
lib1:test - Runs the unit tests.
lib1:lib1_1:test - Runs the unit tests.
lib1:lib1_2:test - Runs the unit tests.
lib2:test - Runs the unit tests.
lib3:test - Runs the unit tests.

Other tasks
-----------
C
compileJava - Compiles main Java source.
lib1:compileJava - Compiles main Java source.
lib1:lib1_1:compileJava - Compiles main Java source.
lib1:lib1_2:compileJava - Compiles main Java source.
lib2:compileJava - Compiles main Java source.
lib3:compileJava - Compiles main Java source.
compileTestJava - Compiles test Java source.
lib1:compileTestJava - Compiles test Java source.
lib1:lib1_1:compileTestJava - Compiles test Java source.
lib1:lib1_2:compileTestJava - Compiles test Java source.
lib2:compileTestJava - Compiles test Java source.
lib3:compileTestJava - Compiles test Java source.
components - Displays the components produced by root project 'GradleTest'. [deprecated]
lib1:components - Displays the components produced by project ':lib1'. [deprecated]
lib1:lib1_1:components - Displays the components produced by project ':lib1:lib1_1'. [deprecated]
lib1:lib1_2:components - Displays the components produced by project ':lib1:lib1_2'. [deprecated]
lib2:components - Displays the components produced by project ':lib2'. [deprecated]
lib3:components - Displays the components produced by project ':lib3'. [deprecated]
lib2:D
dependentComponents - Displays the dependent components of components in root project 'GradleTest'. [deprecated]
lib1:dependentComponents - Displays the dependent components of components in project ':lib1'. [deprecated]
lib1:lib1_1:dependentComponents - Displays the dependent components of components in project ':lib1:lib1_1'. [deprecated]
lib1:lib1_2:dependentComponents - Displays the dependent components of components in project ':lib1:lib1_2'. [deprecated]
lib2:dependentComponents - Displays the dependent components of components in project ':lib2'. [deprecated]
lib3:dependentComponents - Displays the dependent components of components in project ':lib3'. [deprecated]
model - Displays the configuration model of root project 'GradleTest'. [deprecated]
lib1:model - Displays the configuration model of project ':lib1'. [deprecated]
lib1:lib1_1:model - Displays the configuration model of project ':lib1:lib1_1'. [deprecated]
lib1:lib1_2:model - Displays the configuration model of project ':lib1:lib1_2'. [deprecated]
lib2:model - Displays the configuration model of project ':lib2'. [deprecated]
lib3:model - Displays the configuration model of project ':lib3'. [deprecated]
prepareKotlinBuildScriptModel
processResources - Processes main resources.
lib1:processResources - Processes main resources.
lib1:lib1_1:processResources - Processes main resources.
lib1:lib1_2:processResources - Processes main resources.
lib2:processResources - Processes main resources.
lib3:processResources - Processes main resources.
processTestResources - Processes test resources.
lib1:processTestResources - Processes test resources.
lib1:lib1_1:processTestResources - Processes test resources.
lib1:lib1_2:processTestResources - Processes test resources.
lib2:processTestResources - Processes test resources.
lib3:processTestResources - Processes test resources.
startScripts - Creates OS specific scripts to run the project as a JVM application.
Task1

Rules
-----
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

可以看到,C、Task1和lib2:D都被分到了Other任务组中。

查看指定的任务组任务

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle tasks --group="demo"

> Configure project :
executing Task1....

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'GradleTest'
------------------------------------------------------------

Demo tasks
----------
A
B

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

查看某一任务的详细信息

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle help --task A

> Configure project :
executing Task1....

> Task :help
Detailed task information for A

Path
     :A

Type
     Task (org.gradle.api.Task)

Description
     -

Group
     demo

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

查看项目的依赖关系

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle dependencies

> Configure project :
executing Task1....

> Task :dependencies

------------------------------------------------------------
Root project 'GradleTest'
------------------------------------------------------------

annotationProcessor - Annotation processors and their dependencies for source set 'main'.
No dependencies

apiElements - API elements for main. (n)
No dependencies

archives - Configuration for archive artifacts. (n)
No dependencies

compileClasspath - Compile classpath for source set 'main'.
No dependencies

compileOnly - Compile only dependencies for source set 'main'. (n)
No dependencies

default - Configuration for default artifacts. (n)
No dependencies

implementation - Implementation only dependencies for source set 'main'. (n)
No dependencies

runtimeClasspath - Runtime classpath of source set 'main'.
No dependencies

runtimeElements - Elements of runtime for main. (n)
No dependencies

runtimeOnly - Runtime only dependencies for source set 'main'. (n)
No dependencies

testAnnotationProcessor - Annotation processors and their dependencies for source set 'test'.
No dependencies

testCompileClasspath - Compile classpath for source set 'test'.
\--- org.junit.jupiter:junit-jupiter-api:5.7.0
     +--- org.junit:junit-bom:5.7.0
     |    +--- org.junit.jupiter:junit-jupiter-api:5.7.0 (c)
     |    \--- org.junit.platform:junit-platform-commons:1.7.0 (c)
     +--- org.apiguardian:apiguardian-api:1.1.0
     +--- org.opentest4j:opentest4j:1.2.0
     \--- org.junit.platform:junit-platform-commons:1.7.0
          +--- org.junit:junit-bom:5.7.0 (*)
          \--- org.apiguardian:apiguardian-api:1.1.0

testCompileOnly - Compile only dependencies for source set 'test'. (n)
No dependencies

testImplementation - Implementation only dependencies for source set 'test'. (n)
\--- org.junit.jupiter:junit-jupiter-api:5.7.0 (n)

testRuntimeClasspath - Runtime classpath of source set 'test'.
+--- org.junit.jupiter:junit-jupiter-api:5.7.0
|    +--- org.junit:junit-bom:5.7.0
|    |    +--- org.junit.jupiter:junit-jupiter-api:5.7.0 (c)
|    |    +--- org.junit.jupiter:junit-jupiter-engine:5.7.0 (c)
|    |    +--- org.junit.platform:junit-platform-commons:1.7.0 (c)
|    |    \--- org.junit.platform:junit-platform-engine:1.7.0 (c)
|    +--- org.apiguardian:apiguardian-api:1.1.0
|    +--- org.opentest4j:opentest4j:1.2.0
|    \--- org.junit.platform:junit-platform-commons:1.7.0
|         +--- org.junit:junit-bom:5.7.0 (*)
|         \--- org.apiguardian:apiguardian-api:1.1.0
\--- org.junit.jupiter:junit-jupiter-engine:5.7.0
     +--- org.junit:junit-bom:5.7.0 (*)
     +--- org.apiguardian:apiguardian-api:1.1.0
     +--- org.junit.platform:junit-platform-engine:1.7.0
     |    +--- org.junit:junit-bom:5.7.0 (*)
     |    +--- org.apiguardian:apiguardian-api:1.1.0
     |    +--- org.opentest4j:opentest4j:1.2.0
     |    \--- org.junit.platform:junit-platform-commons:1.7.0 (*)
     \--- org.junit.jupiter:junit-jupiter-api:5.7.0 (*)

testRuntimeOnly - Runtime only dependencies for source set 'test'. (n)
\--- org.junit.jupiter:junit-jupiter-engine:5.7.0 (n)

(c) - dependency constraint
(*) - dependencies omitted (listed previously)

(n) - Not resolved (configuration is not meant to be resolved)

A web-based, searchable dependency report is available by adding the --scan option.

BUILD SUCCESSFUL in 6s
1 actionable task: 1 executed

查看项目的属性信息

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle properties

> Configure project :
executing Task1....

> Task :properties

------------------------------------------------------------
Root project 'GradleTest'
------------------------------------------------------------

A: task ':A'
B: task ':B'
C: task ':C'
Task1: task ':Task1'
allprojects: [root project 'GradleTest', project ':lib1', project ':lib2', project ':lib3', project ':lib1:lib1_1', project
':lib1:lib1_2']
ant: org.gradle.api.internal.project.DefaultAntBuilder@517c60a5
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@2e19b3ca
application: extension 'application'
applicationDefaultJvmArgs: []
applicationDistribution: org.gradle.api.internal.file.copy.DefaultCopySpec_Decorated@3168c248
applicationName: GradleTest
archivesBaseName: GradleTest
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@1535b610
asDynamicObject: DynamicObject for root project 'GradleTest'
autoTargetJvmDisabled: false
base: extension 'base'
baseClassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@277e855b
buildDir: D:\develop\ideaWorkspace\GradleTest\build
buildFile: D:\develop\ideaWorkspace\GradleTest\build.gradle
buildPath: :
buildScriptSource: org.gradle.groovy.scripts.TextResourceScriptSource@449ae59d
buildscript: org.gradle.api.internal.initialization.DefaultScriptHandler@331715c4
childProjects: {lib1=project ':lib1', lib2=project ':lib2', lib3=project ':lib3'}
class: class org.gradle.api.internal.project.DefaultProject_Decorated
classLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@b2ab080
components: SoftwareComponentInternal set
configurationActions: org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@58adb8e3
configurationTargetIdentifier: org.gradle.configuration.ConfigurationTargetIdentifier$1@4b881866
configurations: configuration container
convention: org.gradle.internal.extensibility.DefaultConvention@403a9de6
crossProjectModelAccess: org.gradle.api.internal.project.DefaultCrossProjectModelAccess@1eca8bd1
defaultArtifacts: extension 'defaultArtifacts'
defaultTasks: []
deferredProjectConfiguration: org.gradle.api.internal.project.DeferredProjectConfiguration@2b15424b
dependencies: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@20553467
dependencyLocking: org.gradle.internal.locking.DefaultDependencyLockingHandler_Decorated@34145826
dependencyMetaDataProvider: org.gradle.internal.service.scopes.ProjectScopeServices$ProjectBackedModuleMetaDataProvider@7eca
c976
depth: 0
description: null
detachedState: false
displayName: root project 'GradleTest'
distributions: Distribution container
distsDirName: distributions
distsDirectory: extension 'base' property 'distsDirectory'
docsDir: D:\develop\ideaWorkspace\GradleTest\build\docs
docsDirName: docs
executableDir: bin
ext: org.gradle.internal.extensibility.DefaultExtraPropertiesExtension@7fccdbfe
extensions: org.gradle.internal.extensibility.DefaultConvention@403a9de6
fileOperations: org.gradle.api.internal.file.DefaultFileOperations@76332e6c
fileResolver: org.gradle.api.internal.file.BaseDirFileResolver@60709de4
gradle: build 'GradleTest'
group: org.example
identityPath: :
inheritedScope: org.gradle.internal.extensibility.ExtensibleDynamicObject$InheritedDynamicObject@48d979e5
internalStatus: property(java.lang.Object, fixed(class java.lang.String, integration))
java: extension 'java'
javaToolchains: extension 'javaToolchains'
layout: org.gradle.api.internal.file.DefaultProjectLayout@51d3582b
libsDirName: libs
libsDirectory: extension 'base' property 'libsDirectory'
listenerBuildOperationDecorator: org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator@3e7c4c33
logger: org.gradle.internal.logging.slf4j.OutputEventListenerBackedLogger@5a8769a5
logging: org.gradle.internal.logging.services.DefaultLoggingManager@59922541
mainClassName: com.szc.Main
model: project :
modelIdentityDisplayName: null
modelRegistry: org.gradle.model.internal.registry.DefaultModelRegistry@12cb3c58
name: GradleTest
normalization: org.gradle.normalization.internal.DefaultInputNormalizationHandler_Decorated@4e0af7e6
objects: org.gradle.api.internal.model.DefaultObjectFactory@2fa165c3
owner: project :
parent: null
parentIdentifier: null
path: :
pluginContext: false
pluginManager: org.gradle.api.internal.plugins.DefaultPluginManager_Decorated@67d1e55b
plugins: [org.gradle.api.plugins.HelpTasksPlugin@2cb33c05, org.gradle.buildinit.plugins.BuildInitPlugin@359f4bb2, org.gradle
.buildinit.plugins.WrapperPlugin@11b4afbf, org.gradle.language.base.plugins.LifecycleBasePlugin@79a76bef, org.gradle.api.plu
gins.BasePlugin@4c4133ca, org.gradle.api.plugins.JvmEcosystemPlugin@3cc232b, org.gradle.api.plugins.ReportingBasePlugin@37b1
bdba, org.gradle.api.plugins.JavaBasePlugin$Inject@758b40b0, org.gradle.api.plugins.JavaPlugin@3011f2a8, org.gradle.api.dist
ribution.plugins.DistributionPlugin@52a65afa, org.gradle.api.plugins.ApplicationPlugin@68c06179]
processOperations: org.gradle.process.internal.DefaultExecActionFactory$DecoratingExecActionFactory@47612211
project: root project 'GradleTest'
projectConfigurator: org.gradle.api.internal.project.BuildOperationCrossProjectConfigurator@785a1ce7
projectDir: D:\develop\ideaWorkspace\GradleTest
projectEvaluationBroadcaster: ProjectEvaluationListener broadcast
projectEvaluator: org.gradle.configuration.project.LifecycleProjectEvaluator@184bf89c
projectPath: :
properties: {...}
providers: org.gradle.api.internal.provider.DefaultProviderFactory_Decorated@73eb8945
publicType: org.gradle.api.plugins.BasePluginConvention
reporting: extension 'reporting'
reportsDir: D:\develop\ideaWorkspace\GradleTest\build\reports
repositories: repository container
resources: org.gradle.api.internal.resources.DefaultResourceHandler@3dd44c83
rootDir: D:\develop\ideaWorkspace\GradleTest
rootProject: root project 'GradleTest'
rootScript: false
script: false
scriptHandlerFactory: org.gradle.api.internal.initialization.DefaultScriptHandlerFactory@1541c2fa
scriptPluginFactory: org.gradle.configuration.ScriptPluginFactorySelector@520947d6
serviceRegistryFactory: org.gradle.internal.service.scopes.ProjectScopeServices$$Lambda$971/632597627@7d074d73
services: ProjectScopeServices
sourceCompatibility: 1.8
sourceSets: SourceSet container
standardOutputCapture: org.gradle.internal.logging.services.DefaultLoggingManager@59922541
state: project state 'EXECUTED'
status: integration
subprojects: [project ':lib1', project ':lib2', project ':lib3', project ':lib1:lib1_1', project ':lib1:lib1_2']
targetCompatibility: 1.8
taskThatOwnsThisObject: null
tasks: task set
test: task ':test'
testReportDir: D:\develop\ideaWorkspace\GradleTest\build\reports\tests
testReportDirName: tests
testResultsDir: D:\develop\ideaWorkspace\GradleTest\build\test-results
testResultsDirName: test-results
version: 1.0

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

任务的属性也可以在创建好后动态指定或修改:

B.dependsOn("A")
B.description = "This is a simple Task, depending on Task A"
B.group = "demo"

任务类型

在这里插入图片描述
官方文档
比如,定义一个删除build目录的任务,类型为Delete任务:

tasks.create("myDel", Delete) {
    delete buildDir
}
myDel.group("demo")

我们还可以自定义任务类型,并指定任务体,如下所示:

class MyTask extends DefaultTask { // 继承自DefaultTask
    @TaskAction // 定义任务体
    def execute() {
        println("One MyTask is executing...")
    }
}

def mt1 = task "mt1"(type: MyTask) // 实例化该类型的任务
// 设置doFirst和doLast
mt1.doFirst {
    println("Before executing mt1")
}

mt1.doLast {
    println("After executing mt2")
}

执行效果:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle mt1

> Configure project :
executing Task1....

> Task :mt1
Before executing mt1
One MyTask is executing...
After executing mt2

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

任务的执行顺序

Gradle提供了三种指定任务顺序的方式:dependsOn依赖、Task输入输出和通过API指定,参见官方文档

动态分配任务

比如在循环中注册任务:

5.times {
    counter -> {
        tasks.register("task$counter") {
            it.doLast {
                println "Task No.$counter"
            }
        }
    }
}

注册的任务只有在真正执行它的时候才会被创建,然后我们给这些任务设置依赖关系:

tasks.named("task0") {
    dependsOn("task1", "task3")
}

task0的执行效果:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle task0

> Configure project :
executing Task1....

> Task :task1
Task No.1

> Task :task3
Task No.3

> Task :task0
Task No.0

BUILD SUCCESSFUL in 2s
3 actionable tasks: 3 executed

任务的开启与关闭

通过设置enable属性即可:

5.times {
    counter -> {
        tasks.register("task$counter") {
            it.doLast {
                println "Task No.$counter"
            }


            if (counter == 3) {
                it.enabled = false
            } else {
                it.enabled(true)
            }
        }
    }
}

人物的开启或关闭不影响依赖者的执行,还是上面的task0依赖于task1和task3的例子:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle task0

> Configure project :
executing Task1....

> Task :task1
Task No.1

> Task :task0
Task No.0

BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed

任务的超时

通过timeout属性设置:

task "t0" {
    doLast {
        Thread.sleep(1000)
        println "after t0 is executed"
    }

    timeout = Duration.ofMillis(100)
}

task "t1" {
    doLast {
        println "after t1 is executed"
    }
}

上例中,t0的超时时间为100毫秒,但t0的doLast会先阻塞1000毫秒,因此执行t0时,t0会报异常,同时如果后面还有任务,则也不能被执行:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle t0 t1

> Configure project :
executing Task1....

> Task :t0 FAILED
Requesting stop of task ':t0' as it has exceeded its configured timeout of 100ms.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':t0'.
> Timeout has been exceeded

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --sc
an to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
1 actionable task: 1 executed

但是,加上--continue参数,t1就依旧会执行,即使前驱报了异常:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle t0 t1 --continue

> Configure project :
executing Task1....

> Task :t0 FAILED
Requesting stop of task ':t0' as it has exceeded its configured timeout of 100ms.

> Task :t1
after t1 is executed

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':t0'.
> Timeout has been exceeded

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --sc
an to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
2 actionable tasks: 2 executed

但如果t1依赖于t0,则上述方法失效。

任务的查找

根据任务名查找(只支持在当前项目中查找任务):

tasks.findByName("task0").doFirst {
    println "Before task0 1"
}
tasks.findByName("task0").doFirst {
    println "Before task0 2"
}

根据任务的相对路径查找:

tasks.findByPath(":task0").doLast {
    println "After task0 1"
}

执行效果:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle task0

> Configure project :
executing Task1....

> Task :task1
Task No.1

> Task :task0
Before task0 2
Before task0 1
Task No.0
After task0 1

BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed

任务的规则

通过tasks.addRule()函数可以添加任务规则,比如任务不存在时,输出任务名,而非报错:

tasks.addRule("规则1") {
    String taskName -> task(taskName){
        doLast {
            println "$taskName does not exist!"
        }
    }
}

执行某个不存在的任务时,该任务的任务名会作为taskName参数传入闭包,从而新建一个以该名字命名的任务,执行task(taskName)后面的默认闭包函数,比如:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle tttt task0

> Configure project :
executing Task1....

> Task :tttt
tttt does not exist!

> Task :task1
Task No.1

> Task :task0
Before task0 2
Before task0 1
Task No.0
After task0 1

BUILD SUCCESSFUL in 2s
3 actionable tasks: 3 executed

任务的onlyIf断言

onlyIf断言里的闭包返回true时,才会执行任务,例如:

task "test_onlyIf" {
    doLast {
        println "After executing test_onlyIf"
    }

    onlyIf {
        project.hasProperty("flag")
    }
}

不使用flag参数运行该任务:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle test_onlyIf

> Task :test_onlyIf
After executing test_onlyIf

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

使用flag参数运行该任务,但我这里一直能执行,说明断言没生效,不知为何:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle test_onlyIf -Pflag

> Task :test_onlyIf
After executing test_onlyIf

BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

默认任务

通过defaultTasks指定默认任务:

defaultTasks("d1", "d2")

task("d1") {
    doLast {
        println "After executing d1"
    }
}

task("d2") {
    doLast {
        println "After executing d2"
    }
}

task("d3") {
    doLast {
        println "After executing d3"
    }
}

其中d1和d2是默认任务,我们运行gradle看一下效果:

(base) PS D:\develop\ideaWorkspace\GradleTest> gradle

> Task :d1
After executing d1

> Task :d2
After executing d2

BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值