[英]Prevent large text file from being added to commit when using GitHub
我們想要阻止:
git
而不是git-lfs
,因為它們會擴展git歷史記錄。 鑒於:
問題:
git add
一個大文件並且它不被git-lfs
處理時會看到一條警告消息嗎? (我們的環境是macOS。我已經看了很多解決方案,到目前為止還沒有滿足我們的需求)
- 我們如何可靠地防止大文件被添加到提交?
- 這可以通過repo中的配置文件來完成,這樣所有用戶都可以優雅地遵循此規則嗎? 由於GitHub不支持服務器端掛鈎,因此您可以使用客戶端掛鈎。 您可能已經知道,這些掛鈎可以通過並且沒有問題被禁用,但是,這仍然是一個很好的方法。
core.hooksPath
Git v2.9添加了在遠程文件夾上設置客戶端掛鈎的功能。 在此之前,鈎子必須放在.git
文件夾中。
這將允許您編寫腳本並將它們放在任何地方。 我假設你知道什么是鈎子,但如果沒有隨意問。
通常,您將鈎子放在repo(或任何其他常見文件夾)中。
# set the hooks path. for git config, the default location is --local
# so this configuration is locally per project
git config core.hooksPath .githooks
好吧,在CodeWizard的幫助和這個SO答案的幫助下,我設法自己創建了一個很好的指南:
首先,使用以下命令設置repo core.hooksPath
:
git config core.hooksPath .githooks
其次,在.githooks
文件夾中創建這個pre-commit
文件,這樣就可以跟蹤它( gist鏈接 ),然后記得用chmod +x
給它執行權限。
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".
# Redirect output to stderr.
exec 1>&2
FILE_SIZE_LIMIT_KB=1024
CURRENT_DIR="$(pwd)"
COLOR='\033[01;33m'
NOCOLOR='\033[0m'
HAS_ERROR=""
COUNTER=0
# generate file extension filter from gitattributes for git-lfs tracked files
filter=$(cat .gitattributes | grep filter=lfs | awk '{printf "-e .%s$ ", $1}')
# before git commit, check non git-lfs tracked files to limit size
files=$(git diff --cached --name-only | sort | uniq | grep -v $filter)
while read -r file; do
if [ "$file" = "" ]; then
continue
fi
file_path=$CURRENT_DIR/$file
file_size=$(ls -l "$file_path" | awk '{print $5}')
file_size_kb=$((file_size / 1024))
if [ "$file_size_kb" -ge "$FILE_SIZE_LIMIT_KB" ]; then
echo "${COLOR}${file}${NOCOLOR} has size ${file_size_kb}KB, over commit limit ${FILE_SIZE_LIMIT_KB}KB."
HAS_ERROR="YES"
((COUNTER++))
fi
done <<< "$files"
# exit with error if any non-lfs tracked files are over file size limit
if [ "$HAS_ERROR" != "" ]; then
echo "$COUNTER files are larger than permitted, please fix them before commit" >&2
exit 1
fi
exit 0
現在,假設您正確設置了.gitattributes
和git-lfs
,當您嘗試git commit
並確保git-lfs(如.gitattributes
指定)未跟蹤的所有暫存文件時,此預提交掛鈎將運行滿足指定的文件大小限制。
您的repo的任何新用戶都需要自己設置core.hooksPath
,但除此之外, 事情應該可行 。
希望這有助於其他Unity開發人員與不斷增長的git repo大小戰斗!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.