了解gradlew和gradle命令的区别之前,尝试花几分钟思考下面几个问题:
- gradlew是一个什么命令工具呢?
- 为什么要有这个工具?
- gradlew脚本是怎样的?
- gradlew命令和gradle命令的区别?
一、gradlew、gradle脚本的区别
先看看gradlew脚本代码
#!/usr/bin/env sh
PRG="$0"
# 1.检查是否是软连接
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=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# 2.获取系统内核信息
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
# 3.设置classpath路径
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, switch paths to Windows format before running java
if $cygwin ; 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=$((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"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
# 4.执行java命令运行wrapper jar包里头的类文件
exec "$JAVACMD" "$@"
代码量不多,脚本主要干了几件事:
获取电脑系统内核的信息,JRE环境信息等;
设置classpath路径;
执行java命令工具,调用gradle jar包的class文件
在gradlew脚本中添加log打印:
echo "$JAVACMD $@"
$ ./gradlew -v
/Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home/bin/java -Xdock:name=Gradle -Xdock:icon=/Users/cengfanwei/zengfw/ATrain/media/gradle.icns -Dorg.gradle.appname=gradlew -classpath /Users/cengfanwei/zengfw/ATrain/gradle/wrapper/gradle-wrapper.jar org.gradle.wrapper.GradleWrapperMain -v
从打印结果可知,最终其实是通过java命令执行gradle-wrapper.jar包的GradleWrapperMain类,再继续看看GradleWrapperMain干了什么事情...
public class GradleWrapperMain {
public static final String GRADLE_USER_HOME_OPTION = "g";
public static final String GRADLE_USER_HOME_DETAILED_OPTION = "gradle-user-home";
public static final String GRADLE_QUIET_OPTION = "q";
public static final String GRADLE_QUIET_DETAILED_OPTION = "quiet";
public static void main(String[] args)
throws Exception {
File wrapperJar = wrapperJar();
File propertiesFile = wrapperProperties(wrapperJar);
File rootDir = rootDir(wrapperJar);
CommandLineParser parser = new CommandLineParser();
parser.allowUnknownOptions();
parser.option(new String[]{"g", "gradle-user-home"}).hasArgument();
parser.option(new String[]{"q", "quiet"});
SystemPropertiesCommandLineConverter converter = new SystemPropertiesCommandLineConverter();
converter.configure(parser);
ParsedCommandLine options = parser.parse(args);
Properties systemProperties = System.getProperties();
systemProperties.putAll(converter.convert(options, new HashMap()));
File gradleUserHome = gradleUserHome(options);
addSystemProperties(gradleUserHome, rootDir);
Logger logger = logger(options);
WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile(propertiesFile);
wrapperExecutor.execute(args, new Install(logger, new Download(logger, "gradlew", wrapperVersion()), new PathAssembler(gradleUserHome)), new BootstrapMainStarter());
}
// ...
}
public class WrapperExecutor {
// ...
public void execute(String[] args, Install install, BootstrapMainStarter bootstrapMainStarter) throws Exception {
File gradleHome = install.createDist(this.config);
bootstrapMainStarter.start(args, gradleHome);
}
// ...
}
public class BootstrapMainStarter {
// ...
public void start(String[] args, File gradleHome) throws Exception {
File gradleJar = this.findLauncherJar(gradleHome);
URLClassLoader contextClassLoader = new URLClassLoader(new URL[]{gradleJar.toURI().toURL()}, ClassLoader.getSystemClassLoader().getParent());
Thread.currentThread().setContextClassLoader(contextClassLoader);
Class<?> mainClass = contextClassLoader.loadClass("org.gradle.launcher.GradleMain");
Method mainMethod = mainClass.getMethod("main", String[].class);
mainMethod.invoke((Object)null, args);
if (contextClassLoader instanceof Closeable) {
contextClassLoader.close();
}
}
// ...
}
public class GradleMain {
// ...
public static void main(String[] args) throws Exception {
(new ProcessBootstrap()).run("org.gradle.launcher.Main", args);
}
}
public class Main extends EntryPoint {
// ...
public static void main(String[] args) {
(new Main()).run(args);
}
protected void doAction(String[] args, ExecutionListener listener) {
this.createActionFactory().convert(Arrays.asList(args)).execute(listener);
}
CommandLineActionFactory createActionFactory() {
return new CommandLineActionFactory();
}
}
看到这里比较清晰的,WrapperExecutor会先检查是否有配置已下载到本地的gradle路径,没有则先从服务器下载(根据gradle-wrapper.properties文件配置distributionUrl链接),再是根据传进来的命令行参数,用命令行工厂构建不同的命令行action,并通过命令解析器execute对应的命令行action;
Gradle Wrapper工作流程图
思考:如何避免同个项目在其他开发者电脑上运行时,因gradle版本不同而引发各种问题?
可上传wrapper目录,统一gradle-wrapper.properties配置的gradle版本,使得其他开发者也用同个gradle版本构建同个项目。
以上是关于gradlew脚本的了解,那gradle脚本呢?我们直接打开文件对比,就基本可以知道两份脚本之间的主要差异了:
差异之所以在classpath,是因为java命令运行jar包里头的文件的话,我们需要通过classpath指定命令运行时查找class文件的路径。
同样,在gradle脚本中添加 echo "$JAVACMD $@"
日志打印,得到如下打印:
echo "$JAVACMD $@"
$ ~/Library/Android/gradle/gradle-4.4/bin/gradle -v
/Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home/bin/java -Xdock:name=Gradle -Xdock:icon=/Users/cengfanwei/Library/Android/gradle/gradle-4.4/media/gradle.icns -Dorg.gradle.appname=gradle -classpath /Users/cengfanwei/Library/Android/gradle/gradle-4.4/lib/gradle-launcher-4.4.jar org.gradle.launcher.GradleMain -v
你会发现如果直接通过gradle命令的话,其实运行的是gradle-launcher-4.4.jar包里头的org.gradle.launcher.GradleMain类,之后的流程就跟上面从GradleMain开始一样的了!
思考:使用gradle命令效率比使用gradlew效率快的原因?
因为gradlew命令,需要执行一些额外流程,如类加载、反射gradle-launcher-xx.jar包里头的类等等,最后再到org.gradle.launcher.GradleMain类的main函数。
二、gradle常用命令
前面了解gradlew、gradle的区别之后,下面列出一些gradle常用的命令
命令 | 描述 |
---|---|
gradle androidDependencies | 查看项目依赖树 |
gradle assembleDebug | 构建debug版本apk |
gradle assembleRelease | 构建release版本apk |
gradle installDebug | 安装debug版本apk到设备,在adb设备时,这个命令省每次都还要敲install命令行 |
gradle installRelease | 同installDebug,只是apk版本是release |
gradle uninstallDebug | 卸载debug版本apk |
gradle clean | 清除build缓存 |
gralde build --stacktrack | 构建整个模块,且打印整个构建流程的日志(包括异常日志) |