Working with Git Hooks: An Introduction

Working with Git Hooks: An Introduction

·

4 min read

Git hooks are scripts that Git executes before or after certain events such as committing, pushing, or receiving changes. They are a powerful way to automate tasks and enforce policies in your Git workflow. This guide will introduce you to Git hooks and show you how to use them effectively.

What Are Git Hooks?

Git hooks are custom scripts that run automatically when certain Git events occur. They can be used for a variety of purposes, such as:

  • Enforcing code quality standards

  • Running tests before allowing a commit

  • Sending notifications

  • Formatting code

  • Automating deployments

Types of Git Hooks

Git hooks are categorized into client-side and server-side hooks:

  1. Client-Side Hooks: These hooks run on your local machine and are typically used to automate tasks related to commits, merges, and other local operations.

    • Pre-Commit Hook: Runs before a commit is created. It’s commonly used to check the code quality or run tests.

    • Prepare-Commit-Message Hook: Runs before the commit message editor is fired up. It’s used to prepare the default commit message.

    • Commit-Message Hook: Runs after the commit message is created but before the commit is finalized. It’s used to verify or modify the commit message.

    • Post-Commit Hook: Runs after a commit is made. It’s often used for notifications or to perform follow-up actions like pushing the commit.

    • Pre-Push Hook: Runs before any push to a remote repository. It’s used to validate changes before they are pushed.

  2. Server-Side Hooks: These hooks run on the remote repository server and are used to enforce policies or perform actions when changes are pushed to the repository.

    • Pre-Receive Hook: Runs before any changes are accepted by the remote repository. It can be used to enforce policies.

    • Update Hook: Runs after the pre-receive hook but before the changes are applied. It’s used to enforce branch-specific policies.

    • Post-Receive Hook: Runs after the changes are accepted. It’s used for notifications and deployments.

How to Set Up Git Hooks

Git hooks are stored in the .git/hooks directory of your repository. By default, this directory contains sample scripts that can be modified to suit your needs.

  1. Locate the Hooks Directory:

     cd your-repo/.git/hooks
    
  2. Create or Modify a Hook Script: Hooks are shell scripts (or any executable file). To create a pre-commit hook, for example:

     touch pre-commit
     chmod +x pre-commit
    
  3. Edit the Hook Script: Open pre-commit in your favorite text editor and add your custom logic. For example, to prevent commits with messages containing "WIP":

     #!/bin/sh
     if git log -1 | grep -q "WIP"; then
       echo "Aborting commit: Work in Progress (WIP) commits are not allowed."
       exit 1
     fi
    

Example: Pre-Commit Hook to Run Tests

Here's an example of a pre-commit hook that runs tests before allowing a commit:

    #!/bin/sh
    # Run tests before committing
    npm test
    if [ $? -ne 0 ]; then
      echo "Tests failed, commit aborted."
      exit 1
    fi

Example: Post-Commit Hook to Notify Team

Here's an example of a post-commit hook that sends a notification after a commit:

    #!/bin/sh
    # Send a notification after committing
    commit_message=$(git log -1 --pretty=format:%s)
    curl -X POST -H 'Content-type: application/json' \
    --data '{"text":"New commit: '"$commit_message"'"}' \
    https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK

Best Practices for Using Git Hooks

  • Keep Hooks Simple: Hooks should be straightforward and quick to run to avoid slowing down your workflow.

  • Make Hooks Shareable: Store your hooks in a version-controlled directory and create symlinks in .git/hooks to share them with your team.

  • Use a Hook Manager: Consider using tools like Husky for JavaScript projects or pre-commit for Python projects to manage hooks more easily.

Here's a visual representation of where Git hooks fit into the Git workflow:

        Client-Side Hooks
           (Local Repository)
      ----------------------------------
      | Pre-Commit | Commit-Message   |
      | Prepare-Commit-Message        |
      | Post-Commit  | Pre-Push       |
      ----------------------------------

                 |
                 V

          Server-Side Hooks
           (Remote Repository)
      ----------------------------------
      | Pre-Receive  | Update          |
      | Post-Receive                   |
      ----------------------------------

Conclusion

Git hooks are a powerful tool to automate and enforce policies in your Git workflow. By understanding and utilizing hooks, you can significantly enhance your development process, ensuring higher code quality and smoother operations. Start by setting up basic hooks, and gradually integrate more complex automation as needed.