Skip to content

Instantly share code, notes, and snippets.

@danielwestendorf
Last active May 6, 2021 15:38
Show Gist options
  • Save danielwestendorf/5776c5c80de36e0399a6701ccd044e43 to your computer and use it in GitHub Desktop.
Save danielwestendorf/5776c5c80de36e0399a6701ccd044e43 to your computer and use it in GitHub Desktop.
Enforce codestyle automatically on git commit
#!/bin/sh
# Create this file here: ./.git/hooks/pre-commit
# chmod +x ./.git/hooks/pre-commit
.git/hooks/pre-commit-format-js
.git/hooks/pre-commit-format-ruby
#!/bin/sh
# .Create this file here:/.git/hooks/pre-commit-format-js
# chmod +x ./.git/hooks/pre-commit-format-js
jsfiles=$(git diff --cached --name-only --diff-filter=ACM "*.js" | tr '\n' ' ')
[ -z "$jsfiles" ] && exit 0
# Standardize all ruby files
echo "💅 Automatically formatting staged javascript files using eslint ($(echo $jsfiles | wc -w | awk '{print $1}') total)"
echo "$jsfiles" | xargs yarn run eslint --no-ignore --fix
result=$?
# Add back the modified/prettified files to staging
echo "$jsfiles" | xargs git add
# Replace $result with 0 if you don't want this hook to block your commit
# exit 0
exit $result
#!/bin/sh
# .Create this file here:/.git/hooks/pre-commit-format-ruby
# chmod +x ./.git/hooks/pre-commit-format-ruby
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
result=$?
# Add back the modified/prettified files to staging
echo "$rubyfiles" | xargs git add
# Replace $result with 0 if you don't want this hook to block your commit
# exit 0
exit $result
@danielwestendorf
Copy link
Author

Create these files in the projects .git/hooks directory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment