Skip to content

Instantly share code, notes, and snippets.

@danott
Last active April 26, 2024 06:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danott/25c2bcb76697747f8ada23bd7c1d52d0 to your computer and use it in GitHub Desktop.
Save danott/25c2bcb76697747f8ada23bd7c1d52d0 to your computer and use it in GitHub Desktop.
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