Enabling Linting before git commit

Linting can be annoying

I once worked on an app with a dev lead that required we have a linter checking our code before it rendered a view. I’ll be honest: it was annoying since I was pressed for time on deadlines. But the motive for putting a linter in front of our rendering was designed to make me code better.

But its needed!

I recently had a situation where I needed to set up dev environment and needed high quality code. I couldn’t use Jenkins to lint because this app couldn’t work with it (yes, they do exist). But I still needed a way to automate linting and not depend on my developers to manually do it. Enter precommit hook for linters

How to

Precommit hooks run before you type in a commit message. We are going to customize our precommit file to run a typescript linter before our code can be committed.

  1. Navigate to your project’s .git/hooks folder
  2. There should be several files like pre-commit.sample. This is the file where you will add the linter
  3. Add the following code to your pre-commit.sample file

pass=true
RED='\033[1;31m'
GREEN='\033[0;32m'
NC='\033[0m'
echo "Linting Your Code:"
# Run tslint and get the output and return code
tslint=$(npm run tslint)
ret_code=$?
# If it didn't pass, announce it failed and print the output
if [ $ret_code != 0 ]; then
printf "\n${RED}tslint failed:${NC}"
echo "$tslint\n"
pass=false
else
printf "${GREEN}tslint passed.${NC}\n"
exit 0
fi
exit 1

4. Rename pre-commit.sample to pre-commit

Now when you type git commit, the linter will use tslint to lint your typescript files and report any linting errors BEFORE you commit your code!

Happy Coding!

Sources

How to add precommit hook linter

Customizing Precommit Hooks