Reputation: 656
how i can run in the pre commit script eslint on the files in the add stage?
I have in the hooks folder the .eslintrc file.
I have also the script:
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".
function lintit () {
a=("${(f)$(git diff --name-only | grep -E '(.js)$')}")
e=$(eslint -c eslint.json $a)
echo $e
if [[ "$e" != *"0 problems"* ]]; then
echo "ERROR: Check eslint hints."
exit 1 # reject
fi
}
lintit
but it doesn't do the eslint i have in the .eslintc file.
Thanks!
Upvotes: 3
Views: 1152
Reputation: 7634
I see two (possible) issues with your script:
Git won't execute unless it has proper executable flags on unixoid systems.
$ chmod ug+x .git/hooks/pre-commit
If you haven't seen any error message yet, it's probably due to this.
But, however this is not correct, it's a syntax error:
a=("${(f)$(git diff --name-only | grep -E '(.js)$')}")
e=$(eslint -c eslint.json $a)
Better:
a="$( git diff --name-only | grep -E '(.js)$' )"
e=$( eslint -c eslint.json $a )
eslint will exit with a negative (non-zero) exit code if it has found an error.
eslint ${ESLINT_CONF} $( ... )
if [ $? -ne 0 ]; then
echo "eslint is unhappy."
exit 1
fi
If no echo
is required it would be enough to have the eslint
statement at the last line, so the shell will exit with that command's exit code.
But, the downside of using the exit code is, that, since eslint does exit with a positive code (zero) on warnings, you won't be able to detect warnings. In that case you still have to match for warnings.
Your git diff
expression won't find new files. You may want to use git status
instead:
git status --porcelain | awk '{print $2}' | grep -E '(.js)$'
#!/bin/sh
ESLINT_CONF=".eslintrc.json"
eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) >/dev/null
if [ $? -ne 0 ]; then
echo "ERROR: Check eslint hints."
exit 1
fi
exit 0
Or, simplified ...
#!/bin/sh
ESLINT_CONF=".eslintrc.json"
eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) >/dev/null
Or, with check for warnings ...
#!/bin/sh
ESLINT_CONF=".eslintrc.json"
RES="( eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) )"
if [ $? -ne 0 ] || [[ "${RES}" != *"0 warning"* ]]; then
echo "ERROR: Check eslint hints."
exit 1
fi
Remove >/dev/null
(script 1 and 2) or echo "${RES}"
(script 3) to show the output of eslint.
Upvotes: 4