Android 工具命令——Gradle学习day1基本的gradle命令

https://rainmonth.github.io/posts/A191994.html

摘要

通过本文,记录下gradle最基本的命令讲解。如创建gradle项目的方法、gradle基本命令以及gradle里面的基本概念等。

[TOC]

创建一个gradle项目

通过gradle init 命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
cd /Documents
mkdir gradle-demo1
cd gradle-demo1
# 工作目录准备完毕
# 输入gradle init
gradle init
# 会有如下输出:
Select type of project to generate:
1: basic
2: groovy-application
3: groovy-library
4: java-application
5: java-library
6: kotlin-application
7: kotlin-library
8: scala-library
Enter selection (default: basic) [1..8]

Select build script DSL:
1: groovy
2: kotlin
Enter selection (default: groovy) [1..2]

Project name (default: gradle-demo):
BUILD SUCCESSFUL in 1m 0s
2 actionable tasks: 2 executed

上面输出提示已经很清楚了,如果不想选择直接按enter

这样一个名为gradle-demo的项目就新建完成了,项目结构如下:

1
2
3
4
5
6
7
8
├── build.gradle  
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle

常用命令

  • 通过./gradlew tasks来查看Task,
  • 通过./gradlew properties来查看项目的基础属性
  • 通过./gradlew 具体Task名 --scan 可以在gradle提供调试网站上查看task运行的具体信息

常用option

首先,gradle有众多的option,可以输入gradle —help查看具体帮助,而且都有详细的解释说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
USAGE: gradle [option...] [task...]

