hello


Debugging statements like console.log (for JavaScript) and dd (for PHP) can clutter codebases. Learn how to set up Git hooks to prevent pushes containing these statements and enforce coding standards in your projects.


During development, debugging statements can accidentally end up in production code, impacting its quality. To maintain a clean codebase and enforce coding standards, let’s implement Git hooks to block pushes containing debugging statements and ensure adherence to specified guidelines in any project.

  • Locate Your Git Hooks Directory Find or create the .git/hooks directory in your project where Git executes scripts during specific events.
  • Available Git Hooks Git provides various hooks that trigger at different stages. Here are some hooks you might consider implementing:

captionless image


  • Implementing Pre-Push Hook for Debugging Statements Open the pre-push file in a text editor and add the following Bash script:

#!/bin/bash
# Redirect output to stderr
exec 1>&2
# Check for console.log, dd, or 'not-allowed' in the staged changes
if git diff --cached | grep -q -E 'console\.log|dd|\/\/\s*not-allowed'; then
    echo "Error: Debugging statements found in the changes or 'not-allowed' tag detected. Please remove them before pushing."
    exit 1
fi
# If none found, allow the push
exit 0
  • Implement Other Hooks (Optional) Depending on your needs, customize other hooks (e.g., pre-commit, prepare-commit-msg) to enforce coding standards, run tests, or perform additional checks.

By leveraging Git hooks at various stages of the development workflow, you can enforce coding standards, prevent the inclusion of debugging statements, or run tests before committing or pushing code. The provided pre-push hook specifically checks for console.log, dd statements, or a specified comment tag like // not-allowed to ensure clean commits.

Consider this sample JavaScript code snippet with a dedicated // not-allowed comment section:


function exampleFunction() {
    console.log('Debug: This is a console.log statement')
    // more code...
    // not-allowed section
    // This section not allowed to contain console.log
    function restrictedArea() {
        // code...
    }
}

Utilizing Git hooks at different stages of development enables you to enforce coding standards, perform checks, and ensure a clean codebase across various projects and programming languages. Configuring these hooks allows you to prevent accidental inclusion of debugging statements and maintain code quality throughout the development process.

Get In Touch

Although I’m not currently looking for any new opportunities, my inbox is always open. Whether you have a question or just want to say hi, I’ll try my best to get back to you!

Send a Message

Designed & Built by Youssef Jounaid