git cannot execute python-script as hook

Lukas Knuth picture Lukas Knuth · Feb 16, 2012 · Viewed 11.2k times · Source

I have created a little pre-commit hook in python. This hook works like a charm under Linux, but in Windows it keeps telling me:

error: cannot spawn .git/hooks/pre-commit: No such file or directory

I know there have been similar questions here about the same issue and the conclusion seams to be the shebang. My script has this on the very first line:

#!F:\PortableApps\PortablePython3.2\App\python.exe

It's also interesting to note that executing the script simply by writing .git/hooks/pre-commit works wonderful, but as soon as I try to commit, git spits out the above message.

Another interesting thing is, when I convert the encoding from ANSI to UTF-8 (using Notepad++), I get the following error when trying to execute the script:

.git/hooks/pre-commit: Cannot execute binary file

I'm using the following tools:

Answer

Lukas Knuth picture Lukas Knuth · Jun 5, 2012

I used the proxy-approach to make the python script work under windows (with msysgit). The complete script (with description on how I did it) might be found here: https://gist.github.com/1839424

Here is the important part about making it work under Windows


If you're working with Windows (and "msysgit"), it's a little more complicated. Since "msysgit" seems to have a problem handling the SHEBANG, you'll have to use a little trick to make the script executable (further information on this problem can be found here).

In order to make the script work, you'll want to remove the SHEBANG from the Python script ("pre-commit.py") and use a wrapper bash-script to call the interpreter. This script should look something like this:

#!/bin/sh
python .git/hooks/pre-commit.py

Store this script as a file called "pre-commit" (no file-ending). This assumes that you have Python in your PATH. If you don't, you can also specify the full path to your interpreter-executable.

This script will be called by "git commit" and call the python-script to check for the huge files. The path after the SHEBANG should not be changed, as "msysgit" will remap it automatically. You must specify a path relative to the repo-root for the Python script to be executed (because thats from where the script is called).

Afterwards you'll want to copy both the wrapper-file ("pre-commit") and the Python-script ("pre-commit.py") to your repos ".git/hooks"-directory, personalize the Python-script ("max_file_size" and "git_binary_path") and mark the "pre-commit"-file executable.