Here are two potential issues with your script:
- The file may not have the executable flags set
- Your sub shell expression seems to be incorrect
In order for Git to execute properly on unixoid systems, it requires the correct executable flags.
$ chmod ug+x .git/hooks/pre-commit
If you haven't encountered any error messages yet, this could be the reason for it.
Additionally, there is a syntax error in your script:
a=("${(f)$(git diff --name-only | grep -E '(.js)$')}")
e=$(eslint -c eslint.json $a)
A better approach would be:
a="$( git diff --name-only | grep -E '(.js)$' )"
e=$( eslint -c eslint.json $a )
Further Enhancements
Simplify result checking
When eslint
finds an error, it exits with a non-zero exit code.
eslint ${ESLINT_CONF} $( ... )
if [ $? -ne 0 ]; then
echo "eslint has detected errors."
exit 1
fi
If no echo
message is needed, simply having the eslint
statement at the end will cause the shell to exit based on that command's exit code.
Keep in mind that using the exit code method does not allow you to detect warnings since eslint
exits with a positive code (zero) for warnings.
Include New Files in Checks
The current git diff
statement won't include newly added files. Consider using git status
instead:
git status --porcelain | awk '{print $2}' | grep -E '(.js)$'
Finalized Script
#!/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
Alternatively, a simplified version...
#!/bin/sh
ESLINT_CONF=".eslintrc.json"
eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) >/dev/null
Or, with warning checks implemented...
#!/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
(scripts 1 and 2) or echo "${RES}"
(script 3) to display the eslint output.