赞
踩
Git 仓库中有时会不小心加入了一些大文件,例如模型文件,视频文件
模型文件有可能以 .weights 结尾,或者 .onnx 结尾等等
视频文件有可能以 .avi 结尾,或者 .mp4 结尾
大文件如果一直在仓库中,仓库体积会非常大,下面我们提供一个脚本,专门用于清理 仓库中的文件使用。
本脚本旨在从指定的 Git 仓库中移除不必要的 .weights
文件,优化仓库,并将更改推送到远程服务器。它提供了用户交互、详细日志输出及错误处理功能,以实现顺畅且可靠的清理过程。
在使用本脚本之前,请确保满足以下条件:
.weights
文件的 Git 仓库。可选:为了提升性能,建议安装 git-filter-repo 工具(通常通过 pip install git-filter-repo
安装)。如果安装了 git-filter-repo
,脚本将自动使用它替代 git filter-branch
命令进行更高效的历史清理。
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."
赋予执行权限:在终端中,使用 chmod +x clean_repo.sh
命令为脚本赋予执行权限。
执行脚本:
./clean_repo.sh /path/to/repository
,其中 /path/to/repository
是您要清理的仓库路径。./clean_repo.sh
。脚本将引导您完成确认、清理、推送、压缩等步骤,并在过程中输出详细日志。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。