Skip to content

Instantly share code, notes, and snippets.

@kopkaa
Forked from broofa/pre-commit
Last active February 26, 2024 08:18
Show Gist options
  • Select an option

  • Save kopkaa/41aa960a16c3c8b63f47d9634adf6cf2 to your computer and use it in GitHub Desktop.

Select an option

Save kopkaa/41aa960a16c3c8b63f47d9634adf6cf2 to your computer and use it in GitHub Desktop.
Git pre-commit hook that runs `eslint` with the `--fix` option to fix up issues where possible, and adds "fix"ed files into the commit
# #!/bin/bash
cd "$(git rev-parse --show-toplevel)"
ESLINT="frontend/node_modules/.bin/eslint"
pwd
if [[ ! -x "$ESLINT" ]]; then
printf "\t\033[41mPlease install ESlint\033[0m (npm install eslint)\n"
exit 1
fi
# Check if there are any staged files with the specified extensions
if ! git diff --cached --name-only --diff-filter=ACM | grep -qE "\.(ts|vue|js)$"; then
printf "\n\033[42mNo staged files with .ts, .js, or .vue extensions\033[0m\n"
exit 0
fi
STAGED_FILES=($(git diff --cached --name-only --diff-filter=ACM | grep -E "\.(ts|vue|js)$" 2>/dev/null))
echo "ESLinting ${#STAGED_FILES[@]} files"
$ESLINT "${STAGED_FILES[@]}" --fix
ESLINT_EXIT="$?"
# Re-add files since they may have been fixed
git add "${STAGED_FILES[@]}"
if [[ "${ESLINT_EXIT}" == 0 ]]; then
printf "\n\033[42mCOMMIT SUCCEEDED\033[0m\n"
else
printf "\n\033[41mCOMMIT FAILED:\033[0m Fix eslint errors and try again\n"
exit 1
fi
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment