Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@Moeriki

This comment has been minimized.

Copy link

@Moeriki Moeriki commented Feb 6, 2015

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.

for file in ${files}; do
  result=$(git show :$file | jshint)
  ...
done
@brunops

This comment has been minimized.

Copy link

@brunops 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

This comment has been minimized.

Copy link

@laktarugar laktarugar commented Oct 13, 2015

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

This comment has been minimized.

Copy link

@alextreppass alextreppass commented Dec 10, 2015

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

This comment has been minimized.

Copy link
Owner Author

@jhartikainen jhartikainen commented Oct 28, 2016

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

@shorinji

This comment has been minimized.

Copy link

@shorinji shorinji commented Jan 18, 2017

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

@enapupe

This comment has been minimized.

Copy link

@enapupe 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