Skip to content

Instantly share code, notes, and snippets.

@kiwidamien
Last active January 31, 2023 03:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiwidamien/597ebbaeaf2388932ac9a3aaff7d1287 to your computer and use it in GitHub Desktop.
Save kiwidamien/597ebbaeaf2388932ac9a3aaff7d1287 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# 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 is the python version.
#
# This prevents the local repo from getting out of sync with the Github
# repo. To install
# 1) Install gitpython
# $ pip install gitpython
# 2) Change this file to executable:
# $ chmod a+x pre-commit
# 3) 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
from git import Repo
from gitdb.exc import BadName
import os
import sys
repo = Repo('.')
limit = 10**8
try:
filenames = (diff_obj.a_path for diff_obj in repo.index.diff('HEAD'))
except BadName:
# new repo, no 'HEAD' or master until first commit completed
filenames = (filename for filename, _ in repo.index.entries.keys())
for filename in filenames:
filesize = os.stat(filename).st_size
if filesize > limit:
print(f"""
{filename} ({filesize // 10**6} MB) is larger than the {limit // 10**6} MB limit
Commit aborted""")
sys.exit(1)
@eric-kernfeld-dzd
Copy link

Have you ever tested this after deleting a file from a repo? It seems as if filenames may include the deleted file's name, causing FileNotFoundError in os.stat(filename).st_size.

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