Force commits to pass TSLint

Story

I was recently working on a project and multiple collaborators started to contribute to. All seemed fine until one day, I synced up with the master branch and had 100 warnings pop up in VSCode. I thought about buying my hot dog cart and moving to a beach area finally.

 

hotdogcart.jpg

Being totally honest, that cart near the beach looks way more fun than sitting behind a desk staring at a beam of light sucking my soul away sometimes, but that’s just me. You are different and still love programming, because you’re young and full of energy. You’ll mature once you realize you attend meetings that could have been emails for years.

At any rate, lets get back to the issue.

So here I was staring at 100+ warnings all related to TSLint. At first, I thought, “Damn, I’m gonna Macho Man Randy Savage elbow drop someone.”

elbowdrop.gif

I then started thinking “how could they commit with these warnings?”, it turned out I had the TSLint extension for VSCode installed and they did not, so they never seen the warnings as they worked on the project. Worse yet, nothing was in place to warn them or prevent the code from being committed.

The Solution

We already use a precommit hook that runs Prettier against files so it was a simple step to add tslint to run during the precommit hook we have in our project.

"lint-staged": {
    "*.ts": [
      "tslint",
      "prettier --write",
      "git add"
    ]
  }

The above basically runs on all the TypeScript files and runs `tslint` then `prettier` and last `git add`.

As for how this gets executed I have a brief write up on adding a precommit hook for Prettier. Which outlines the dependencies on `husky` and `lint-staged`. If you don’t want to look at that, then add the following as a script in your package.json `scripts` section:

    "precommit": "lint-staged",

Be sure to add the dependencies to your project as well under the `devDependencies`: `lint-staged` and `husky`.

Now when someone tries to commit files to the repo their files will be ran against `tslint` (at this point I shouldn’t have to tell you that you need it inside your project). If all the tslint checks pass then the commit works, if not you’ll have errors with your git logs.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s