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

echo "Linting Your Code:"
# Run tslint and get the output and return code
tslint=$(npm run tslint)
# 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"
printf "${GREEN}tslint passed.${NC}\n"
exit 0
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!


How to add precommit hook linter

Customizing Precommit Hooks