Last active
January 31, 2023 03:43
-
-
Save kiwidamien/597ebbaeaf2388932ac9a3aaff7d1287 to your computer and use it in GitHub Desktop.
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
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you ever tested this after deleting a file from a repo? It seems as if
filenames
may include the deleted file's name, causingFileNotFoundError
inos.stat(filename).st_size
.