Pre Commit Git Hook

Git hooks are custom scripts that Git runs before or after certain events, such as commits or merges. They provide a way to automate tasks and enforce policies. The pre-commit hook is particularly useful because it runs before the commit process, letting you inspect the changes and decide whether to proceed.

Pre-Commit Hook Primer

  1. Location: Git hooks are located in the .git/hooks directory inside your repository.

  2. Activation: To activate a pre-commit hook, create an executable file named pre-commit in this directory.

  3. Content: A pre-commit hook script typically checks staged changes for specific criteria. If the script exits with a non-zero status, the commit is blocked.

Example: Pre-Commit Hook to Prevent Debugging Code

This example checks for console.log (JavaScript) and debugger statements to prevent commits with debugging code.

#!/bin/bash

# A file pattern that contains debugging code
DEBUG_PATTERN='(console\.log|debugger)'

# Grep for the pattern in staged files
if git diff --cached -G "$DEBUG_PATTERN" --name-only | grep -E '.js$'
then
  echo "ERROR: Debugging statements (console.log/debugger) found in staged files."
  echo "Please remove these before committing."
  exit 1
else
  echo "No debugging code detected. Proceeding with commit."
fi

Explanation:

  1. The #!/bin/bash specifies that this is a Bash script.
  2. The DEBUG_PATTERN variable holds a regex pattern for finding debugging statements.
  3. git diff --cached shows changes staged for commit, and the -G option searches for patterns.
  4. The grep -E '.js$' filters for JavaScript files.
  5. If a file matches the pattern, a message is displayed, and the script exits with exit 1, blocking the commit.

Make the script executable using chmod +x .git/hooks/pre-commit.

Note: Customize the pattern and file extensions as per your project's requirements.