- 进入项目的hooks文件夹(.git/hooks)
- 应该看到已经存在的文件列表。 创建一个要使用的确切提交类型的新文件(例如:“ commit-msg”,“ pre-rebase”,“ pre-commit”等)。不要有扩展名。
- 打开新文件并粘贴代码(如下图所示Python代码)
- 保存存档。 并将pre-commit文件设置为可执行! 现在,git钩子将自动触发。
#!/usr/bin/python
#-*- mode: python -*-
"""Git pre-commit hook: reject large files, save as 'pre-commit' (no .py)
and place in .git/hooks"""
#!/usr/bin/python3
import sys
import os
import re
from subprocess import Popen, PIPE
from io import StringIO
def git_filesize_hook(megabytes_cutoff=5, verbose=False):
"""Git pre-commit hook: Return error if the maximum file size in the HEAD
revision exceeds <megabytes_cutoff>, succes (0) otherwise. You can bypass
this hook by specifying '--no-verify' as an option in 'git commit'."""
if verbose: print (os.getcwd())
cmd = "git diff --name-only --cached"
kwargs = dict(args=cmd, shell=True, stdout=PIPE, cwd=os.getcwd())
if sys.platform.startswith("win"):
del kwargs["cwd"]
cmd = "pushd \"%s\" && " % os.getcwd() + cmd + " && popd"
kwargs["args"] = cmd
git = Popen(**kwargs)
output = git.stdout.readlines()
def try_getsize(f):
"""in case the file is removed with git rm"""
try:
return os.path.getsize(f)
except (EnvironmentError, OSError):
return 0
files = {f.rstrip(): try_getsize(f.strip()) for f in output}
bytes_cut_off = megabytes_cutoff * 2 ** 20
too_big = [f for f, size in files.items() if size > bytes_cut_off]
if too_big:
msg = ("ERROR: your commit contains %s files that exceed size "
"limit of %d Mbytes:\n%s")
msg = msg % (len(too_big), bytes_cut_off/(1024*1024), "\n".join(sorted(too_big)))
msg += "\n\nUse the '--no-verify' option to by-pass this hook"
return msg
return 0
if __name__ == "__main__":
size = 10
sys.exit(git_filesize_hook(size, True))
默认大于10M的文件均不能被commit,如果想修改大小阈值,可以设置size变量