【Git Hook】之pre-push

当提交记录中存在如下merge branch的记录时禁止push,防止污染提交记录

Merge branch 'xx1' of git_url1 into xx2

将如下shell脚本保存为pre-push文件,注意没有后缀,然后拷贝到工程里.git/hooks/目录下

#!/bin/sh
remote="$1"
url="$2"

z40=0000000000000000000000000000000000000000

while read local_ref local_sha remote_ref remote_sha
do
    echo "local_ref = $local_ref, local_sha = $local_sha"
    echo "remote_ref = $remote_ref, remote_sha = $remote_sha"
    if [ "$local_sha" = $z40 ]
    then
        # Handle delete
        :
    else
        if [ "$remote_sha" = $z40 ]
        then
            # New branch, examine all commits
            range="$local_sha"
        else
            # Update to existing branch, examine new commits
            range="$remote_sha..$local_sha"
        fi
        echo "range = $range"
        git log $remote_sha > /dev/null 2>&1;
        if [[ $? -ne 0 ]]; then
            echo "本地代码不是最新的,请先更新"
            echo "  1. git stash"
            echo "  2. git pull --rebase"
            exit 1
        fi

        # git show $commit_id | awk -F "[\n]" '{print $1}' | awk "NR==2"
        for commit_id in `git rev-list "$range"`; do
            # echo "commit_id = $commit_id"
            line2=`git show $commit_id | awk -F "[\n]" '{print $1}' | awk "NR==2"`
            words=${line2:0:6}
            # echo "line 2 = $line2"
            # echo "words = $words"
            if [[ "$words" = "Merge:" ]]; then
                oldifs="$IFS"
                IFS=$'\n'

                echo "提交不符合规范,存在merge commit记录,记录如下:"
                for content in `git show $commit_id`; do
                    echo "‼️ ‼️ $content"
                done

                IFS="$oldifs"
                exit 1
            fi
        done
    fi
done

exit 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容