Instantly share code, notes, and snippets.

@danott danott/pre-commit
Last active Jan 18, 2019

Embed
What would you like to do?
A git hook that automatically formats JavaScript and Ruby code on commit
#!/bin/sh
# ./.git/hooks/pre-commit
.git/hooks/pre-commit-format-javascript
.git/hooks/pre-commit-format-ruby
#!/bin/sh
# ./.git/hooks/pre-commit-format-javascript
# Assumption: npm/yarn has installed the prettier package
# Based on the bash script prescribed at https://prettier.io/docs/en/precommit.html#option-5-bash-script
jsfiles=$(git diff --cached --name-only --diff-filter=ACM "*.js" "*.jsx" | tr '\n' ' ')
[ -z "$jsfiles" ] && exit 0
# Prettify all staged .js files
echo "💅 Automatically formatting staged Javascript files using prettier ($(echo $jsfiles | wc -w | awk '{print $1}') total)"
echo "$jsfiles" | xargs ./node_modules/.bin/prettier --write --loglevel=error
# Add back the modified/prettified files to staging
echo "$jsfiles" | xargs git add
exit 0
#!/bin/sh
# ./.git/hooks/pre-commit-format-ruby
# Assumption: bundler has installed the standard gem
# Based on the bash script prescribed at https://prettier.io/docs/en/precommit.html#option-5-bash-script
rubyfiles=$(git diff --cached --name-only --diff-filter=ACM "*.rb" "*.rake" "Gemfile" "Rakefile" | tr '\n' ' ')
[ -z "$rubyfiles" ] && exit 0
# Standardize all ruby files
echo "💅 Automatically formatting staged Ruby files using standardrb ($(echo $rubyfiles | wc -w | awk '{print $1}') total)"
echo "$rubyfiles" | xargs bundle exec standardrb --fix
# Add back the modified/prettified files to staging
echo "$rubyfiles" | xargs git add
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment