git pre-commit 钩子禁止commit大文件

  1. 进入项目的hooks文件夹(.git/hooks)
  2. 应该看到已经存在的文件列表。 创建一个要使用的确切提交类型的新文件(例如:“ commit-msg”,“ pre-rebase”,“ pre-commit”等)。不要有扩展名。
  3. 打开新文件并粘贴代码(如下图所示Python代码)
  4. 保存存档。 并将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变量

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值