簡體   English   中英

使用GitHub時,防止將大文本文件添加到提交中

[英]Prevent large text file from being added to commit when using GitHub

我們想要阻止:

  • 非常大的文本文件(每個文件大於50MB)被提交到git而不是git-lfs ,因為它們會擴展git歷史記錄。
  • 問題是,其中99%<1MB,應該致力於更好的差異化。
  • 大小差異的原因:這些是YAML文件,它們通過base64編碼支持二進制序列化。
  • 我們無法可靠地防止二進制序列化的原因:這是一個Unity項目,由於各種原因需要二進制序列化。

鑒於:

  • GitHub托管缺乏預接收掛鈎支持。
  • git-lfs缺少文件大小屬性支持。

問題:

  1. 我們如何可靠地防止大文件被添加到提交?
  2. 這可以通過repo中的配置文件來完成,這樣所有用戶都可以優雅地遵循此規則嗎?
  3. 如果沒有,這可以通過bash命令別名來完成,這樣可信用戶在意外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

現在,假設您正確設置了.gitattributesgit-lfs ,當您嘗試git commit並確保git-lfs(如.gitattributes指定)未跟蹤的所有暫存文件時,此預提交掛鈎將運行滿足指定的文件大小限制。

您的repo的任何新用戶都需要自己設置core.hooksPath ,但除此之外, 事情應該可行

希望這有助於其他Unity開發人員與不斷增長的git repo大小戰斗!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM