How do you set up a Git hook to run scripts during certain repository events?
Posted by PaulAnd
Last Updated: June 18, 2024
Git hooks are scripts that run automatically at certain points in the Git workflow. They allow you to automate tasks and enforce certain rules during specific Git events such as committing, pushing, or merging. Here's a guide on how to set up Git hooks in your repository.
Step 1: Navigate to the Hooks Directory
In your local Git repository, navigate to the .git/hooks directory. This directory contains sample hook scripts that Git provides by default.
cd path/to/your/repo/.git/hooks
Step 2: Choose a Hook to Set Up
Here are some commonly used hooks: - pre-commit: Runs before a commit is finalized. Great for running linters or tests. - post-commit: Runs after a commit has been made. Useful for notifications or further scripts. - pre-push: Runs before pushing to a remote. Can be used to run tests or checks to ensure the integrity before a push. - post-merge: Runs after a successful merge. Useful for updating dependencies or compiling code.
Step 3: Create or Modify a Hook Script
1. Create a new hook: You can create a new hook script by simply creating a file with the name of the hook you want to use, for example, pre-commit.
touch pre-commit
2. Make the hook executable: Ensure the script has executable permissions.
chmod +x pre-commit
3. Edit the hook script: Use your favorite text editor to add logic to the script. Here’s an example of a simple pre-commit hook that checks for a specific string in staged files:
#!/bin/bash

# Example pre-commit hook script
if git diff --cached --name-only | grep '\.js$' | xargs grep -n 'TODO'; then
    echo "Commit aborted: please remove TODO comments."
    exit 1
fi
Step 4: Use Your Hook Script
Once you’ve created and configured your hook script, it will trigger automatically when the corresponding Git event occurs. For example, if you've set up a pre-commit hook, it will run every time you attempt to make a commit.
Step 5: Share Hooks (Optional)
By default, the hooks are not versioned with your repository. If you want to