Skip to content

Instantly share code, notes, and snippets.

@ankjevel
Last active February 18, 2021 11:04
Show Gist options
  • Save ankjevel/0388c6d969f83a0a21473aab70e66707 to your computer and use it in GitHub Desktop.
Save ankjevel/0388c6d969f83a0a21473aab70e66707 to your computer and use it in GitHub Desktop.
run prettier and eslint on pre-commit
#!/usr/bin/env bash
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)
STAGED_ESLINT_FILES=$(echo "$STAGED_FILES"|grep -E "(ts|js)$")
STAGED_PRETTIER_FILES=$(echo "$STAGED_FILES"|grep -E "(ts|js|json|md)$")
BIN_DIRECTORY="$(git rev-parse --show-toplevel)/node_modules/.bin"
function eslint () {
if ! command -v ${BIN_DIRECTORY}/eslint &> /dev/null; then
exit 0
fi
echo "Checking eslint changes"
${BIN_DIRECTORY}/eslint --cache --quiet $@
}
function prettier () {
if ! command -v ${BIN_DIRECTORY}/prettier &> /dev/null; then
exit 0
fi
echo "Checking prettier changes"
${BIN_DIRECTORY}/prettier --check --loglevel warn $@
}
if [[ ! -z "$STAGED_ESLINT_FILES" ]]; then
eslint $STAGED_ESLINT_FILES
if [ $? -ne 0 ]; then
echo "eslint failed"
exit 1
fi
fi
if [[ ! -z "$STAGED_PRETTIER_FILES" ]]; then
prettier $STAGED_PRETTIER_FILES
if [ $? -ne 0 ]; then
echo "prettier failed"
exit 1
fi
fi
exit 0
@ankjevel
Copy link
Author

ankjevel commented Feb 18, 2021

To make it runnable on all pre-commits:

  • (create directory: mkdir -p ~/.git-hooks)
  • Move to directory ~/.git-hooks/
  • Make executable: chmod u+x ~/.git-hooks/pre-commit
  • update ~/.gitconfig with:
    [core]
          hooksPath = ~/.git-hooks
    

Now, it will be executed (on alla staged files) before a commit

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