Search code examples
git

limit number of commits to push on remote


overview: in our company we are trying to introduce a policy so that a developer should not be able to push 5 or more commits in one single push . for example: if there are 20 commits which are needed to be pushed to upstream . the check should not allow it with a message hat only 5 or less commits at a time are allowed to be pushed. i am trying the following to get the no of commits at my local master and upstream master .


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

but its not giving me expected output.


Solution

  • The hosting service Gerrit has such kind of limit that in one push there are at most 20 commits for review by default. The number is defined by receive.maxBatchChanges in gerrit.config. If it's more than 20, the user needs to push them in batches. I don't know why you need such a policy, and I think the Gerrit policy is more about performance.

    To calculate the number of the new commits we have made since the fork point, which is usually on the remote tracking branch (supposing it's origin/foo), we can use

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

    or if we know the two commits

    git rev-list --count commit1..commit2
    

    In order to implement your policy, I would write a server side hook like pre-receive. In the hook, calculate the number of the new commits, and reject the push if the number is bigger than 4.

    #!/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