Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
prettier pre-commit git hook
#!/bin/sh
set -e
exec 1>&2
warn(){
printf '\x1b[31m%s\x1b[0m\n' "$*" >&2
}
projroot=.
emptyblob=e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
if ! test -e "$projroot/node_modules/.bin/prettier"
then
warn "prettier npm module not found, skipping prettier"
exit 0
fi
blacklist=/tmp/$$.blacklist
trap "rm -f '$blacklist'" EXIT
cat >"$blacklist" <<!
.eslintrc.js
!
check_files(){
extension="$1"
shift
git diff-index --cached --name-only --diff-filter=ACM HEAD -- "$@" \
| while read file
do
if grep -F "$(basename "$file")" "$blacklist" >/dev/null
then
echo >&2 "not prettifying '$file' - blacklisted"
continue
fi
newblob=$(git show :"$file" \
| (cd "$projroot" && node_modules/.bin/prettier --stdin-filepath "a.$extension") \
| git hash-object -w --stdin)
if test $(git rev-parse :"$file") != $newblob
then
if test $newblob = $emptyblob
then
# prettier gave us nothing - emitted an error
echo "prettier error on $file" >&2
exit 1
fi
warn "prettier changed \"$file\""
git update-index --cacheinfo 100644 $newblob "$file"
fi
done
}
check_files js '*.js' '*.jsx'
check_files less '*.less'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment