Clicky

iOS Dev Nugget 176 Git no-commit Pre-commit Hook

.

Need to run a code review on your codebase? Hire me

I like to sprinkle specific comments markers (such as NOCOMMIT) in my code while I'm working on it to remind me of TODOs that I need to complete in the current change. I don't ever want to commit my code with this markers in them. Over the years, this has inadvertently happened a few times.

If you are like me, Mark Smith shares a way to prevent this with a git pre-commit hook. I made a slight modification to it so it checks in the index instead of the entire file. This is useful if you do interactive staging (git add -p or git add -i). Here's my version:

#!/bin/sh

if git rev-parse --verify HEAD >/dev/null 2>&1; then  
  against=HEAD
else  
  # Initial commit: diff against an empty tree object
  against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

exec 1>&2

#Workaround for filenames with spaces in them (because for loop breaks use space by default)
SAVEIFS=$IFS
IFS=$(echo "\n\b")

for ENTRY in `git diff-index --cached --name-status $against -- | cut -c1,3-`; do  
  CHANGE=`echo "$ENTRY" | cut -c1`
  FILE=`echo "$ENTRY" | cut -c2-`
  if [ $CHANGE = "A" ] || [ $CHANGE = "M" ]; then
    if git diff --cached "$FILE" | grep -q 'NOCOMMIT'; then
      echo "$FILE" 'contains NOCOMMIT!'
      IFS=$SAVEIFS
      exit 1
    fi
  fi
done

IFS=$SAVEIFS
exit 0

Check out the article to see how to set it up.

  • Updated 20160306: Modified to remove warning when commit include deleting files.
  • Updated 20160329: Modified to handle path names with spaces.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues