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_hooksdirectory. - 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 fidoneBest 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.