First week - Pre-commit hooks¶
I wanted to study gits hook system, and decided to write a local pre-commit hook that tests the commited file size, as the course requirements state that there should not be any large files in the git repository. I decided to set the file size limit to 3 megabytes, as that seemed big enough for anything that is needed in the course.
I can get the list of commited files with command (according to this link)
git diff --cached --name-only --diff-filter=ACM
Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R), have their type (i.e. regular file, symlink, submodule, …) changed (T), are Unmerged (U), are Unknown (X), or have had their pairing Broken (B).
To check file size in bash: https://stackoverflow.com/questions/5920333/how-can-i-check-the-size-of-a-file-using-bash
file=file.txt
minimumsize=90000
actualsize=$(wc -c <"$file")
if [ $actualsize -ge $minimumsize ]; then
echo size is over $minimumsize bytes
else
echo size is under $minimumsize bytes
fi
Go to .git/hooks/
folder in your repository. Add a pre-commit
file to that directory (with touch pre-commit
). Added the following script to the file to test its functionality:
#!/bin/sh
for file in $(git diff --cached --name-only --diff-filter=ACM);
do
minimumsize=3000000
actualsize=$(wc -c <"$file")
echo $file
if [ $actualsize -ge $minimumsize ]; then
echo size is over $minimumsize bytes
else
echo size is under $minimumsize bytes
fi
done
The file needed to be executable, so I called chmod +x pre-commit
to change its executing permissions.
This was tested with a long list of unnecessary commits to the local repository.
In the end, I updated the file to its final form:
#!/bin/sh
for file in $(git diff --cached --name-only --diff-filter=ACM);
do
maxsize=500000
actualsize=$(wc -c <"$file")
if [ $actualsize -ge $maxsize ]; then
echo $file is over $maxsize bytes
exit 1
fi
done