Preventing Garbage Code from Entering Your Git Repository

I was just reminded of a successful approach to prevent problematic code from contaminating our codebase from a previous project. In our project we used HTML, PHP, JavaScript, CSS and we frequently had failed deployments to our staging server due to syntax errors. With multiple devs working and users performing UAT on this server it really slowed us down. The following quality control measures dramatically increased our team’s velocity and stability.

Git pre-commit hook

Git can run a bash script before a commit happens using a pre-commit hook. Our team created this bash script that looped through the committed files and ran various checks on them to make sure they met criteria agreed by the dev team.

Coding Standards in PHP

For the main language of PHP, we used two tools, the first being the PHP Interpreter to ensure that the PHP could compile, and then a linter that would ensure that the PHP was also meeting the team’s agreed upon coding standards.

Blacklisted items

We had to create a special list of items and functions that we did not want to see in the code base. This included:

Debugging functions like vardump()

Merge conflict markers (<<<<<<<, =======, >>>>>>>)

These checks were manually added in bash. These blacklisted items applied to both PHP and JavaScript.

JavaScript

Separately, we used another tool to validate the JavaScript before allowing it in our repository. This area is much more mature in terms of tools than when we implemented this.

Drawbacks

Since we used this technique, DevOps has gotten more sophisticated and a lot of these checks are usually put in the DevOps pipeline. However, for large code bases this can give a more immediate feedback to the developer.

Developers need to set up tools on their local machine.

If a developer wanted to, they could bypass this, so putting these checks in the DevOps pipeline is also a good idea these days, especially for open-source software.

Summary

Focusing on these areas above to make sure the code worked with the interpreter and met the team’s agreed upon standards reduced the amount of time that our server was down and increased the team velocity.

Reference

Git pre-commit hook example on GitHub