Using Pre-Receive Hooks in GitLab
Introduction
Section titled “Introduction”Pre-receive hooks allow custom validation scripts to run on the GitLab server before commits are accepted.
Creating a Pre-Receive Hook
Section titled “Creating a Pre-Receive Hook”- On the GitLab server, navigate to the repository’s
custom_hooks
directory. - Create an executable script named
pre-receive
. - Implement checks such as validating commit messages, scanning for secrets, or enforcing file size limits.
- Save the script and ensure it has execute permission:
Terminal window chmod +x pre-receive
Example: Block Missing JIRA ID
Section titled “Example: Block Missing JIRA ID”#!/bin/shwhile read oldrev newrev refname; do if ! git log --format=%s $oldrev..$newrev | grep -q '^[A-Z]\+-[0-9]\+'; then echo "JIRA ID missing in commit message" >&2 exit 1 fidone
Best Practices
Section titled “Best Practices”- Keep hook scripts in version control for traceability.
- Log hook failures to assist developers.
- Test hooks in a staging environment before production use.