Last active
March 10, 2025 09:51
-
-
Save piksel/af64b9ca445c1354be862cd1485e15c0 to your computer and use it in GitHub Desktop.
Common pre-commit hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
git_root=$(git rev-parse --show-toplevel) | |
if [[ "$git_root" == "" ]]; then | |
exit 1 | |
fi | |
cd "$git_root/.git/hooks" | |
curl -LO https://gist.github.com/piksel/af64b9ca445c1354be862cd1485e15c0/raw/pre-commit | |
chmod a+x pre-commit |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
keywords=("TODO" "FIXME" "nocommit") | |
need_exit=1 | |
lines="$(git diff-index -p -M --cached HEAD)" | |
while read -r line; do | |
if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/ ]]; then | |
file="${BASH_REMATCH[1]}" | |
fi | |
if [[ "$line" =~ ^@@\ -[0-9]+,[0-9]+\ \+([0-9]+), ]]; then | |
line_number_base=${BASH_REMATCH[1]} | |
line_number=$line_number_base | |
fi | |
if [[ "$line" =~ ^\+[^+] ]]; then | |
for keyword in ${keywords[@]}; do | |
if [[ "$line" =~ "$keyword" ]]; then | |
printf '\e[93mWarning\e[m: \e[95m%s\e[m found in \e[94m%s\e[m:\e[96m%s\e[m\n' $keyword $file $line_number | |
need_exit=1 | |
fi | |
done | |
((line_number++)) | |
fi | |
if [[ "$line" =~ ^[^+-@] ]]; then | |
((line_number++)) | |
fi | |
done <<< "$lines" | |
if [[ $need_exit == 1 ]]; then | |
printf "\nFix warnings above or use \e[97mgit commit --no-verify\e[m\n" | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment