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變量

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章