Skip to content

Instantly share code, notes, and snippets.

@fengxsong
Last active July 12, 2017 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fengxsong/593108447e19ae7e0317a90ff94d3004 to your computer and use it in GitHub Desktop.
Save fengxsong/593108447e19ae7e0317a90ff94d3004 to your computer and use it in GitHub Desktop.
a git pre-recieve hook sample protect .gitlab-ci.yml, comes from https://github.com/github/platform-samples/blob/master/pre-receive-hooks/block_file_extensions.sh
#!/bin/env bash
zero_commit="0000000000000000000000000000000000000000"
permit_user="gitlab-ci"
commit_msg_format="ci/`date +%Y%m%d`/*"
excludeExisting="--not --all"
# if .gitlab-ci.yml file exists then check the commit message and the author name of the last commit, if not match then reject commit.
check_pass=false
exists=false
times=0
while read oldrev newrev refname; do
#echo $refname $oldrev $newrev
if [ "$newrev" = "$zero_commit" ]; then
continue
fi
if [ "$oldrev" = "$zero_commit" ]; then
span=`git rev-list $newrev $excludeExisting`
else
span=`git rev-list $oldrev..$newrev $excludeExisting`
fi
for COMMIT in $span;
do
for FILE in `git log -1 --name-only --pretty=format:'' $COMMIT`;
do
case $FILE in
.gitlab-ci.yml )
exists=true
times=`expr $times + 1`
username=`git log -1 --format=format:%an $COMMIT`
msg=`git log -1 --format=format:%B $COMMIT`
if [ "$username" == "$permit_user" ] && echo "$msg" | grep -oP "$commit_msg_format" >/dev/null; then
check_pass=true
else
check_pass=false
fi
;;
esac
done
$check_pass && break
done
done
if $exists; then
if $check_pass && [[ $times -eq 1 ]]; then
exit 0
else
echo "Hello there! We have restricted committing gitlab-ci.yml. Please contact admins."
exit 1
fi
else
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment