Created
February 6, 2015 17:46
-
-
Save jhartikainen/36a955f3bfe06557e16e to your computer and use it in GitHub Desktop.
ESLint git commit hook
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/bash | |
files=$(git diff --cached --name-only | grep '\.js$') | |
# Prevent ESLint help message if no files matched | |
if [[ $files = "" ]] ; then | |
exit 0 | |
fi | |
echo $files | xargs eslint | |
rc=$? | |
if [[ $rc != 0 ]] ; then | |
echo "ESLint check failed, commit denied" | |
exit $rc | |
fi |
Mixed both solutions for eslint
#!/bin/bash
files=$(git diff --cached --name-only | grep '\.jsx\?$')
# Prevent ESLint help message if no files matched
if [[ $files = "" ]] ; then
exit 0
fi
failed=0
for file in ${files}; do
git show :$file | eslint --stdin --stdin-filename $file
if [[ $? != 0 ]] ; then
failed=1
fi
done;
if [[ $failed != 0 ]] ; then
echo "ESLint check failed, commit denied"
exit $failed
fi
There is a bug with selecting deleted files. You may change selector to:
git diff --cached --name-status | grep '^\(A\|M\).*\.jsx\?$' | sed 's/^[AM]//g'
A more-generic version that'll also work for [added/modified/untracked] files:
# returns added (A), modified (M), untracked (??) filenames
function git_changed_files {
echo $(git status -s | grep -E '[AM?]+\s.+?\.js$' | cut -c3-)
}
# run lint over changed files, if any
alias lint='(files=$(git_changed_files); if [ ! -z "${files}" ]; then eslint $files; fi)'
alias for zsh:
alias lint='(files=$(git_changed_files); if [[ -n $files ]]; then eslint ${=files}; fi)'
So apparently GitHub doesn't notify me of comments on my Gists. Thanks for all the suggestions :)
I think you could use git diff --staged --diff-filter=AM --name-only
to shorten down file status selection
One liner for using at package.json
:
"lint-staged": "eslint `git diff --staged --diff-filter=AM --name-only | grep .js$ | tr '\n' ' '`"
It runs like eslint [file1] [file2] [file3] [etc]
for all staged added/modified files
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One caveat. If you modify a file after staging it, the git-hook will run eslint against the file as-is and not as-is-staged.
How we lint our staged files.