Skip to content

Instantly share code, notes, and snippets.

@jarodsmk
Forked from guilherme/gist:9604324
Last active September 30, 2021 03:44
Show Gist options
  • Save jarodsmk/2e46444d09ca2d2913df6e9a266fdbd0 to your computer and use it in GitHub Desktop.
Save jarodsmk/2e46444d09ca2d2913df6e9a266fdbd0 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 <jdowdle@gmail.com>
##
## 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