0

I have a problem with a Git pre-commit hook.

My use case is: When I am in a deatched head state I want to checkout the master branch before the commit is done. The checkout of the master branch needs to be done by an external tool.

To reproduce that issue I checkout a commit to come into the detached head state and then I do a commit:

git checkout 8060963376296d7d8286b0f7e37965e526442b4c
echo test >> file25.txt 
git add file25.txt
git commit -m "test commit"

Git shows the following error message and the commit is not done:

fatal: cannot lock ref 'HEAD': is at b302d8f6806dffcb222f95ac10b4371dea6254c6 but expected 8060963376296d7d8286b0f7e37965e526442b4c

The commit b302d8f6806dffcb222f95ac10b4371dea6254c6 points to the master branch.

My pre-commit hook contains only one line:

exec "c:/temp/hook-test/checkout-branch.bat"

The file checkout-branch.bat contains also only one line to checkout the master branch:

git checkout master

My Git version:

git --version
git version 2.21.0.windows.1

Please note:

  • the error does not occur if I do the command "git checkout master" directly in the pre-commit hook. But for my use case I have to call an external application
  • The example above is simplified - I removed the handling to detect the detached head mode

Does anybody has an idea how to solve that issue?

aufda
  • 1

1 Answers1

0

Hooks in general run in a rarefied environment, in which not everything is possible. A pre-commit hook should not try to change what will be committed, and cannot change the branch on which the commit will be added.1 A pre-commit hook can terminate the attempt to commit, and can print advice to a user, such as please check out a branch by name first, before causing the attempt-to-commit to terminate. So the thing to do here would be to check for this state, complain, and fail the attempt to commit.


1Even if you figure out some workaround, it's not a good idea in general. A workaround might involve running additional plumbing commands, but you run the danger of messing up the normal index / current-branch linkage, in a way similar to the problem that is the reason that git push won't normally push to a checked-out branch. Don't do this!

torek
  • 448,244
  • 59
  • 642
  • 775