Last active
February 5, 2023 10:59
-
-
Save kiwidamien/a6a909ee196be8795b30431079074d64 to your computer and use it in GitHub Desktop.
Github pre-commit hook to prevent commits of large files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# This is a pre-commit hook that ensures attempts to commit files that | |
# are larger than 100 MB to your _local_ repo fail, with a helpful error | |
# message. | |
# | |
# This prevents the local repo from getting out of sync with the Github | |
# repo. To install | |
# 1) Change this file to executable: | |
# $ chmod a+x pre-commit | |
# 2) Move into the .git/hooks directory at the top-level of the repo | |
# $ mv pre-commit .git/hooks/ | |
# | |
# See blog post on https://kiwidamien.github.io/prevent-big-commits | |
function file_too_large(){ | |
filename=$0 | |
# This command is more portable, but harder to reason about | |
# filesize=`echo $1 | awk '{ mb =$1 / 1024 / 1024; print mb " MB"}'` | |
filesize=$(( $1 / 10**6 )) | |
cat <<HEREDOC | |
File $filename is $filesize MB, which is larger than github's maximum | |
file size (100 MB). We will not be able to push this file to Github. | |
Commit aborted | |
HEREDOC | |
} | |
empty_tree=$( git hash-object -t tree /dev/null ) | |
limit=100000000 | |
if git rev-parse --verify HEAD > /dev/null 2>&1 | |
then | |
against=HEAD | |
else | |
against=empty_tree | |
fi | |
for file in $( git diff-index --cached --name-only $against ); do | |
file_size=$( ls -la $file | awk '{ print $5 }') | |
if [ "$file_size" -gt "$limit" ]; then | |
file_too_large $filename $file_size | |
exit 1; | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI, another fix picked up by @guysmoilov over here that's prob worth a blog update too.