Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

git - How do I activate a pre-receive hook in GitLab?

I need to check each commit coming into GitLab and block any of them which have a certain file in. I used the documentation here

I have created a file named pre-receive in the .git/custom_hooks directory.

The file just has the contents:

exit 1

Which, I believe, should reject any attempt to push code to the repo (?)

The file is owned by git and is executable:

ls -a gives the response:

-rwxrwxrwx 1 git root 550 ...

But all commits go through without issue, the commit hook does not seem to activate in any way.

I do not see anything else in the documentation that I am supposed to do. Have I missed anything?

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way to do that is to set a pre-commit hook on your local machine, and check for the presence of said file among the staged files :

# .git/hooks/pre-comit :


forbidden=$(git diff --cached --diff-filter=ACMR -- forbidden/file)

if [ -n "$forbidden" ]; then
    echo "*** rejecting commit, file '$forbidden' is present" >&2
    exit 1

One major benefit is : you (or other users) are informed right now that this file should not be committed, rather than later when the push is rejected.

Downsides are :

  • this hook must be installed once per clone of your repo
  • a user can skip that hook (uninstall it manually, modify the hook script, or run git commit -n to skip pre-commit and commit-msg hooks)

If you need to be 100% positive this file does not reach the central repo, one way to prevent this is indeed to set a pre-receive hook, but this hook must be set on the server.

You tagged your question gitlab, here is the documentation page to set such a hook :


You need to access your gitlab's install filesystem (e.g : ssh to gitlab's server with the admin account), and set the pre-receive hook in the appropriate project(s).

Note that, since a user can push a whole branch (or even several branches) in one go, you should check the presence of said file in all new commits pushed to the server, not just the tip of each branch.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share