Skip to content

Instantly share code, notes, and snippets.

@matthojo
Last active June 19, 2018 14:27
Show Gist options
  • Save matthojo/2a52d7e23d67f0a8b0e20bf9a6691943 to your computer and use it in GitHub Desktop.
Save matthojo/2a52d7e23d67f0a8b0e20bf9a6691943 to your computer and use it in GitHub Desktop.
Format JS and JSX code with `prettier-standard` on commit
#!/bin/sh
#
# A hook script to format JS and JSX files wth 'prettier-standard'.
# Called by "git commit" with no arguments.
#
# If formatting causes an empty commit, the commit will abort (`exit 1`).
#
# FAQ
# ====
#
# It's not running?!
# =====
# Try running `chmod +x .git/hooks/pre-commit`
#
# Changes are still in Git after the commit..
# =====
# See for a potential `post-commit` fix: https://github.com/prettier/prettier/issues/2978#issuecomment-354982956
#
STAGED_JS_FILES=$(git diff --cached --name-only --diff-filter=ACM "*.js" "*.jsx" | tr '\n' ' ')
# Don't run format code if there are no .js[x] files to format..
if [[ "$STAGED_JS_FILES" = "" ]]; then
exit 0
fi
echo "\nFormatting Javascript:\n"
# Check for prettier-standard
which ./node_modules/.bin/prettier-standard &> /dev/null
if [[ "$?" == 1 ]]; then
echo "\t\033[41mPrettier not setup on Project\033[0m"
exit 0
else
# Prettify all staged .js[x] files
echo "$STAGED_JS_FILES" | xargs ./node_modules/.bin/prettier-standard
# Add back the modified/prettified files to staging
echo "$STAGED_JS_FILES" | xargs git add
# Check to see if any files staged
# Abort if we zero staged files after formatting (empty commit)
if [[ $(git diff --cached --name-only | tr '\n' ' ') = "" ]]; then
echo "\nNo longer files staged, aborting commit.\n"
exit 1
fi
fi
# 🚀
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment