Screening files on push in a git repo

I recently had the need to make sure that files that were pushed to a git repository had a required string in them. It took a few hours, but here’s what I came up with to do it:

#!/bin/sh
 
refname="$1"
oldrev="$2"
newrev="$3"
 
paths="path/in/repo/"
required="REQUIRED_STRING"
 
hashes=( $(git diff-tree -r $newrev -- $paths | awk '{if ($5 == "A" || $5 == "M") print $4}') )
files=( $(git diff-tree -r $newrev -- $paths | awk '{if ($5 == "A" || $5 == "M") print $6}') )
 
error=0
errors=()
 
for (( c = 0; c < ${#hashes[@]}; c++ ))
do
	check=$(git show ${hashes[$c]} | grep $required | wc -l)
 
	if [ "$check" == "0" ] 
	then
		errors=( "${errors[@]}" ${files[$c]} )
		error=1
	fi
done
 
if [ "$error" == "1" ]
then
	echo
	echo "The following SQL scripts do not have the required string '$required':"
 
	for (( c = 0; c < ${#errors[@]}; c++ ))
	do
		echo "    ${errors[$c]}"
	done
 
	echo 
fi
 
exit $error

Save this as ‘update’ in the ‘hooks’ directory of your bare repo, make it executable, and enjoy. Any files in the paths specified that don’t contain the required text will result in a rejected push.

%d bloggers like this: