When using git, you can grab your current build number (number of commits) by using the command: git rev-list HEAD --count.

If you need to incorporate that build number into your project you can use a hook to add the build number to one or more of your project’s files. A git hook is just a shell script that is executed at a specific event. In this case, we’ll want the build number to be added whenever you commit so we’ll need to use the pre-commit hook. Your hooks are located in the .git/hooks directory, relative to your project root.

You’ll need to create a file called pre-commit in that directory, if it doesn’t already exist. Make sure your file begins with the hashbang #!/bin/sh. Once that is done you can start writing your script.

The first step is to fetch the current build number. Since this script is being executed before the actual commit, you’ll also need to increment the build number.

Now your build number is stored in the buildnumber variable. For now, we’ll just write that build number out to a file:

This will create or update a file called build in your project root with the build number. If you need the build number in your actual source, you could read in that file. Alternatively, you could update a build constant directly in your source with a sed command:

The above code updates a class constant called BUILD in file called Class.php. It works by searching for a line beginning with const BUILD and replacing the entire line with const BUILD = $buildnumber; where $buildnumber references the shell variable, not to be confused with the PHP variable syntax. Assuming your current build number is 10, the line in the source would be updated to: const BUILD = 10;.

A final but important step is to add the modified (or created) files to the commit.

Without the above code your build number won’t make it into the actual commit. I’m also echoing the build number for reference and exiting with a status of 0 (no error).

Adding all of the above code to your pre-commit file will automatically add or update the build numbers in your source whenever git commit is called. An alternative to adding it to your pre-commit file is to create a separate shell script in your project that you could call from your hook. For example, you could use the following code in your hook to run a script called build.sh in your project root.

The above method has the advantage of not cluttering your hooks if you’re using them for multiple purposes. It also allows you to track your script along with the rest of your project files.

Full Code