[Gradle-5] Gradle common commands and parameters

1 Introduction

There are many Gradle commands. After being familiar with common commands, it can not only improve efficiency in daily development, but also help us quickly locate and solve compilation problems; and in some cases, the compilation results of command line (CLI) and button execution are different. The same, for example, you need to pass parameters (-P) when building, so I will just come up with an explanation, I hope it will be helpful to you~

1. Gradle command

1.1、gradlew

The Gradle execution command line is mainly used Gradle Wrapperfor the introduction of the Gradle Wrapper, which was introduced in the previous article ( [Gradle-2] understand the Gradle configuration in the article ), so I won’t go into details here.
So what we commonly use ./gradlew(Mac), gradlew is the abbreviation of Gradle Wrapper.

Gradle Wrapper workflow:
wrapper-workflow.png
Let's look at the next gradlewscript content

#!/usr/bin/env sh

#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

##############################################################################
##
##  Gradle start up script for UN*X
##
##############################################################################

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG=`dirname "$PRG"`"/$link"
    fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn () {
    
    
    echo "$*"
}

die () {
    
    
    echo
    echo "$*"
    echo
    exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
  NONSTOP* )
    nonstop=true
    ;;
esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar


# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`

    JAVACMD=`cygpath --unix "$JAVACMD"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option

        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
        else
            eval `echo args$i`="\"$arg\""
        fi
        i=`expr $i + 1`
    done
    case $i in
        0) set -- ;;
        1) set -- "$args0" ;;
        2) set -- "$args0" "$args1" ;;
        3) set -- "$args0" "$args1" "$args2" ;;
        4) set -- "$args0" "$args1" "$args2" "$args3" ;;
        5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
        6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
        7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
        8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
        9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
    esac
fi

# Escape application args
save () {
    
    
    for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
    echo " "
}
APP_ARGS=`save "$@"`

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"

exec "$JAVACMD" "$@"

The amount of code is not much, gradlew mainly does a few things:

  1. Obtain information about the computer system kernel, JRE environment information, etc.;
  2. Set the classpath path;
  3. Execute the java command tool and call the class file of the gradle jar package;

1.2, Command Encyclopedia

When we want to know what commands a tool has, the easiest and most direct way is to use helpcommands to see which ones are supported, and then find what we want.
implement:

 ./gradlew --help

output:

USAGE: gradlew [option...] [task...]

-?, -h, --help                     Shows this help message.
-a, --no-rebuild                   Do not rebuild project dependencies.
-b, --build-file                   Specify the build file. [deprecated]
--build-cache                      Enables the Gradle build cache. Gradle will try to reuse outputs from previous builds.
-c, --settings-file                Specify the settings file. [deprecated]
--configuration-cache              Enables the configuration cache. Gradle will try to reuse the build configuration from previous builds. [incubating]
--configuration-cache-problems     Configures how the configuration cache handles problems (fail or warn). Defaults to fail. [incubating]
--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.
--export-keys                      Exports the public keys used for dependency verification.
-F, --dependency-verification      Configures the dependency verification mode. Values are 'strict', 'lenient' or 'off'.
--foreground                       Starts the Gradle daemon in the foreground.
-g, --gradle-user-home             Specifies the Gradle user home directory. Defaults to ~/.gradle
-I, --init-script                  Specify an initialization script.
-i, --info                         Set log level to info.
--include-build                    Include the specified build in the composite.
-M, --write-verification-metadata  Generates checksums for dependencies used in the project (comma-separated list)
-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-configuration-cache           Disables the configuration cache. [incubating]
--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.
--no-watch-fs                      Disables watching the file system.
--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'
--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.
--refresh-keys                     Refresh the public keys used for dependency verification.
--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', 'fail', 'summary'(default) or 'none'
--watch-fs                         Enables watching the file system for changes, allowing data about the file system to be re-used for the next build.
--write-locks                      Persists dependency resolution for locked configurations, ignoring existing locking information if it exists
-x, --exclude-task                 Specify a task to be excluded from execution.

Shorthand:

./gradlew -// or
./gradlew -h

You can see that many commands have been listed in the above output, some of which may have been seen and some have not. The following will extract and explain the commonly used ones and classify them.

1.3. Command structure

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

Multiple tasks are separated by spaces.

2. Gradle-related

2.1. View Gradle version

There are two common ways to check the Gradle version.
The first is to check the gradle version download address directly under the gradle>wrapper>gradle-wrapper.properties file distributionUrl:

distributionUrl=https://services.gradle.org/distributions/gradle-7.4-bin.zip

The distributionUrl here means that the current gradle version is 7.4.

The second is to use the command line to view the current version.
implement:

 ./gradlew -version
// or
./gradlew -v

output:

------------------------------------------------------------
Gradle 7.4
------------------------------------------------------------

Build time:   2022-02-08 09:58:38 UTC
Revision:     f0d9291c04b90b59445041eaa75b2ee744162586

Kotlin:       1.5.31
Groovy:       3.0.9
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          11 (Oracle Corporation 11+28)
OS:           Mac OS X 10.16 x86_64

2.2. Upgrade Gradle

There are three common ways to upgrade Gradle.

The first one is to manually modify the version pointed to by distributionUrl under the wrapper.properties file, then manually modify the Android Gradle Plugin (AGP) version, and then resync.

The second is to open file>Project Structure to modify the versions of AGP and Gradle, and then apply.
project-structure.png

The third way is to use the command line (officially recommended, but it is also possible to upgrade with AS):

./gradlew wrapper --gradle-version 7.5.1

3. Compile command

3.1. Check dependencies and compile and package

./gradlew build

3.2. Compile and export the Debug package

./gradlew assembleDebug

3.3. Compile and print the Debug package and install it

./gradlew installDebug

3.4. Compile and print the Release package

./gradlew assembleRelease

3.5. Compile and print the Release package and install it

./gradlew installRelease

3.6, Debug/Release compile and print logs

./gradlew assembleDebug --info
// or
./gradlew assembleRelease --info

4. Clear command

Clear the artifacts under the build directory.

./gradlew clean

Equivalent to Build->Clean Project.

5. Uninstall command

5.1. Uninstall the Debug/Release installation package

./gradlew uninstallDebug
// or
./gradlew uninstallRelease

output:

Uninstalling com.yechaoa.gradlex (from app:debug) from device 'Pixel_5_API_31(AVD) - 12' (emulator-5554).
Uninstalled com.yechaoa.gradlex from 1 device.

5.2, adb uninstall

Execution in Android Studio is to directly uninstall the current project installation package, if it is executed by adb, it needs to be specified 包名.

adb uninstall com.yechaoa.gradlex  

6. Debug command

Debug commands are very useful when locating compilation problems.
When we encounter compilation errors, we often see this prompt:

* Try:
> Run gradle tasks to get a list of available tasks.
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

6.1. Compile and print the stack log

./gradlew assembleDebug --stacktrace
// or
./gradlew assembleDebug -s

Detailed version:

./gradlew assembleDebug --full-stacktrace
// or
./gradlew assembleDebug -S

6.2, log level

Sometimes there will be a lot of build logs, and what you see may not be complete, or even not a real compilation problem, and the build logs cannot be logcatvisually filtered like that. At this time, you need to use the log level to filter.

-q,--quiet
仅记录错误。

-w,--warn
将日志级别设置为警告。

-i,--info
将日志级别设置为信息。

-d,--debug
调试模式(包括正常的stacktrace)。

Example:

./gradlew assembleDebug -w

7. Task related

7.1, view the main Task

./gradlew tasks

7.2. View all Tasks

./gradlew tasks --all

7.3, execute Task

./gradlew taskName
// or
./gradlew :moduleName:taskName

At the same time, you can view the task of the project and module in the tool class Gradle on the right side of AS, and click to execute the corresponding task.
tasks.png

8. View dependencies

Many problems in compilation are errors caused by dependencies. Viewing dependencies can help us quickly locate the problem.

8.1. Check the dependencies in the root directory of the project

./gradlew dependencies

8.2. Check the dependencies under the app module

./gradlew app:dependencies

8.3. View dependency output to file

./gradlew app:dependencies > dependencies.txt

Example:
dependencies.png

9. Performance-related

9.1, offline compilation

./gradlew assembleDebug --offline

9.2, build cache

./gradlew assembleDebug --build-cache // 开启

./gradlew assembleDebug --no-build-cache // 不开启

9.3, configuration cache

./gradlew assembleDebug --configuration-cache // 开启

./gradlew assembleDebug --no-configuration-cache // 不开启

9.4. Parallel construction

./gradlew assembleDebug --parallel // 开启

./gradlew assembleDebug --no-parallel // 不开启

The above configurations of 9.1-9.4 can also be gradle.propertiesconfigured in .
Example:

#并行编译
org.gradle.parallel=true

#构建缓存
org.gradle.caching=true

9.5. Compile and output performance report

./gradlew assembleDebug --profile

The performance report is located GradleX/build/reports/profile/under the path of the build project

See the profiling report at: file:///Users/yechao/AndroidStudioProjects/GradleX/build/reports/profile/profile-2022-11-29-23-13-29.html

The output is an html file, open it with a browser:
profile.png

9.6. Compile and output a more detailed performance report

./gradlew assembleDebug --scan

The first execution requires email verification, authorization is enough, and the link can be opened after the work is done. scanThe report content is more detailed than the profile.
![[email protected]](https://img-blog.csdnimg.cn/img_convert/7d0d5d4979c18cda96ec4019fd19355c.png#averageHue=#f6f8f8&clientId=u1346de98-2630-4&errorMess age=unknown error&from=ui&id=u744d4ece&name=WX20210829-165838 @2x.png&originHeight=1346&originWidth=1948&originalType=binary&ratio=1&rotation=0&showTitle=false&size=297358&status=error&style=none&taskId=u70ac8499-768d-4807-b63d-36ccd9b2506 &title=)

10. Dynamic parameter passing

Let's introduce a more commonly used parameter passing attribute, --project-prop, we generally -Puse it to set the project attribute of the root project.

10.1. Obtain parameters

Example:

 ./gradlew assembleDebug -PisTest=true 

Here we use -P to pass a isTestfield and assign a value true.
So how to get this parameter in the code? Then write the following code in build.gradle:

if (hasProperty("isTest")){
    
    
    println("---hasProperty isTest yes")
}else {
    
    
    println("---hasProperty isTest no")
}

We can hasPropertyuse it to obtain the parameters of the command line (CLI), and modules or plug-ins can also be obtained in this way:

project.property('isTest')

Then we use the above command to compile and see the output:

➜  GradleX git:(master)./gradlew assembleDebug -PisTest=true 
---Gradle:开始初始化了
---Gradle:settingsEvaluated Settings对象评估完毕
---Gradle:projectsLoaded 准备加载Project对象了

> Configure project :
---Gradle:Projec beforeEvaluate Project开始评估,对象是 = GradleX
---hasProperty isTest yes //   --- 看这里 ---
---Gradle:Projec afterEvaluate Project评估完毕,对象是 = GradleX

> Configure project :app
---Gradle:buildFinished 构建结束了

You can see that it has been printed.

It's not over yet. It's good to get the parameters, but I haven't got the value of the parameters yet.

10.2. Get parameter value

We can getProperty()use to get:

if (hasProperty("isTest")) {
    
    
    println("---hasProperty isTest yes")
    if (Boolean.valueOf(getProperty('isTest'))) {
    
    
        println("---isTest true")
    } else {
    
    
        println("---isTest false")
    }
} else {
    
    
    println("---hasProperty isTest no")
}

Note that getProperty('isTest')single quotation marks are used here. In addition, the parameter values ​​​​in the command line are all objects, and the basic data types need to be converted, ie Boolean.valueOf(getProperty('isTest')).

10.3, custom operation

Ok, now we can do some custom operations on the obtained parameters, such as modifying our dependencies.
app>build.gradle:

dependencies {
    
    

    implementation 'androidx.core:core-ktx:1.7.0'

    if (project.hasProperty("isTest")) {
    
    
        println("---hasProperty isTest yes")
        if (Boolean.valueOf(getProperty('isTest'))) {
    
    
            println("---isTest true")

            implementation 'com.yechaoa.gradlex.devtools:devtools:1.1.1'

        } else {
    
    
            println("---isTest false")

            implementation 'com.yechaoa.gradlex.devtools:devtools:2.2.2'
        }
    } else {
    
    
        println("---hasProperty isTest no")
    }

    testImplementation 'junit:junit:4.13.2'
}

Here is an example, isTest=truewhen I relied on devtools version 1.1.1, and isTest=falsewhen I relied on devtools version 2.2.2.
In addition to dependencies in dependencies, plugins, tasks, etc. can also be customized by dynamically passing parameters.

11. Summary

This article introduces the knowledge related to the Gradle Command-Line Interface (CLI), such as debugging commands, viewing dependencies, performance-related, dynamic parameter passing, etc., which are still very useful in locating problems and improving efficiency. I hope it can bring you something to gain . (Don’t forget Sanlian, hey~)

12、Github

https://github.com/yechaoa/GradleX

13. Related documents

Guess you like

Origin blog.csdn.net/yechaoa/article/details/130305055