Git receive/update hooks and new branches

marc.guenther picture marc.guenther · Aug 18, 2010 · Viewed 11.2k times · Source

I have a problem with the 'update' hook. In the case of a new branch, it gets a 0000000000000000000000000000000000000000 as the 'oldrev'. And I don't know how to handle that case.

We have the requirement, that every commit message references a valid Jira issue. So I have installed an "update" hook on our central repository. That hook gets an "oldrev" and a "newrev". I then pass those to "git rev-list" like this:

git rev-list $oldrev..$newrev

This gives me the list of all revs, which I can then iterate through, and do whatever I need to do.

The problem is, when the user pushes a new branch, the hook gets 0000000000000000000000000000000000000000 as the oldrev. And "git rev-list" simply complains with:

fatal: Invalid revision range 0000000000000000000000000000000000000000..21bac83b2

So how do I get the list of all the revs that are on that new branch? I have searched the net for quite some time now, and found nothing. The example hooks I found either

  • don't handle the problem, and fail with the above error message
  • incorrectly try to fix the problem by setting the oldrev to "", which returns the wrong results from rev-list
  • simply give up when they encounter that oldrev

None of these sound particularly exciting.

So does someone have any idea how to get the right answer in that case? I was thinking about querying git for "give me all revs that are reachable from newrev, but not from any of the other branches (=all branches except the new one)". But even that would give the wrong answer if there had been a merge from the new branch to any of the old ones.

Answer

Cascabel picture Cascabel · Aug 18, 2010

The term "right answer" is a bit ambiguous in this case. I actually think that "all revs reachable from newrev but nowhere else" is completely correct. This is true even if there was a merge - in that case, you should see the commits unique to the new ref, and the merge commit, but not the commits that were merged.

So, I would say, check if the "oldrev" is all zeroes, and if it is, act accordingly:

if [ "$oldrev" -eq 0 ]; then
    # list everything reachable from newrev but not any heads
    git rev-list $(git for-each-ref --format='%(refname)' refs/heads/* | sed 's/^/\^/') "$newrev"
else
    git rev-list "$oldrev..$newrev"
fi