Skip to content

Instantly share code, notes, and snippets.

@ardislu
Last active November 8, 2021 05:30
Show Gist options
  • Save ardislu/73a29a6cb9492813a393d2337908eb5a to your computer and use it in GitHub Desktop.
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.
#!/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