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

方式 1 在服务器进行设置#

如这里(gitlab 服务搭建小记 - J.晒太阳的猫 - 博客园)提到的

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

方式 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 的值

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

将脚本放在仓库中管理#

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

@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

作者:JasonGrass

出处:https://www.cnblogs.com/jasongrass/p/18326879

版权:本作品采用「署名 4.0 国际」许可协议进行许可。

posted @   J.晒太阳的猫  阅读(69)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示