Git Hooks: Automated Checks Before Push

Git Hooks: Automated Checks Before Push

David Hartl

21. Juli 2024

CI/CD

DevOps

Software Development

What are Git Hooks?

Git hooks are scripts that Git executes at specific events. They enable developers to define automated checks and actions that occur before or after certain Git operations such as commit, merge, or push. This helps in early detection of errors and maintaining code quality.

The Pre-Push Hook in Detail

A pre-push hook is executed before a `git push` command actually transfers changes to the remote repository. Here is an example of a pre-push hook script that performs various checks:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
bash needs-rebase.sh \
  && node tools/check-schematics.js \
  && node tools/depcheck.js \
  && pnpm nx format:check --base origin/develop --head HEAD \
  && pnpm nx print-affected --target build --select tasks.target.project --base origin/develop --head HEAD

Let's take a closer look at the individual steps of this script:
1. Initialization with Husk:

sh
. "$(dirname "$0")/_/husky.sh"

This loads the Husky script, which facilitates the execution of Git hooks.

2. Rebase Check:

sh
bash needs-rebase.sh

This script checks if a rebase is required before the changes can be pushed. It ensures that the local branch is up to date and conflicts are avoided.

3. Dependency Check:

sh
node tools/depcheck.js

This script verifies that all necessary dependencies are present and that there are no unnecessary dependencies in the project.

4. Format Check:

sh
pnpm nx format:check --base origin/develop --head HEAD

This step checks if the code adheres to formatting guidelines. It compares the changes with the `origin/develop` branch and ensures that the code is consistently formatted.

5. Build Check:

sh
pnpm nx print-affected --target build --select tasks.target.project --base origin/develop --head HEA

  Finally, this step checks which projects are affected by the build based on the changes. This helps in early detection of potential issues and ensures a successful build.

Summary

Using Git hooks like the pre-push hook is an excellent method to ensure code quality and consistency in a project. By automating checks before the push, many potential issues can be identified and resolved early, leading to a more stable and reliable codebase.

Integrating such automated checks into the development process allows teams to work more efficiently and ensures that only reviewed and high-quality code reaches the central repository. Try it out and experience the difference in your code quality!