shell脚本同步git多仓库
source link: http://blog.xuedingmiao.com/blog/shell_git_sync.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
shell脚本同步git多仓库
2023-04-16 22:22:26使用shell脚本在仓库间同步代码
# 背景
公司项目大多是定制项目,仓库是每个地区都拆分成了独立的,有需要更新时才会需要同步修改代码。为了方便管理,我们大都采取了两种管理模式:
- 独立仓库单独拉取到本地进行开发部署
- 原仓库分别创建对应的地区环境分支进行开发,需要更新时将地区分支同步到该地区的独立仓库进行部署发版
本文是基于单仓库开发,多仓库发版时同步代码的模式。
# 示例代码
以下代码仅供参考:
- 需要自己定义仓库代码的工作目录
- 脚本名称以仓库名字来命名
#!/bin/bash
a=`uname -a`
b="Darwin"
if [[ $a =~ $b ]];then
echo "mac"
else
# get file name
fname=${BASH_SOURCE#*sync-}
workspace=$1
echo "cd "$workspace${fname%.sh*}
cd $workspace${fname%.sh*}
fi
old_repo=$(git config --get remote.origin.url)
old_path=$(git config --get remote.origin.url)
current_branch=$(git rev-parse --abbrev-ref HEAD)
# old repo
echo '旧仓库:'$old_path
# old repo name
pre_repo=${old_path%9336/*}
project=${old_path#*9336/}
# repo group
group=basic-platform
# repo name change
echo '当前分支:'$current_branch
# 拉取代码
echo '拉取代码'
git pull
if [ -n "$2" ] ;then
target_env=$2
# env setting
declare -A target_repo_prefix
target_repo_prefix['hbsy']=hbsy_
target_repo_prefix['uat']=
echo '目标仓库前缀:'${target_repo_prefix[$target_env]}
new_pro_name=$group'/'${target_repo_prefix[$target_env]}'basic-platform-frontend'
else
# read branch
case $current_branch in
shiyan)
echo '所属环境:十堰'
new_pro_name=$group'/hbsy_basic-platform-frontend'
;;
uat)
echo '所属环境:UAT'
new_pro_name=$group'/basic-platform-frontend'
;;
*)
echo '未找到所属环境'
exit 1
;;
esac
fi
newRepo=${old_path/project/new_pro_name}
newRepoUrl=$pre_repo'9336/'$new_pro_name'.git'
echo '新仓库:'$newRepoUrl
echo '切换新仓库'
git remote set-url origin $newRepoUrl
git remote set-url origin --push $newRepoUrl
echo '推送至'$current_branch
git push -f $newRepoUrl $current_branch
echo '检查本地是否存在master分支'
if git rev-parse --verify master;then
echo '删除本地master分支'
git branch -d master
fi
# 非单(环境)分支同步的情况
if [ x"$2" = x ] ;then
echo '检查远端是否存在master分支'
branch_exist=$(git ls-remote --heads origin master | wc -l | awk '$1=$1')
echo "$branch_exist"
if [ "$branch_exist" == "1" ] ;then
echo '删除远端master分支'
git push origin --delete master
fi
echo '推送至master'
git checkout -b master
git push --set-upstream origin master
git checkout $current_branch
git branch -d master
fi
echo '切换原仓库'
git remote set-url origin $old_repo
git remote set-url origin --push $old_repo
exit 0
脚本的主要作用:
接收两个参数--工作空间及同步的目标地区环境代码。
脚本名称对应目标环境的仓库名,进入到工作空间对应的仓库目录获取当前所在分支名称,拉取最新代码,将代码同步推送到分支对应地区仓库的当前分支,删除本地主分支,删除远端的主分支并将本地分支作为主分支推送至目标地区仓库远端分支,最后再切换回原仓库。
如果参数中指定了目标地区环境代码则只会将本地仓库目录的当前分支推送至远端目标仓库。
# 参考资料
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK