如何快速移除Git仓库特定目录一年前的历史变更?
清理Git仓库指定目录的历史(按日期筛选)
一、用git filter-repo结合日期回调直接处理
这是最简便的批量处理方式,一次性重写所有分支的历史,自动移除指定目录一年前的记录:
备份仓库:先克隆镜像仓库避免影响原数据
git clone --mirror <你的仓库地址> repo-mirror cd repo-mirror编写日期过滤脚本:创建
filter-dated-dir.py文件,替换目标目录和 cutoff 日期(用UTC时间)import datetime from gitfilterrepo import util # 设定一年前的UTC日期,比如2023-05-20 CUTOFF_DATE = datetime.datetime(2023, 5, 20, tzinfo=datetime.timezone.utc) # 替换为你要清理的二进制文件目录 TARGET_DIR = "assets/large-binaries/" def filter_callback(commit): commit_date = datetime.datetime.fromtimestamp(commit.committed_date, tz=datetime.timezone.utc) if commit_date < CUTOFF_DATE: # 删除该提交中目标目录下的所有文件 for path in list(commit.tree.keys()): if path.startswith(TARGET_DIR): del commit.tree[path] if __name__ == "__main__": util.run_filter(filter_callback)执行过滤:
git filter-repo --commit-callback filter-dated-dir.py推送结果:如果需要同步到远程,执行强制推送(仅个人仓库使用,避免影响协作者)
git push --force
二、命令行直接过滤(无需脚本)
如果不想写脚本,可直接通过命令行指定日期和目录:
- 先获取一年前第一个提交的哈希:
CUTOFF_COMMIT=$(git log --reverse --since="1 year ago" --format="%H" | head -1) - 执行filter-repo命令,移除该提交之前所有记录中的目标目录:
git filter-repo --commit-callback ' import gitfilterrepo.util cutoff_date = gitfilterrepo.util.get_commit("'"$CUTOFF_COMMIT"'").committed_date if commit.committed_date < cutoff_date: [del commit.tree[path] for path in list(commit.tree.keys()) if path.startswith("assets/large-binaries/")] '
三、Cherry-pick方案优化
如果你偏好手动可控的方式,可优化你提到的流程:
- 克隆新仓库并进入:
git clone <你的仓库地址> cleaned-repo cd cleaned-repo - 获取一年前main分支的首个提交哈希:
CUTOFF_COMMIT=$(git log main --reverse --since="1 year ago" --format="%H" | head -1) - 基于该提交创建临时分支并清理目录:
git checkout -b temp-clean $CUTOFF_COMMIT git rm -r assets/large-binaries/ git commit --amend --no-edit - 重写main分支历史:
git checkout main git rebase temp-clean - 批量处理其他入职后创建的分支:
for branch in $(git branch --list 'feature-*' 'bugfix-*'); do # 替换为你的分支匹配规则 git checkout $branch git rebase temp-clean done - 删除临时分支:
git branch -D temp-clean
注意事项
- 重写历史后,所有分支的提交哈希都会改变,需强制推送至远程,确保仅在个人仓库或无协作者的场景下操作。
- 操作前务必备份原仓库,避免数据丢失。
- 若需同步公司版本控制系统,需确认对方支持重写后的历史结构。
内容的提问来源于stack exchange,提问作者TooTone
相关产品推荐
相关产品推荐

