June 20, 2012

A usecase for git commit hooks

I’ve been working a lot with XCode lately, developing an iPad app for a customer at weluse. Sometimes I just dropped assets from my dropbox into XCode, which lead to XCode adding the files using my absolute file directory path, rather than the path relative to the project.

Now this wasn’t a problem until our customer started building the project which obviously failed.

The solution which worked great for me was a git pre-commit hook to ensure that no files have been checked in containing absolute paths, in this case: any file which path starts with $HOME.

So I came up with this simple pre-commit hook script which causes git to stop commits for just this use case:

#!/bin/sh

# Redirect output to stderr.
exec 1>&2

search_for_absolute_paths() {
  git grep "$HOME"
}

if [ "" != "$(search_for_absolute_paths)" ]
then
  echo "commit contains paths relative to the current user:"
  echo ""
  echo $(search_for_absolute_paths)
  exit 1;
else
  exit 0;
fi

The installation is straight forward: place the content under

/path/to/your/project/.git/hooks

in a file named pre-commit, chmod it to 755 and voila: git will refuse any commit containing your $HOME environment variables value.

Now this wouldn’t have been necessary if I were a little more cautious when working with my assets, but it feels good to be on the safe side anyways.

© Raphael Randschau 2010 - 2022 | Impressum