hjr265.me / blog /

Prevent Git Commits with Unformatted Go Code

Git has this great feature that I think is well-known but under-used. I am talking about Git hooks.

With Git hooks, you can run scripts during different Git actions.

Like this one:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/bin/sh

GOFILES=`git diff --name-only --cached | grep -e '.go$' | grep -ve 'vendor/'`
UNFMTFILES=()
for f in $GOFILES; do
  if [ -n "`gofmt -l -s ./"$f"`" ]; then
    UNFMTFILES+=("$f")
  fi
done

if [ ${#UNFMTFILES[@]} -gt 0 ]; then
  echo You have staged unformatted Go files. Please run \`go fmt\` first.
  for f in ${UNFMTFILES[@]}; do
    echo " $f"
  done
  exit 1
fi

This script will take a list of all the staged Go files. It will then run gofmt to determine if these Go files are not formatted.

If you use it as a part of the pre-commit hook of your Git repository in your Go project, it will prevent commits with unformatted Go files.

To use it as the pre-commit hook, save it as pre-commit inside the .git/hooks/ directory.


This post is 59th of my #100DaysToOffload challenge. Want to get involved? Find out more at 100daystooffload.com.


comments powered by Disqus