Skip to content

Instantly share code, notes, and snippets.

@davemo
Last active September 14, 2018 00:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save davemo/6064437 to your computer and use it in GitHub Desktop.
Save davemo/6064437 to your computer and use it in GitHub Desktop.
A pre-commit hook for git running on OS X to abort if it detects keywords in specified files (this version is setup for .coffee and .js files).

Git pre-commit Hooks

The pre-commit file listed here is setup to scan files for invalid keywords prior to commit to avoid debug or logging information making its way into production files. Right now it is setup to scan only .js and .coffee files for the following keywords:

KEYWORDS_REGEX="console\.(debug|info|log|warn)\(|alert\(|debugger"
EXTENSIONS_REGEX="(.js$|.coffee$)"

Installing the Hook

  • cp pre-commit .git/hooks/
  • chmod +x .git/hooks/pre-commit

Credits

#!/usr/bin/env bash
# https://github.com/borisguery/git-keywords-checker
# Add or remove keywords here
KEYWORDS_REGEX="console\.(debug|info|log|warn)\(|alert\(|debugger"
# Add extensions to check here
EXTENSIONS_REGEX="(.js$|.coffee$)"
ERRORS_BUFFER=""
TEXT_DEFAULT="\\033[0;39m"
TEXT_INFO="\\033[1;32m"
TEXT_ERROR="\\033[1;31m"
TEXT_UNDERLINE="\\0033[4m"
TEXT_BOLD="\\0033[1m"
VERBOSE=false
FILES=$(git diff-index --cached --name-only --diff-filter=ACMR HEAD)
echo -e "\\033[1;33m""Keywords checker - pre-commit hook" "$TEXT_DEFAULT"
echo
for FILE in $FILES; do
if [[ $FILE =~ $EXTENSIONS_REGEX ]]; then
ERRORS=""
while IFS=: read -ra RESULT; do
if [ "$RESULT" != "" ]; then
ERRORS="$ERRORS\n\tline $TEXT_BOLD${RESULT[1]}$TEXT_DEFAULT: "
ERRORS="$ERRORS"$(sed -n ${RESULT[1]}p $FILE | sed -E "s/($KEYWORDS_REGEX)/\\$TEXT_UNDERLINE\1\\$TEXT_DEFAULT/g")
if [ "$ERRORS_BUFFER" != "" ]; then
ERRORS_BUFFER="$ERRORS_BUFFER\n$ERRORS"
else
ERRORS_BUFFER="$ERRORS"
fi
fi
done < <(grep -sEnH $KEYWORDS_REGEX $FILE)
if [ "$ERRORS" != "" ]; then
ERRORS="$TEXT_ERROR Errors found in $TEXT_BOLD$FILE$TEXT_DEFAULT$ERRORS"
echo -e "$ERRORS"
fi
fi
done
if [ "$ERRORS_BUFFER" != "" ]; then
echo
echo -e "$TEXT_ERROR" "There were errors or warnings, commit aborted." "$TEXT_DEFAULT"
echo -e "$TEXT_INFO" "If you are sure you want to commit those files, use --no-verify option" "$TEXT_DEFAULT"
exit 1
else
echo -e "$TEXT_INFO" "All files are clean." "$TEXT_DEFAULT"
exit 0
fi
@jasonkarns
Copy link

Also take a look at git-hooks for managing hooks across repos (can be installed global, per user, or per repo). Useful to avoid copy/pasta hooks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment