Skip to content

Instantly share code, notes, and snippets.

@imakecodes
Forked from jarodsmk/pre-commit
Last active February 25, 2021 11:42
Show Gist options
  • Save imakecodes/6b52a01f2b69058d38e7913e3d567997 to your computer and use it in GitHub Desktop.
Save imakecodes/6b52a01f2b69058d38e7913e3d567997 to your computer and use it in GitHub Desktop.
Git pre-commit hook that detects if the developer forget to remove all the javascript console.log before commit, detects merge markers, and prettifies your code!
#!/bin/sh
# ------------------------------------------------------------------------------------#
# Console log check
# ------------------------------------------------------------------------------------#
# Redirect output to stderr.
exec 1>&2
# Enable user input
exec < /dev/tty
# Updated regexp to only look at the addition of console.log's on the current branch HEAD
# thanks @brugnara!
consoleregexp='^\+.*console\.log('
# Check
if test $(git diff --cached | grep $consoleregexp | wc -l) != 0
then
exec git diff --cached | grep -ne $consoleregexp
read -p "There are some occurrences of console.log at your modification. Are you sure want to continue? (y/n)" yn
echo $yn | grep ^[Yy]$
if [ $? -eq 0 ]
then
exit 0; # Continue
else
exit 1; # Halt
fi
fi
# ------------------------------------------------------------------------------------#
# Merge conflict marker checker
# ------------------------------------------------------------------------------------#
# Taken from: https://jondowdle.com/2015/02/block-merge-conflicts-in-commits/
## pre-commit script to prevent merge markers from being committed.
## Author: Jon Dowdle <[email protected]>
##
## This simply searches the files that you are about to commit.
##
changed=$(git diff --cached --name-only)
if [[ -z "$changed" ]]
then
exit 0; # Continue
else
echo $changed | xargs egrep '[><]{7}' -H -I --line-number
## If the egrep command has any hits - echo a warning and exit with non-zero status.
if [ $? == 0 ]
then
echo "\n\nWARNING: You have merge markers in the above files, lines. Fix them before committing.\n\n"
exit 1;
fi
fi
# ------------------------------------------------------------------------------------#
# Prettify
# ------------------------------------------------------------------------------------#
# Taken from https://prettier.io/docs/en/precommit.html
jsfiles=$(git diff --cached --name-only --diff-filter=ACM "*.js" "*.jsx" | tr '\n' ' ')
[ -z "$jsfiles" ] && exit 0;
# Prettify all staged .js files
echo "$jsfiles" | xargs ./node_modules/.bin/prettier --write;
# Add back the modified/prettified files to staging
echo "$jsfiles" | xargs git add;
exit 0; #Successful finish
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment