Check before you commit

Issue #7

Original post https://medium.com/@onmyway133/check-before-you-commit-5a7601cffc87


We usually have some experiment code that we don’t want they to step into our commit. I usually mark my experiment with // but sometimes forget to unstage that
Starting with 2.9, Git has improvement on its commit hook which makes it globally using hooksPath

Create pre-commit file

Create a file called pre-commit, and place it into, for example /Users/khoa/hooks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/sh

# https://appventure.me/2016/04/04/prevent-accidental-test-code-commits/

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

# The special marker tag to mark things which we still need to change
marker="<TEST>"

# Redirect output to stderr.
exec 1>&2

if test $(git diff --cached -z $against | grep $marker | wc -c) != 0
then
cat <<\EOF
Error: Still has invalid debug markers in code:
EOF
echo `git diff --cached -z $against -G $marker`
exit 1
fi

Apply the hook

In your project, run git config core.hooksPath /Users/khoa/hooks
That’s it. Whenever you commit a file with that pattern, it won’t let you commit

How to use

Try

1
2
// <TEST>
UserManager.shared.isActive = true

and git commit -m "my commit message" will assert with Error: Still has invalid debug markers in code:

Reference

Comments