Last active
July 23, 2024 21:51
-
-
Save danott/25c2bcb76697747f8ada23bd7c1d52d0 to your computer and use it in GitHub Desktop.
A git hook that automatically formats JavaScript and Ruby code on commit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# ./.git/hooks/pre-commit | |
.git/hooks/pre-commit-format-javascript | |
.git/hooks/pre-commit-format-ruby |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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