Skip to content

Instantly share code, notes, and snippets.

@kiwidamien
Last active February 5, 2023 10:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiwidamien/a6a909ee196be8795b30431079074d64 to your computer and use it in GitHub Desktop.
Save kiwidamien/a6a909ee196be8795b30431079074d64 to your computer and use it in GitHub Desktop.
Github pre-commit hook to prevent commits of large files
#!/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
@benmccallum
Copy link

benmccallum commented Nov 28, 2019

I had issues with modified files that had spaces in their name and also my cwd was different so I have it cd to the repo root straight away so the staged file paths make sense. Posted here. Got it working with Husky. Thanks for the share!

@kiwidamien
Copy link
Author

kiwidamien commented Dec 2, 2019 via email

@benmccallum
Copy link

No worries!

@benmccallum
Copy link

FYI, another fix picked up by @guysmoilov over here that's prob worth a blog update too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment