Git – pre-receive hook on server-side that refuse any push to master which has any non-linear history


I am looking for a shell script (sh, not bash possibly) that would refuse any push to master which has any non-linear history.

I tried script from:

How to avoid "Merge branch 'master' of ssh://"

which is implemented in ruby, but it does not even run on sourceforge server. I tried then the bash equivalent:

this one runs, but does not do what it is supposed to do (it does not reject anything).

Thanks for suggestions.

Best Solution

You can do this much, much more simply than your hook.

merge_commit=$(git rev-list -n 1 --merges $rev_old..$rev_new)
if [ -n "$merge_commit" ]; then
     echo "Merge commit detected: $merge_commit";
     exit 1

You also might want to make this an update hook, not a pre-receive hook. The pre-receive hook runs once for the entire push, taking input on stdin, while the update hook runs once per ref to be updated, taking input as arguments. That gives you better granularity.

if [ "$ref" = refs/heads/master ]; then

There's also usually no need to check for fast forwards. Git already by default disallows non-fast-forward pushes, and if you want to deny them even on forced pushes, just set receive.denyNonFastForwards to true in the config. I guess you want to deny them even for forced pushes to master, but allow them elsewhere? That's a kind of access control that's actually implemented very well by things like gitolite, if you're doing your own hosting, but I guess if that's your requirement and you don't have gitolite, this is the best you can do.

Finally, it also strikes me as odd that you'll allow merge commits to be pushed to other refs, just not master. That could lead to some surprises, if someone pushes to an unstable branch, it gets tested, then you want it on master - but can't push it there!