如何解决如何在 GitLab 中激活预接收挂钩?
我需要检查进入 GitLab 的每个提交并阻止其中包含特定文件的任何提交。我使用了文档 here
我在 pre-receive
目录中创建了一个名为 .git/custom_hooks
的文件。
文件只有内容:
#!/bin/sh
exit 1
我认为应该拒绝将代码推送到存储库的任何尝试 (?)
该文件归 git 所有并且是可执行的:
ls -a
给出响应:
-rwxrwxrwx 1 git root 550 ...
custom_hooks 目录也是可执行的,并且归 git 用户所有。
但是所有提交都没有问题,提交钩子似乎没有以任何方式激活。
我在文档中没有看到我应该做的任何其他事情。 我错过了什么吗?
解决方法
把这个脚本放在你的 gitlab 服务器的 hooks 目录中。 在hooks目录下新建一个目录-pre-receive.d,把脚本文件放在里面。
#!/bin/bash
# Place this script in gitlab server directory -> <path_to_your_gitlab_server_root>/hooks/pre-receive.d
# Create directory,if it does not exists -> mkdir -p <path_to_your_gitlab_server_root>/hooks/pre-receive.d
# Get input data passed along pre-receive hook
read old_sha new_sha refname
# Default separator is ' ',change to ','
IFS=","
# Use env variable GL_USERNAME to get the matching details from users csv file
# This file can be easily generated from the database that you have configured for your gitlab instance.
# It contains records in following format - <username>,<user_email>,<user_name>
IFS=',' read -r -a validuserarray <<< `grep -i "$GL_USERNAME," /tmp/gituser.csv `
valid_user_email=${validuserarray[1]}
valid_user_name=${validuserarray[2]}
# Get the last log user details from git log
IFS=',' read -r -a incoming_committer_array <<< `git log -1 "$new_sha" --pretty=%ce,%cn | tr '[:upper:]' '[:lower:]'`
IFS=',' read -r -a incoming_author_array <<< `git log -1 "$new_sha" --pretty=%ae,%an | tr '[:upper:]' '[:lower:]'`
# If no match found,fail the push
if [[ ${#validuserarray[@]} < 3 ]]; then
echo "GL-HOOK-ERR: You are not authorised to perform this action."
exit 1
fi
# Ensure no conflict markers are there
if git diff "$old_sha" "$new_sha" | grep -qE '^\+(<<<<<<<|>>>>>>>)'; then
echo "GL-HOOK-ERR: Code has conflict markers. Please resolve and retry."
exit 1
fi
# Validate author email ends with domain.com
if ! [[ "${incoming_author_array[0]}" =~ ^[A-Za-z0-9.]+[@]domain\.com$ ]]; then
echo "GL-HOOK-ERR: Author email address ${incoming_author_array[0]} is invalid."
exit 1
fi
# Validate committer email
if [ "${valid_user_email}" != "${incoming_committer_array[0]}" ]; then
echo "GL-HOOK-ERR: Committer email address ${incoming_committer_array[0]} is invalid."
exit 1
fi
# Validate committer name
if [ "${valid_user_name}" != "${incoming_committer_array[1]}" ]; then
echo "GL-HOOK-ERR: Committer name ${incoming_committer_array[1]} is invalid."
exit 1
fi
exit 0
对于每次推送,gitlab 都会提供值 - branch、old_sha、new_sha。将来,如果您有任何其他用例,只需在这些值上放置条件即可。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。