Skip to content

Instantly share code, notes, and snippets.

@yougg
Created August 17, 2018 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yougg/b5875e5d99870bb4023ce311fb6ac481 to your computer and use it in GitHub Desktop.
Save yougg/b5875e5d99870bb4023ce311fb6ac481 to your computer and use it in GitHub Desktop.
git pre-commit hook for format go source files
#!/usr/bin/env bash
cd `dirname $0`
if [ "githook.sh" = "`basename $0`" ]; then
gitroot=$(git rev-parse --show-toplevel)
cp -f ${gitroot}/scripts/githook.sh ${gitroot}/.git/hooks/pre-commit
chmod u+x ${gitroot}/.git/hooks/pre-commit
exit 0
elif [ "pre-commit" = "`basename $0`" ]; then
cd ../..
gitroot=$(git rev-parse --show-toplevel)
if [ -z "${gitroot}" ]; then
echo "can not find repository root"
exit 1
fi
cp -f ${gitroot}/scripts/githook.sh ${gitroot}/.git/hooks/pre-commit
chmod u+x ${gitroot}/.git/hooks/pre-commit
fi
if [ -n "${USERPROFILE}" ]; then
gituser="$(chcp.com 65001 &> /dev/null;net user //domain $(id -un) | awk -F '[ ][(]' '/Full Name/{print $1}' | awk -F 'Full Name[ ]+' '{print $2}') $(id -un | cut -c 2-)"
git config --global user.name "${gituser}"
suffix=".exe"
fi
formatter="${gitroot}/bin/goimports${suffix}"
if [ ! -f "${formatter}" ]; then
echo "can not find goimports file"
exit 1
fi
chmod +x ${formatter}
export GOPATH="${gitroot}"
cd ${GOPATH}
for f in `git diff --cached --name-only --diff-filter=ACM`; do
if [ -z "${f}" -o ! -f "${f}" ] || [[ ! "${f}" =~ .go$ ]]; then
continue
fi
sed -i '/import (/,/)/{/^$/d}' ${f}
${formatter} -local "code.xxxxx.com,aaa,bbb" -w ${f}
git add ${f}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment