Skip to content

Instantly share code, notes, and snippets.

@eik-dahms
Last active June 4, 2024 08:10
Show Gist options
  • Save eik-dahms/46e626fe8747f14a31d9db128dd79b42 to your computer and use it in GitHub Desktop.
Save eik-dahms/46e626fe8747f14a31d9db128dd79b42 to your computer and use it in GitHub Desktop.
pre receive hook for gitlab to limit file size on upload via the web interface and web IDE
#!/bin/bash
# pre-receive server hook to check file size of files submitted by webinterface in gitlab
#
# sources:
# https://gist.github.com/nauar/826f85d25d692d9bc009312cb71577dd
LOG_FILE="/var/log/datahub/size-check-hook.log"
GITCMD="git"
NULLSHA="0000000000000000000000000000000000000000"
EMPTYTREESHA=$($GITCMD hash-object -t tree /dev/null)
MAXSIZE="1" # set your maximum file size in MB here
MAXBYTES=$(( $MAXSIZE * 1048576 ))
function log() {
moment=`date '+%d/%m/%Y %H:%M:%S'`
echo -e "[ $moment ] [ SIZE CHECK ] $1" >> $LOG_FILE
}
# do checks only if files are added via web interface, upload single file and WEB IDE
if [ "$GL_PROTOCOL" = "web" ]; then
log "Starting validation: $GL_ID\t$GL_PROJECT_PATH\t$GL_PROTOCOL\t$GL_REPOSITORY\t$GL_USERNAME"
while read oldref newref refname; do
log "OLDREF: $oldref NEWREF: $newref REFNAME: $refname"
# Avoid removed branches
if [ "${newref}" = "${NULLSHA}" ]; then
continue
fi
# Set oldref properly if this is branch creation.
if [ "${oldref}" = "${NULLSHA}" ]; then
oldref=$EMPTYTREESHA
fi
# Ignore case
shopt -s nocaseglob
newFiles=$($GITCMD diff --stat --name-only --diff-filter=ACMRT ${oldref}..${newref})
if [[ $? -ne 0 ]]; then
log "Error 101: Repository incosistency. Cancelling push..."
echo "GL-HOOK-ERR: Repository incosistency. Cancelling push...";
exit 1;
fi
old_IFS=$IFS
IFS='
'
for filename in $newFiles; do
# get file size info
log "Filename: $filename"
filesize=$($GITCMD cat-file -s "${newref}:${filename}") 2>> $LOG_FILE
if [[ -z $filesize ]]; then filesize=0; fi
filesize_mb=$(($filesize / 1048576))
# check file size, exit if too big
if [ "${filesize}" -gt "${MAXBYTES}" ]; then
log "File $filename is greater than $MAXSIZE MB. Its size is $filesize_mb MB."
echo "GL-HOOK-ERR: At least one of your submitted files ($filename) has been to big ($filesize_mb MB). Max filesize is $MAXSIZE MB. Please use git-lsf to submit bigger files to your ARC.";
exit 1
fi
done
IFS=$old_IFS
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment