Skip to content

git 禁止大文件提交到仓库中

Published: at 14:01

方式 1 在服务器进行设置

如这里(gitlab 服务搭建小记)提到的

但是,这个只能限制提交到服务器,本地提交代码时无法拦截

方式 2 使用 git hooks

编写 git hooks 脚本

以下脚本来自:Git禁止大文件提交到仓库中 | Yunfeng’s Simple Blog

修改仓库下的 .git/hooks/pre-commit 为如下内容(如果没有这个文件请新建)

#!/bin/sh
hard_limit=$(git config hooks.filesizehardlimit)
soft_limit=$(git config hooks.filesizesoftlimit)
: ${hard_limit:=10000000} # 10M
: ${soft_limit:=1000000} # 1M
list_new_or_modified_files()
{
git diff --staged --name-status|sed -e '/^D/ d; /^D/! s/.\s\+//'
}
unmunge()
{
local result="${1#\"}"
result="${result%\"}"
env echo -e "$result"
}
check_file_size()
{
n=0
while read -r munged_filename
do
f="$(unmunge "$munged_filename")"
h=$(git ls-files -s "$f"|cut -d' ' -f 2)
s=$(git cat-file -s "$h")
if [ "$s" -gt $hard_limit ]
then
env echo -E 1>&2 "ERROR: hard size limit ($hard_limit) exceeded: $munged_filename ($s)"
n=$((n+1))
elif [ "$s" -gt $soft_limit ]
then
env echo -E 1>&2 "WARNING: soft size limit ($soft_limit) exceeded: $munged_filename ($s)"
fi
done
[ $n -eq 0 ]
}
list_new_or_modified_files | check_file_size

通过 git config 命令来设置 soft_limit 和 hard_limit 的值

Terminal window
git config hooks.filesizehardlimit 20000000
git config hooks.filesizesoftlimit 2000000

将脚本放在仓库中管理

在仓库根目录,新增 githooks 目录,将 pre-commit 放在其中,新建一个 install.bat 脚本

Terminal window
@echo off
setlocal enabledelayedexpansion
REM 获取当前运行的 BAT 文件名
set currentBatFile=%~nx0
REM 目标目录
set targetDir=..\.git\hooks
REM 检查目标目录是否存在,不存在则创建
if not exist "%targetDir%" (
echo target path %targetDir% not exist
exit /b 1
)
REM 遍历当前目录的所有文件
for %%f in (*) do (
REM 跳过当前运行的 BAT 文件
if not "%%f"=="%currentBatFile%" (
REM 拷贝文件到目标目录,存在同名文件则覆盖
copy /Y "%%f" "%targetDir%"
)
)
echo git hooks copy finish
:: pause

大致的文件夹结构

\----
\----\githooks
\--------pre-commit
\--------install.bat

运行 install.bat, 会将 githooks 中的全部文件(除了 install.bat 文件本身)拷贝到 .git\hooks 目录中

遗憾的是,需要手动运行 install.bat,可以结合具体项目情况,找个时机自动调用 install.bat

比如前端项目可以使用 husky

参考

Git禁止大文件提交到仓库中 | Yunfeng’s Simple Blog


原文链接: https://blog.jgrass.cc/posts/git-prevent-large-size-file/

本作品采用 「署名 4.0 国际」 许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。