DEV Community

Cover image for Console check before commit
Mitesh Kamat
Mitesh Kamat

Posted on

Console check before commit

Introduction

This post is about adding a git hook to check for console.log statements before code commit.

Developers tend to log variables, objects, api response, etc while writing our code. And yes it is fair enough but once we are done with our piece of code we often forget to remove those statements while committing our code.

But Git hooks helps us here.

I faced the same issue of getting rid of all the log statements in my code. so, I decided to use git hooks.
There are various options , but I chose pre-git

You can go through the link to explore about it.

To start off with pre-git, once you install the npm package you would have a .git folder in root of your project directory. Now navigate to hooks folder and locate pre-commit file and copy the below mentioned script and save.

#!/bin/sh

red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
no_color='\033[0m'

echo -e "\n${yellow}Executing pre-commit hook...${no_color}\n"

FILES_PATTERN='\.(js)(\..+)?$'
FORBIDDEN='console\.[clear|dir|log|info|warn|error]'

#check for console. references in your code

if git diff --cached --name-only | \
    grep -E $FILES_PATTERN | \
    xargs grep --with-filename -n $FORBIDDEN | \
    grep -v '//';
then
    echo -e "\n${red}COMMIT REJECTED!  Found console. references. Please remove them before committing.\n${no_color}"
    exit 1;
fi
echo -e "${green}No console. references found!${no_color}\n"
echo -e "${green}Git pre-commit hook was successful!${no_color}\n"
exit 0;

This script just checks for console. statements present in your project and prompts with appropriate message.

Commit would be rejected if it encounters any console statements.

I hope you find this useful.

Cheers !!

Top comments (3)

Collapse
 
rubenyebran profile image
Ruben Yebran

I have a question!
Should I replace the existing code with this one?
Or should I add it without removing the existing code?

Collapse
 
miteshkamat27 profile image
Mitesh Kamat

If you have any other checks apart from console, then you should add this else you can replace.

Collapse
 
nahukas profile image
Nahuel Castro

Hi! How can change the file extension to check js and jsx files?
Thanks!