Skip to content

Instantly share code, notes, and snippets.

@jhartikainen
Created February 6, 2015 17:46
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save jhartikainen/36a955f3bfe06557e16e to your computer and use it in GitHub Desktop.
Save jhartikainen/36a955f3bfe06557e16e to your computer and use it in GitHub Desktop.
ESLint git commit hook
#!/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
@brunops
Copy link

brunops commented May 7, 2015

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

@laktarugar
Copy link

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'

@alextreppass
Copy link

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)'

@jhartikainen
Copy link
Author

So apparently GitHub doesn't notify me of comments on my Gists. Thanks for all the suggestions :)

@shorinji
Copy link

I think you could use git diff --staged --diff-filter=AM --name-only to shorten down file status selection

@enapupe
Copy link

enapupe commented Feb 7, 2017

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