Make writing a habit together! This is the 5th day of my participation in the “Dig gold Day New Plan · April More Text Challenge”

Introduction to Gradle

1. Full name of DSL

​ Domain Special Language

2. Gradle directory listing
D: gradle initialization script directory lib: related libraries LICENSE: media: some icon resources NOTICE: Samples: samples SRC: source filesCopy the code
3. Linux configures environment variables
-[3.1] Edit ~/. Bashrc file GRADLE_HOME=/home/liubo/*** PATH=${PATH}:${GRADLE_HOME}/bin Export GRADLE_HOME PATH 3.2 Enter source on the ue ~/.bashrc Note: If you want all users to use Gradle, you need to add the above content to /etcc/profile and restart your computerCopy the code
4, Gradle Wrapper
Parameter names instructions
–gradle-version Used to specify the Gradle version to use
–gradle-distribution-url Use to specify the URL to download the Gradle distribution

Method of use

gradle wrapper --gradle-version 2.4	
Copy the code

gradle-wrapper.properties

The field name instructions
distributionBase The home directory of the downloaded Gradle compressed package
distributionPath The path to the decompressed Gradle compressed package relative to distributionBase
zipStoreBase The same distributionBase, except for the zip package
zipStorePath The same distributionPath, except for the zip package
distributionUrl Gradle distribution zip download address
5. Customize the Wrapper Task

Gradle-wrapper. properties is generated by the Wrapper Task. We can also customize the Wrapper Task to generate this file. Add the following code to the build.gradle file

task wrapper(type:Wrapper){
	gradleVersion = '2.4'
	archiveBase = 'GRADLE_USER_HOME'
	archivePath = 'wrapper/dists'
	distributionBase = 'GRADLE_USER_HOME'
	distributionPath = 'wrapper/dists'
	distributionUrl = 'http\://services.gradle.org/distributions/gradle-2.4-all.zip'
}
Copy the code
6. Gradle logs
level Used for
ERROR The error message
QUIET Important message
WARNING A warning message
LIFECYCLE Progress of the news
INFO Information message
DEBUG Debug messages

Use the sample

gradle -i tasks

Without options LIFECYCLE and higher log levels will be output.

Error stack switch option

Command line options Used for
There is no option No stack output
-s/–stacktrace Outputs critical stack information
-S/–full-stacktrace Output all stack information

It is generally recommended to use -s rather than -s because -s is compact and readable

6. Debug using log information

​ println

println 'Output a log message'
Copy the code

The built-in Logger outputs different levels of logs

logger.error('Message')
logger.quiet('Message')
logger.lifecycle('Message')
logger.info('Message')
logger.debug('Message')
Copy the code
Gradle command line

help

./gradlew -?

./gradlew -h

./gradlew -help

View all the tasks

tasks

Gradle Help task

./gradlew help –task

The sample

./gradlew help –task tasks

You can display help information for tasks

Force refresh dependency

./gradlew –refresh-dependencies assemble

8. Multi-tasking calls

To run multiple tasks, only __ Spaces are needed to separate them

For example, clean the JAR before executing it

./gradlew clean jar

9. Use the task name abbreviation

When the task name is long, it can be called using an abbreviation based on camel’s nomenclature

./gradlew connectCheck

It can be abbreviated to

./gradlew cc

Groovy based

1. String

Single quotes do not support the __ interpolation __ operation on strings.

task printStringVar << {
    def name = "Zhang"
    
    println ${name}' ${name}'
    println ${name} ${name}
}
Copy the code

/gradlew printStringVar

${name}

Variable calculation in double quotes: triple

__ Note: If __ has only one variable, {} can be omitted, as in $name

2,

List

task printList << {
    def numList = [1.2.3.4.5.6.7.8.9.0]

    println numList[1]// Access the second element
    println numList[- 1]// Access the last element
    println numList[2 -]// Access the penultimate element
    println numList[1.3.]// Access the second through fourth elements

    / / traverse
    numList.each {
        println it
    }
}
Copy the code

Map

task printMap << {
    def map1 = ['width':1024.'height':768]
    
    println map1['width']
    println map1.height
    
    map1.each {
        println "key = ${it.key}, value = ${it.value}"}}Copy the code

Groovy also provides convenient methods like Collect, find, and findAll for collections.

3, the method
3.1. Parentheses can be omitted
task invokeMethod << {
    method1(1.2)
    // Can also be written as
    method1 1.2
}
Copy the code
3.2. Return may not be written

Groovy returns the last line of code during method execution

3.3, code blocks can be passed as arguments –> closures
numList.each ( {println it} )

//Groovy specifies that if the last argument to a method is a closure, it can be placed outside the method
numList.each(){
    println it
}

// The parentheses can also be omitted
numList.each {
    println it
}
Copy the code
4, JavaBean
5. Closure

The sample

task helloClosure << {
    
    customEach {
        println it
    }
}

def customEach (closure) {
    for(int i = 0; i < 10; i ++ ){
        closure(i)
    }
}
Copy the code
6, DSL

Domain Specific Language

Domain Specific Languages by Martin Fowler

Gradle build script basics

1. Setting file

Gradle is a setup file in the root directory of the project. By default, setting.gradle is used for initialization and configuration of the project tree

The sample

rootProject.name = 'android-gradle-book-code'

Chapter 1 project Example definition
include ':example02'
project(':example02').projectDir = new File(rootDir, 'chapter01/example02')

include ':example03'
project(':example03').projectDir = new File(rootDir, 'chapter01/example03')
Copy the code
2. Build file

Build. Gradle file in the Project root directory,

3. Projects and Tasks
  • Project is a standalone module

  • A Task is an operation, an atomic operation. The equivalent of Target in Ant and goal in Maven;

4. Create a task

The method prototype is

create(String name, Closure configureClosure)
Copy the code
task customTask1 {
    doFirst {
        println 'customTask1: doFirst'
    }
    
    doLast {
        println 'customTask1: doLast'}}// It can also be written as follows
tasks.create('customTask2') {
    doFirst {
        println 'customTask2: doFirst'
    }
    
    doLast {
        println 'customTask2: doLast'}}Copy the code
5. Task dependence
task task1 << {
   doLast {
        println 'task1'
    }
}

task task2 << {
    doLast {
        println 'task2'}}// Single dependency
task task3 (dependsOn: task1) {
    doLast {
        println 'task3'}}// Multiple task dependencies
task multiTask {
    dependsOn task1,task2
    
    doLast {
        println 'multiTask'}}Copy the code
6. Tasks are controlled and interact with each other through API
7. Customize attributes

Both Project and Task allow you to add custom attributes, and additional attributes can be added by applying the corresponding Ext attribute.

// Define a Project attribute
ext.age = 18

// Use code blocks to customize multiple attributes
ext {
    phone = 13212345678
    address = 'Beijing'
}
Copy the code

The same applies to SourceSet

sourceSets.all {
    ext.resourceDir = null
}

sourceSets {
    main {
        resourceDir = 'main/res'
    }
    
    test {
        resourceDir = 'main/res'}}Copy the code
Scripts are code and code is script

Gradle task

1. Create tasks in multiple ways
1.1 Creating a Task using a Task name
def Task createTask1 = task(createTask1)

createTask1.doLast {
    println 'createTask1'
}
Copy the code

This method is created by calling methods in the Project object

task(String name) throws InvalidUserDataException
Copy the code
1.2, create a task with a task name + a Map object configured for the task
def Task createTask2 = task(createTask2, group: BasePlugin.BUILD_GROUP)

createTask2.doLast {
    println 'createTask2'
}
Copy the code

This method is created by calling methods in the Project object

Task task(Map
       
         args, String name)
       ,> throws InvalidUserDataException
Copy the code

The configurations available in Map are as follows

Configuration items describe The default value
type Based on an existing Task, similar to class inheritance DefaultTask
overwrite Whether to replace an existing Task with type false
dependsOn Used to configure the dependencies of the task []
action An Action or closure added to a task null
description Task Description null
group Grouping of tasks null
1.3 Task name + Closure
task createTask3 {
    description 'Demo Task Creation'
    
    doLast {
        println 'createTask3'}}Copy the code

This method is created by calling methods in the Project object

Task task(String name, Closure configureClosure)
Copy the code
1.4 Task name + Map parameter + closure

Each of these methods ends up calling the Create method of the TaskContainer object

2. Multiple ways to access tasks
2.1, by accessing collection elements
task tempTask

tasks['tempTask'].doLast {
    println 'tempTask.doLast'
}
Copy the code

This method actually calls

tasks.getAt('tempTask')
// findByName(String name)
Copy the code
2.2. Access by path (Get and find)
task tempTask
tasks['tempTask'].doLast {
    println tasks.findByName(':parentPath:tempTask')
    println tasks.getByName(':parentPath:tempTask')
    println tasks.findByName(':parentPath:bbbb')}Copy the code

The difference between get and find is that “UnknownTaskException” is thrown when the task cannot be found. Find returns null if the task is not found

2.3. Access by Name (Get and find)
task tempTask
tasks['tempTask'].doLast {
    println tasks.findByName('tempTask')
    println tasks.getByName('tempTask')}Copy the code
  • The difference between get and find is as above;
  • The differences between method 2 and Method 3 are as follows: For path access, the parameter value can be a task path or a task name. When accessing by name, the parameter value must be the task name.
3. Task grouping and description
4, the << operator

On Gradle tasks is the short tag form of doLast methods.

parsing

<< corresponds to the leftShift method in Gradle source code.

This method internally calls actions.add()

5. Task execution analysis
def Task myTask = task ex45CustomTask(type: CustomTask)
myTask.doFirst{
    println 'Execute in doFirst before Task execution'
}
myTask.doLast{
    println 'Execute in doLast after Task execution'
}

class CustomTask extends  DefaultTask {
	/ / Task method is used to create a Task, Gradle will parse with TaskAction tagging method as the Action of its execution, and then through prependParallelSafeAction method add the Action to the actions List
    @TaskAction
    def doSelf() {
        println 'Task itself is executing in doSelf'}}Copy the code
6. Task sequencing
  • shouldRunAfter

    TaskB. ShouldRunAfter (taskA) indicates that taskB should be executed after taskA, but it is possible that the task order will not be executed as preset;

  • mustRunAfter

    Taskb.shouldrunafter (taskA) indicates that taskB must be executed after taskA

7. Enable and disable tasks

Task has a enabled attribute that enables and disables tasks. The default value is true, indicating that tasks are enabled.

task tempTask << {
    println 'tempTask'
}

ex47DisenabledTask.enabled =false
Copy the code
8. OnlyIf assertion for the task

An assertion is a conditional expression that takes a closure as an argument, and if the closure returns true, the task executes, otherwise skip.

The sample

final String BUILD_APPS_ALL="all";
final String BUILD_APPS_SHOUFA="shoufa";
final String BUILD_APPS_EXCLUDE_SHOUFA="exclude_shoufa";

task ex48QQRelease << {
    println "Hit app Treasure bag"
}
task ex48BaiduRelease << {
    println "Pack baidu"
}
task ex48HuaweiRelease << {
    println "Bag huawei"
}

task ex48MiuiRelease << {
    println "Bag for Miui."
}

task build {
    group BasePlugin.BUILD_GROUP
    description "Channel package"
}

build.dependsOn ex48QQRelease,ex48BaiduRelease,ex48HuaweiRelease,ex48MiuiRelease

ex48QQRelease.onlyIf {
    def execute = false;
    if(project.hasProperty("build_apps")){
        Object buildApps = project.property("build_apps")
        if(BUILD_APPS_SHOUFA.equals(buildApps)
            || BUILD_APPS_ALL.equals(buildApps)){
            execute = true
        }else{
            execute = false}}else{
        execute = true
    }
    execute
}

ex48BaiduRelease.onlyIf {
    def execute = false;
    if(project.hasProperty("build_apps")){
        Object buildApps = project.property("build_apps")
        if(BUILD_APPS_SHOUFA.equals(buildApps)
                || BUILD_APPS_ALL.equals(buildApps)){
            execute = true
        }else{
            execute = false}}else{
        execute = true
    }
    execute
}

ex48HuaweiRelease.onlyIf {
    def execute = false;
    if(project.hasProperty("build_apps")){
        Object buildApps = project.property("build_apps")
        if(BUILD_APPS_EXCLUDE_SHOUFA.equals(buildApps)
                || BUILD_APPS_ALL.equals(buildApps)){
            execute = true
        }else{
            execute = false}}else{
        execute = true
    }
    execute
}

ex48MiuiRelease.onlyIf {
    def execute = false;
    if(project.hasProperty("build_apps")){
        Object buildApps = project.property("build_apps")
        if(BUILD_APPS_EXCLUDE_SHOUFA.equals(buildApps)
                || BUILD_APPS_ALL.equals(buildApps)){
            execute = true
        }else{
            execute = false}}else{
        execute = true
    }
    execute
}

Copy the code

The package command is as follows

# Hit all channel packages./gradlew :moduleApp:build
./gradlew -Pbuild_apps=all :moduleApp:Build # type the first package./gradlew -Pbuild_apps=shoufa :moduleApp:/gradlew -Pbuild_apps=exclude_shoufa :moduleApp:build
Copy the code

Remark:

-p in the command means to specify an attribute key-value pair for Project in k-V format, using the format -pk =V

9. Task rules

Gradle plug-in

1. The role of plug-ins
  • Add tasks to the project, such as testing, compiling, and packaging.
  • Add a dependency configuration to the project;
  • Add new extension properties and methods to existing objects in the Project to help us configure and optimize the build. For example, the Android {} configuration block is an extension of the Android Gradle plugin for the Project object.
  • For example, if the Java plug-in is applied, SRC /main/ Java is where the source code is stored.