Using git's pre-commit hook

Git hooks are triggered when important events occur, such as before a commit is executed or after a commit is completed. They are designed to introduce custom workflows by running a script when the hook is triggered.

In this article, we use the pre-commit hook to perform a linter check and a vulnerability check. The commit is only allowed if both checks are successful.


Setup

  1. Navigate into .git/hooks directory.
  2. Create a new script file and name it pre-commit.
  3. Make it executable with chmod +x.

Implementation

In this script file, we want to run two commands: Brakeman and Rubocop, to check our application code.

#!/bin/bash

set -e

echo "Running pre-commit checks..."

echo "Running RuboCop..."
if ! bundle exec rubocop; then
  echo "RuboCop failed. Please fix the issues and try again."
  exit 1
fi

echo "Running Brakeman..."
if ! bundle exec brakeman -q; then
  echo "Brakeman found security issues. Please fix them and try again."
  exit 1
fi

echo "All checks passed!"

Testing

  1. We modify some code to fail the Rubocop test.
  2. Then we try to commit the updated code.
$  git commit -m "Test"


Escape

Use the no-verify command to skip the script result.

$git commit -m "Message" --no-verify

AI Summary AI Summary
gpt-4.1-2025-04-14 2025-07-04 13:19:24
This article explains how to use Git’s pre-commit hook to automate code quality and security checks before allowing a commit. By integrating tools like Rubocop and Brakeman, developers can enforce standards and catch vulnerabilities, though the process can be bypassed using the --no-verify option.
Chrome On-device AI 2025-08-05 21:56:43

Share Share this Post