-?, -h, --help Shows this help message.
-a, --no-rebuild Do not rebuild project dependencies.
-b, --build-file Specify the build file.
--build-cache Enables the Gradle build cache. Gradle will try to reuse outputs from previous builds.
-c, --settings-file Specify the settings file.
--configure-on-demand Configure necessary projects only. Gradle will attempt to reduce configuration time for large multi-project builds. [incubating]
--console Specifies which type of console output to generate. Values are 'plain', 'auto' (default), 'rich' or 'verbose'.
--continue Continue task execution after a task failure.
-D, --system-prop Set system property of the JVM (e.g. -Dmyprop=myvalue).
-d, --debug Log in debug mode (includes normal stacktrace).
--daemon Uses the Gradle Daemon to run the build. Starts the Daemon if not running.
--foreground Starts the Gradle Daemon in the foreground.
-g, --gradle-user-home Specifies the gradle user home directory.
-I, --init-script Specify an initialization script.
-i, --info Set log level to info.
--include-build Include the specified build in the composite.
-m, --dry-run Run the builds with all task actions disabled.
--max-workers Configure the number of concurrent workers Gradle is allowed to use.
--no-build-cache Disables the Gradle build cache.
--no-configure-on-demand Disables the use of configuration on demand. [incubating]
--no-daemon Do not use the Gradle daemon to run the build. Useful occasionally if you have configured Gradle to always run with the daemon by default.
--no-parallel Disables parallel execution to build projects.
--no-scan Disables the creation of a build scan. For more information about build scans, please visit https://gradle.com/build-scans.
--offline Execute the build without accessing network resources.
-P, --project-prop Set project property for the build script (e.g. -Pmyprop=myvalue).
-p, --project-dir Specifies the start directory for Gradle. Defaults to current directory.
--parallel Build projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use.
--priority Specifies the scheduling priority for the Gradle daemon and all processes launched by it. Values are 'normal' (default) or 'low' [incubating]
--profile Profile build execution time and generates a report in the <build_dir>/reports/profile directory.
--project-cache-dir Specify the project-specific cache directory. Defaults to .gradle in the root project directory.
-q, --quiet Log errors only.
--refresh-dependencies Refresh the state of dependencies.
--rerun-tasks Ignore previously cached task results.
-S, --full-stacktrace Print out the full (very verbose) stacktrace for all exceptions.
-s, --stacktrace Print out the stacktrace for all exceptions.
--scan Creates a build scan. Gradle will emit a warning if the build scan plugin has not been applied. (https://gradle.com/build-scans)
--status Shows status of running and recently stopped Gradle Daemon(s).
--stop Stops the Gradle Daemon if it is running.
-t, --continuous Enables continuous build. Gradle does not exit and will re-execute tasks when task file inputs change.
--update-locks Perform a partial update of the dependency lock, letting passed in module notations change version. [incubating]
-v, --version Print version info.
-w, --warn Set log level to warn.
--warning-mode Specifies which mode of warnings to generate. Values are 'all', 'summary'(default) or 'none'
--write-locks Persists dependency resolution for locked configurations, ignoring existing locking information if it exists [incubating]
-x, --exclude-task Specify a task to be excluded from execution.

Task相关

task的特点

其实gradle中Task相关的定义都在AbstractTask.java这个类中有定义,如常见的:

doFirst、doLast、dependsOn等

几点说明:

  • lazy dependsOn,即被依赖的task无需提前声明

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    task taskA {
    dependsOn 'taskB'
    doLast {
    println 'taskA'
    }
    }

    task taskB {
    doLast {
    println 'taskB'
    }
    }

    上面演示的就是taskA依赖于taskB,但taskB的声明在taskA之后

  • dynamic Tasks,即可以动态的添加Tasks

    1
    2
    3
    4
    5
    6
    7
    8
    9
    task dynamicTasks {
    4.times { counter ->
    task "task$counter" {
    doLast {
    println "I'm task number $counter"
    }
    }
    }
    }

    上面的dynamicTasks运行后,会生成4个task,分别是task0、task1、task2、task3,且都可以单独运行

task的定义与创建

task有如下可以用如下几种方式定义与创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 方式1
task taskName {
doLast {
...
}
}
#方式2
task('taskname') {
doLast {
...
}
}
#方式3
task('copy', type: Copy) {
from(file('srcDir'))
into(buildDir)
}
#方法4 采用task 容器
tasks.create('hello') {
doLast {
...
}
}
tasks.create('copy', Copy) {
doLast {
...
}
}

task的访问与获取

可以采用以下方法访问task

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#方式1 通过Project的属性来访问
task hello
task copy(type: Copy)

println hello.name(or println project.hello.name)
println copy.destinationDir(or println project.copy.destinationDir)

#方式2 通过task container

println tasks.hello.name
println tasks.named('hello').get().name

println tasks.copy.destinationDir
pringln tasks.named('copy').get().destinationDir

#方式3 通过task container的getByPath(param)方法 param 可以穿task的名称、task的相对路径或者task的绝对路径
project(':projectA') {
task hello
}

task hello

println tasks.getByPath('hello').path
println tasks.getByPath(':hello').path
println tasks.getByPath('projectA:hello').path
println tasks.getByPath(':projectA:hello').path

task的配置

先创建一个没有默认行为的copy task

1
task myCopy(type: Copy)
  1. 使用gradle提供的Api配置

    1
    2
    3
    4
    Copy myCopy = tasks.getByName("myCopy")
    myCopy.from 'resources'
    myCopy.info 'target'
    myCopy.include('**/*.txt', '**/*.xml', '**/*.properties')

    将resources目录下面所有以.txt、.xml、.properties结尾的文件拷贝到target目录

  2. 使用DSL规范语法来配置

    1
    2
    3
    4
    5
    6
    7
    myCopy {
    from 'resources'
    into 'target'
    # 直接添加到这里也可以
    # include('**/*.txt', '**/*.xml', '**/*.properties')
    }
    myCopy.include('**/*.txt', '**/*.xml', '**/*.properties')

向task的构造函数中传参

这里遇到了点问题,直接在demo中添加@Inject注解时找不到

task的操作

这里的操作主要是指task的提供的一些API操作

动态添加依赖

1
2
3
4
5
6
7
8
9
4.times { counter ->
task "task$counter" {
doLast {
println "I'm task number $counter"
}
}
}
# task 0 依赖于task2和task3的运行
task0.dependsOn task2, task3

此时运行task0,会先运行task2和task3,在运行task0

动态添加某些行为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
task hello {
doLast {
println 'Hello doLast'
}
}
hello.doFirst {
println 'Hello doFirst'
}
hello.configure {
doLast {
println "Hello doLast by configure first time"
}
}
hello.configure {
doLast {
println 'Hello doLast by configure second time'
}
}

注意doFirst执行在doLast之前,多个doLast执行循序按其在加入Action列表的循序执行

快捷的获取task的属性

在一个task中可以很方便的获取另一个已经定义好的task的属性

1
2
3
4
5
task anotherHello {
doLast {
println "another hello got hello task's name, is $hello.name"
}
}

注意这里要用双引号

为task添加属性

可以为一个task添加自定义属性

1
2
3
4
5
6
7
8
task myTask {
ext.myProperty = "myValue"
}
task printTaskProperties {
doLast {
println myTask.myProperty
}
}

task的额外属性的添加是没有限制的,只要你想,你可以添加任意多的自定义属性