Welcome to the Git Server-side Hooks tutorial! šÆ
In this lesson, we'll dive into the fascinating world of Git hooks. These are scripts that run automatically on your Git server (like GitHub, GitLab, or Bitbucket) in response to specific events. By creating and customizing your own hooks, you can automate and secure your Git workflow.
Let's get started! š
š Definition: Git hooks are scripts located in the .git/hooks directory of your Git repository. They are executed automatically by the Git server in response to certain events, such as commit, push, and receive.
Git hooks can be classified into two main categories:
š” Pro Tip: By default, server-side hooks are disabled on GitHub and GitLab. To enable them, you'll need to make the scripts executable.
Settings tab.Webhooks section and click on Add webhook.Payload URL field with the URL of your server-side hook script.Active checkbox and click on Add webhook.š Note: Server-side hooks are written in shell script (.sh), but you can also use other languages like Python, Ruby, or JavaScript.
.git/hooks directory with a name corresponding to the event you want to hook into (e.g., post-receive).chmod +x <script-name>.Let's create a script that requires commit messages to follow a specific format.
#!/bin/sh
# Check if the commit message is in the format: <type>: <subject>
if [[ $(git rev-parse HEAD) = $(git rev-parse --short HEAD)^ ]]; then
if [[ $(git log -1 --format=%s) != *:* ]]; then
echo "Invalid commit message format. Please use <type>: <subject>"
exit 1
fi
fi
exit 0Save this script as commit-msg in your repository's .git/hooks directory, make it executable (chmod +x commit-msg), and test it out!
This script blocks pushes if a blacklisted word is found in any commit message.
#!/bin/sh
# List of blacklisted words
BLACKLIST=("secret" "confidential" "password")
# Iterate through the commit messages
for commit in $(git log --format=%s --grep-file=blacklist.txt); do
if [[ $commit =~ .*(secret|confidential|password).* ]]; then
echo "Commit message contains a blacklisted word. Push aborted."
exit 1
fi
done
exit 0Save this script as pre-push in your repository's .git/hooks directory, make it executable (chmod +x pre-push), and test it out!
What is the purpose of Git server-side hooks?