批量替换git目录的远程仓库URL地址脚本

需求:

  1. 输入work-dir 工作目录

  2. 扫描工作目录中的子目录

  3. 对每一个子目录, 判断是否是git repo

  4. 确认是git repo, 获取git origin remote-url

  5. 请求服务, 获取迁移地址:curl -X GET http://server/repo/query?old-origin=git%xxdef

  6. 判断repo是否迁移, 迁移则修改origin remote-url

  7. 如果修改了origin remote-url, 打印:目录 ${dir} 从${old-origin-url} 自动迁移到 ${new-origin-url}

  8. 完成退出

脚本如下:

# cat gitlab_repo_replace.sh

#!/bin/bash

# Author: huangjie
# time: 2019-05-27
# function: 用于递归判断某目录下的git仓库目录并修改远程仓库url。

set -e

# help帮助函数
function help()
{
    cat <<- EOF
        Desc: 该程序需要输入一个目录的绝对路径或者相对路径作为参数,请确认输入的参数。
        Usage: bash $0 <directory name>
EOF
    exit 0
}

# urlencode编码函数
function urlencode() {
    local length="${#1}"
    for (( i = 0; i < length; i++ )); do
        local c="${1:i:1}"
        case $c in
            [a-zA-Z0-9.~_-]) printf "$c" ;;
            *) printf "$c" | xxd -p -c1 | while read x;do printf "%%%s" "$x";done
        esac
    done
}

# 替换本地仓库的url为指定远程仓库
function replace_git_repo(){
    cd $1
    old_origin_url=$(git remote -v | grep "fetch" | awk '{print $2}')
    urlencode=$(urlencode ${old_origin_url})
    new_origin_url=$(curl -X POST http://tools.test.xxx.com/repo/query?old-origin=${urlencode})
    if [ "${new_origin_url}" != "" ]
    then
        echo "To replace the remote url,wait..."
        git remote set-url origin $new_origin_url
        echo "目录 $1 从 ${old_origin_url} 自动迁移到 ${new_origin_url}" >> ${root_dir}/git_replace_print.log
    fi
}

# 递归遍历目录下的子目录完成git仓库的替换
function getdir(){
    for sub_dir in $(ls -al $1 | grep "^d" | grep -Ewv ".$|.git"| awk '{print $NF}')
    do
        dir_or_gitrepo=$1"/"${sub_dir}
        if [ $(ls -al ${dir_or_gitrepo} | grep "^d" | grep -w ".git" | wc -l) -eq 1 ]
        then
            replace_git_repo ${dir_or_gitrepo}
        else
            echo "The ${dir_or_gitrepo} dir is not git repo dir!"
        fi
        getdir ${dir_or_gitrepo}
    done
}

# 主函数
function main(){
    if [ $# -ne 1 ]
    then
        help
        exit 0
    fi

    # 获取脚本工作目录参数
    dir=$1
    if [ ${dir:0:1} == "/" ]; then
        root_dir=${dir}
    elif [ ${dir:0:2} == "./" ]; then
        root_dir=$(cd $(dirname $0); pwd)"/"${dir:2}
    else
        root_dir=$(cd $(dirname $0); pwd)"/"${dir}
    fi

    # 遍历工作目录执行函数操作
    getdir "${root_dir}"
}

main "$@"

执行情况:

原文地址:https://www.cnblogs.com/wsjhk/p/10935304.html