Lint Typescript Before pushing with Pre Push Hooks

If you aren't linting your Typescript before pushing your code, you are probably pushing bugs.

Lint Typescript Before pushing with Pre Push Hooks

If you aren't linting your Typescript before pushing your code, you are probably pushing bugs.

USE CASE:

As a developer, you want to make sure you are pushing good code that passes tests and doesn't break any builds. One thing that can be done to assist with this is implementing a git pre-push hook.

This hook will run a script before your code is pushed to your version control remote. All you have to do is put it in the correct location. Easy Peasy.

WIP's:

We also have the need to push WIP (Work In Progress) from time to time. The following hook will look at the beginning of your last commit message for WIP: If the string is found, it wont run the linter.

ASSUMPTIONS:

You have an existing codebase that is tracking a remote and you have a .git directory in your project.

You also have eslint installed in your node_modules directory.

THE PROCESS:

We are going to create a pre-push-hook hook that will do all the work for us.

THE CODE:

#!/bin/bash

ROOT=$(git rev-parse --show-toplevel)
ESLINT="$ROOT/node_modules/.bin/eslint"
LOG="$SCRIPTPATH/../eslint.log"
LAST_COMMIT_MSG=$(cat $1 | grep "WIP:" | wc -l)

red=$(tput setaf 1)
magenta=$(tput setaf 5)
gold=$(tput setaf 3)
default=$(tput sgr0)

if [ ${LAST_COMMIT_MSG[*]} -gt 0 ]; then
  printf "WIP it GOOD!"
  exit 0
else
  # Check for eslint
  if [[ ! -x "$ESLINT" ]]; then
    printf "${red}\nESlint Is Requird to perform linting\n\n${default} Run ${gold}[${magenta}npm install eslint${gold}]${default} to install\n\n"
    exit 1
  fi

  PASS=true

  npx eslint $ROOT --ext .ts -c $ROOT/eslint.json >/dev/null 2>&1

  if [[ "$?" == 1 ]]; then
    PASS=false
  fi

  if $PASS; then
    printf "${magenta}\nProceeding with Push${default}\n"
    exit 0
  else
    printf "${red}\n\nLINTING FAILED\n\nPUSH ABORTED\n\n${default}Run ${gold}[${magenta}npm run lint${gold}]${default} for more details.\n\n"
    exit 1
  fi
fi
.git/hooks/pre-push-hook

IMPLEMENT:

By putting the file pre-push-hook file in the .git/hooks/ directory of your project, you will be good to go.

TROUBLESHOOTING:

You will need to give the pre-push-hook execute permissions or it wont run.

chmod +x .git/hooks/pre-push-hook