限制推送到远程的提交数量

limit number of commits to push on remote

概述:在我们公司,我们正在尝试引入一项政策,以便开发人员不能在一次推送中推送 5 次或更多次提交。例如:如果有 20 个提交需要推送到上游。检查不应允许它带有消息帽,一次只允许推送 5 次或更少的提交。我正在尝试以下操作来获取我本地 master 和上游 master 的提交次数。


git log --oneline origin/master ^master | wc -l 

但它没有给我预期的输出。

托管服务Gerrit有这样的限制,一次推送最多有20个提交供审查。如果超过20个,用户需要分批推送。我不知道你为什么需要这样的策略,我认为 Gerrit 策略更多是关于性能的。

要计算自分叉点以来我们所做的新提交的数量,通常在远程跟踪分支上(假设它是origin/foo),我们可以使用

git rev-list --count origin/foo..HEAD

或者如果我们知道这两个提交

git rev-list --count commit1..commit2

为了实施您的政策,我会编写一个服务器端挂钩,如 pre-receive。在hook中,计算新commit的个数,大于4则拒绝push

#!/bin/bash

while read oldvalue newvalue refname;do
    # todo, case 0, deal with refs other than branches
    # todo, case 1, create a branch
    # todo, case 2, delete a branch

    # case3, update a branch
    count=$(git rev-list --count ${oldvalue}..${newvalue})
    if [[ "${count}" -ge 5 ]];then
        echo some message
        exit 1
    fi
done