Modifying the Push Failure Condition after Lint Checks in Git Pre-Push Hook

Tuesday, March 11, 2025

Context of the Task

In our team's project, we have strict linting rules, including enforced import sorting. This ensures uniform code style, but occasionally, we faced lint errors in the CI after creating a PR.

While these instances were not frequent, dealing with a lint error meant running scripts locally to fix the errors, then committing and pushing the updated code. This was quite cumbersome and became a primary cause of extended code review times. Therefore, I suggested integrating lint checks into the pre-push hook to my team.

After gaining consensus, I employed the existing lint-fix:global script to craft a pre-push hook as follows:

echo "🔍 Running lint fix..."
pnpm run lint-fix:global

# Check for changes
if ! git diff --quiet; then
  echo "❌ Linting fixed some files. Please commit the changes before pushing."
  exit 1
fi

The following day, I received feedback. Some of you might have already spotted the problem in this code.

It turned out that regardless of whether lint-fix:global was executed, pushing with staged files would result in a git push failure. 🤦

I realized it was more appropriate to perform a simple lint error check rather than a lint fix, leading me to tweak the code as shown below:

echo "🔍 Running lint..."

if ! pnpm run lint -- --quiet; then
  echo "❌ Lint errors were detected."
  echo "👉 To automatically fix errors, run: pnpm run lint-fix:global"
  exit 1
fi

In the code above, the lint script effectively executes next lint. I used the --quiet option to print only errors. If an error occurs, a message is shown, preventing the push. Moreover, I revised the error message to be more friendly for my team members.

Hopefully, going forward, we will no longer waste time on lint errors within the CI. 🙏