背景
在安卓模块化和组件化开发的趋势下,一个构建物往往依赖会依赖其他构建物进行进行编译,而构建物也可能发布到多个不同的仓库,此时采用手动构建和发布的方式就会非常影响开发效率,我们期望构建和发布可以自动化和批量化,即:
- 可以指定构建哪些模块;
- 可以指定发布到哪些仓库;
知识点
- Shell脚本命令的参数的读取;
- 字符串的提取、分割技术;
- 数组的遍历;
- if、case等流程控制;
脚本实现
假设有common、core、lib1、lib2四个模块,libX是我们要发布的最终产物,其依赖关系如下:
有repo1、repo2、repo3三个仓库,我们可以指定一次发布到其中某个或全部仓库。
#!/bin/bash
# Usage:
# 1. build all modules without publish:
# `./build_aar.sh` or `./build_aar.sh -from=common`
# 2. build from core:
# `./build_aar.sh -from=core`
# 2. build from core and publish to repo1 and repo2:
# `./build_aar.sh -from=core -publish=repo1,repo2`
# Option:
# 1. `-from=xxx`: specify which module to start build from.
# 2. `-publish=repo1,repo2,repo3`: specify which repos to publish, support multiple repos.
for option
do
case $option in
-from=* | --from=*)
FROM=$(expr "x$option" : "x-*from=\(.*\)")
;;
-publish=* | --publish=*)
PUBLISH=$(expr "x$option" : "x-*publish=\(.*\)")
;;
*)
echo "[INFO]: Unknown option $option"
;;
esac
done
if [ -z "$FROM" ]; then
FROM=common
fi
echo "[INFO]: Start build from $FROM, publish to $PUBLISH"
publishToRepo1=no
publishToRepo2=no
publishToRepo3=no
if [ -z "$PUBLISH" ]; then
echo "[INFO]: Build without publish."
else
# shellcheck disable=SC2206
publishes=(${PUBLISH//,/ })
for var in ${publishes[*]}
do
if [ "$var" = local ]; then
publishToRepo1=yes
elif [ "$var" = byte ]; then
publishToRepo2=yes
elif [ "$var" = volc ]; then
publishToRepo3=yes
fi
done
echo "[INFO]: Build publish to publishToRepo1=$publishToRepo1, publishToRepo2=$publishToRepo2, publishToRepo3=$publishToRepo3"
fi
# clear previous build.
./gradlew clean
beginFlag=no
for name in common:assembleRelease:Common \
core:assembleRelease:Core \
lib1:assembleRelease:Lib1 \
lib2:assembleRelease:Lib2 \
others:assembleFullDebug
do
# shellcheck disable=SC2206
cmd=(${name//:/ })
if test "x$beginFlag" = xno; then
if test "${cmd[0]}" = "$FROM"; then
beginFlag=yes
fi
fi
if test "x$beginFlag" = xyes; then
# build aar.
./gradlew :"${cmd[0]}":"${cmd[1]}"
# backup aar.
cp -r ./"${cmd[0]}"/build/outputs/aar ./output
# publish aar.
if [ -n "${cmd[2]}" ]; then
if [ "$publishToRepo1" = yes ]; then
./gradlew :"${cmd[0]}":publish"${cmd[2]}"PublicationToRepo1Repository
fi
if [ "$publishToRepo2" = yes ]; then
./gradlew :"${cmd[0]}":publish"${cmd[2]}"PublicationToRepo2Repository
fi
if [ "$publishToRepo3" = yes ]; then
./gradlew :"${cmd[0]}":publish"${cmd[2]}"PublicationToRepo3Repository
fi
fi
fi
done