【代码管理】Git删除仓库中的大文件压缩仓库大小

发布于:2024-04-26 ⋅ 阅读:(26) ⋅ 点赞:(0)

Git 仓库中有时会不小心加入了一些大文件,例如模型文件,视频文件
模型文件有可能以 .weights 结尾,或者 .onnx 结尾等等
视频文件有可能以 .avi 结尾,或者 .mp4 结尾
大文件如果一直在仓库中,仓库体积会非常大,下面我们提供一个脚本,专门用于清理 仓库中的文件使用。

仓库清理脚本

本脚本旨在从指定的 Git 仓库中移除不必要的 .weights 文件,优化仓库,并将更改推送到远程服务器。它提供了用户交互、详细日志输出及错误处理功能,以实现顺畅且可靠的清理过程。

使用前准备

在使用本脚本之前,请确保满足以下条件:

  • 您拥有一个包含待移除 .weights 文件的 Git 仓库。
  • 已在系统上安装 Git

可选:为了提升性能,建议安装 git-filter-repo 工具(通常通过 pip install git-filter-repo 安装)。如果安装了 git-filter-repo,脚本将自动使用它替代 git filter-branch 命令进行更高效的历史清理。

使用方法

  1. 下载或复制脚本:将以下脚本保存为 clean_repo.sh 文件。

#!/bin/bash
# 清理指定仓库中无用的.weights文件
# 通过命令行参数接收仓库地址(文件夹路径)

# 获取仓库路径(优先使用命令行参数,否则使用当前目录)
if [ -n "$1" ]; then
    repository_path="$1"
else
    repository_path="."
fi

# 检查路径是否存在且为Git仓库
if [ ! -d "$repository_path" ] || ! (cd "$repository_path" && git rev-parse --is-inside-work-tree &>/dev/null); then
    echo "Error: The specified path '$repository_path' is not a valid Git repository."
    exit 1
fi

# 用户确认是否继续
read -p "Are you sure you want to proceed with cleaning the repository at '$repository_path'? [y/N] " confirm
confirm=${confirm,,}  # Convert to lowercase
if [[ $confirm != "y" ]]; then
    echo "Aborting the operation."
    exit 0
fi

cd "$repository_path" || exit 1  # 切换到指定仓库目录,若失败则退出脚本

# 清理垃圾文件并记录结果
echo "Cleaning up unnecessary .weights files..."
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch *.weights' --prune-empty --tag-name-filter cat -- --all || {
    echo "Error: Failed to clean up .weights files. Check the output above for details."
    exit 1
}

# 记录清理前后的仓库大小
before_size=$(du -sh .git | cut -f1)
echo "Repository size before cleanup: $before_size"

# 提交到远程仓库
echo "Pushing changes to remote repository (this may take some time)..."
git push origin --force --all || {
    echo "Error: Failed to push changes to the remote repository. Check your network connection and authentication settings."
    exit 1
}

# 回收垃圾并压缩本地仓库
echo "Performing garbage collection and compression..."
git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
git reflog expire --expire=now --all
git gc --prune=now

# 可选:进行更深度的压缩(视情况决定是否需要)
git gc --aggressive --prune=now

# 记录清理后的仓库大小
after_size=$(du -sh .git | cut -f1)
echo "Repository size after cleanup: $after_size"

echo "Cleanup completed successfully."

  1. 赋予执行权限:在终端中,使用 chmod +x clean_repo.sh 命令为脚本赋予执行权限。

  2. 执行脚本

    • 指定仓库路径:运行 ./clean_repo.sh /path/to/repository,其中 /path/to/repository 是您要清理的仓库路径。
    • 使用当前目录:如果您想清理当前目录下的仓库,只需运行 ./clean_repo.sh

    脚本将引导您完成确认、清理、推送、压缩等步骤,并在过程中输出详细日志。

注意事项

  • 谨慎操作:清理操作会修改仓库历史,可能导致分支合并复杂性增加。请确保所有团队成员知晓此次清理,并在执行前备份重要数据。
  • 权限要求:执行清理和推送操作需具有相应的 Git 权限。确保您有权修改所清理仓库的历史记录及向远程服务器推送更改。
  • 性能影响:对于大型仓库,清理和压缩过程可能耗时较长。请耐心等待,并确保网络连接稳定。
  • 清理效果:清理后,仓库在本地和远程的大小可能不会立即更新。请等待一段时间后刷新查看,或联系服务提供商确认是否需要手动触发更新。