Last active
November 8, 2021 05:30
-
-
Save ardislu/73a29a6cb9492813a393d2337908eb5a to your computer and use it in GitHub Desktop.
git hook for a common use case: linting staged files before commit. Pipes all staged JS or TS files to eslint, and all CSS or SCSS files to stylelint. Assuming eslint and stylelint are node modules installed in the same root as the git repo.
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
#!/usr/bin/env bash | |
root="$(git rev-parse --show-toplevel)" # Full file path to the directory where this git repo sits | |
cd "$root" # Required to make the relative file paths to eslint and stylelint work | |
for file in $(git diff --name-only --cached) # List of staged files | |
do | |
filename="${file##*/}" # Remove all except the characters after the last '/' | |
extension="${filename##*.}" # Remove all except the characters after the last '.' | |
if [[ "$extension" =~ ^(js|ts)$ ]]; then | |
# Must pipe the output from 'git show' to the linter, do NOT directly run the linter | |
# on the file because that may contain changes that have been saved but not staged yet. | |
git show ":$file" | ./node_modules/.bin/eslint --stdin --stdin-filename "$filename" | |
if [ $? -ne 0 ]; then | |
echo "eslint failed on ${file}, aborting commit." | |
exit 1 | |
fi | |
fi | |
if [[ "$extension" =~ ^(css|scss)$ ]]; then | |
# Must pipe the output from 'git show' to the linter, do NOT directly run the linter | |
# on the file because that may contain changes that have been saved but not staged yet. | |
git show ":$file" | ./node_modules/.bin/stylelint --stdin --stdin-filename "$filename" | |
if [ $? -ne 0 ]; then | |
echo "stylelint failed on ${file}, aborting commit." | |
exit 1 | |
fi | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment