Skip to content

Instantly share code, notes, and snippets.

@bobrippling
Created December 3, 2019 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobrippling/24c74e948d8a5fbc27ac1b3bb6f6c089 to your computer and use it in GitHub Desktop.
Save bobrippling/24c74e948d8a5fbc27ac1b3bb6f6c089 to your computer and use it in GitHub Desktop.
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