Do you make apps? Then read on. Otherwise this blog post is probably of no interest to you at all.
When making apps you often run into the problem that you want to have incrementing build numbers associated with your binaries. You can do it the old fashioned way and just increase it every time you make a release. Or you can simplify your life drastically with just one little script and some initial setup:

Overview

The idea is to have a script run during the build phase (or better just before the build) which pulls the number of commits resulting in the current git tree and puts it into the bundle version key in the Apps Info.plist.
Now I know, technically it's then no longer a build counter, as it does not count each individual build but rather the state the git repository was in at the time of the build. If you ask me, that's even better.

Suppose we have a new App. We set everything up and then make our initial commit. We can then make how many builds we like, the build number will not increase. Unless we make a change to the source of the App and commit it to git. Then all of a sudden we get a higher build number. Exactly what we want. Magic :-)

Setup

Pre-Build Script

  • Open your build scheme, in the left hand sidebar expand the Build event, and add a new Pre-action.
  • Make sure to provide the build settings from your App target
  • Insert the following script:

cd "${SRCROOT}"

REV_SHA1=`git rev-list --max-count=1 HEAD`

GIT_REV=`git rev-list --reverse HEAD | grep -n ${REV_SHA1} | cut -d: -f1`

echo "#define MY_APP_REVISION "${GIT_REV}"\n" > "/tmp/My-Info.plist-Prefix.pch"

Preprocess Info.plist

  • Next go to the Build Settings of your Apps Target
  • Turn Preprocess Info.plist File on
  • Enter the path from the script (/tmp/My-Info.plist-Prefix.pch) into Info.plist Preprocessor Prefix File

Info.plist

  • Finally, in your Info.plist change the value from Bundle Version/CFBundleVersion to MY_APP_REVISION