Git hooks on Windows

On Unix/Linux, a Git hook script has a special #! (called “shebang”) first line that is used to indicate which program should run the script. On Windows, normally the special shebang first line has no effect (as it’s treated as a comment). However, Git on Windows is able to recognize the shebang first line. Therefore, we add a shebang line in a Git hook script on Windows just as we do on Linux. Below are two Git commit-msg hooks that run on Linux and Windows respectively.

Git commit-msg hook example on Linux

#!/bin/sh

# This example just print "commit-msg" when you executes a commit.

echo 'commit-msg';
exit 0;

Git commit-msg hook example on Windows

#!C:/Program Files (x86)/Git/bin/sh.exe

# This example just print "commit-msg" when you executes a commit.

echo 'commit-msg';
exit 0;

The first line indicate using Git’s shell to run the script. If you want to write a hook in other languages like PHP or Python, just replace the first line with the full path of the program running the script.

A PHP Git hook example on Windows

Below commit-msg Git hook checks the commit message length, if it exceeds 52 then reject the commit.

#!D:/php/php.exe

<?php
/**
 * Check the commit message length, if it exceeds 52 then reject the commit.
 */

// Note the commit-msg hook's three arguments starts from index of 1.
// The first argument $argv[0] is the script file itself.    
$msg_file = $argv[1];
$contents = file_get_contents( $msg_file );
$commit_msg = strstr( $contents, "n", true ); // First line in commit msg file.
if( strlen(  $commit_msg ) > 52 ) {
    echo "Commit message format error: The length of commit message '$commit_msg' exceeds 52.";
    exit( 1 );
}
exit( 0 );

Save the content in above example in a file named commit-msg and put it in your git repository’s .git/hooks directory. Then you’ll see the effect by running the below command.

# The option --allow-empty allows an empty commit containing only a commit message.
$ git commit --allow-empty -m 'test commit-msg hook which checks the lenght of commit message'

Commit message format error: The length of commit message 'test commit-msg hook which checks the lenght of commit message' exceeds 52.

Leave a Reply