Skip to content

Instantly share code, notes, and snippets.

@mbrehin
Last active January 31, 2019 08:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbrehin/2c50bee6067c6bf15215b03cbc60820c to your computer and use it in GitHub Desktop.
Save mbrehin/2c50bee6067c6bf15215b03cbc60820c to your computer and use it in GitHub Desktop.
Git hooks: pre-commit
#! /bin/bash
# If you encounter any error like `declare: -A: invalid option`
# then you'll have to upgrade bash version to v4.
# For Mac OS, see http://clubmate.fi/upgrade-to-bash-4-in-mac-os-x/
# Hash using its key as a search Regex, and its value as associated error message
declare -A PATTERNS;
PATTERNS['^[<>|=]{4,}']="You've got leftover conflict markers";
PATTERNS['focus:\s*true']="You've got a focused spec";
# Declare empty errors array
declare -a errors;
# Loop over staged files and check for any specific pattern listed in PATTERNS keys
# Filter only added (A), copied (C), modified (M) files
for file in $(git diff --staged --name-only --diff-filter=ACM --no-color --unified=0); do
for elem in ${!PATTERNS[*]} ; do
{ git show :0:"$file" | grep -Eq ${elem}; } || continue;
errors+=("${PATTERNS[${elem}]} in ${file}…");
done
done
# Print errors
# author=$(git config --get user.name)
for error in "${errors[@]}"; do
echo -e "\033[1;31m${error}\033[0m"
# Mac OS only: use auditable speech
# which -s say && say -v Samantha -r 250 "$author $error"
done
# If there is any error, then stop commit creation
if ! [ ${#errors[@]} -eq 0 ]; then
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment