如何基于Excel哈希ID批量自动改写Git特定项目提交信息
批量修改Git提交信息(无需VIM交互)
1. 准备映射数据
把Excel里的提交哈希和对应新提交信息,导出成纯文本文件(比如命名为commit_updates.txt),每行格式严格为:
<完整40位提交哈希> <新的提交信息>
备注:用完整哈希避免匹配冲突,提交信息里的空格可直接保留
2. 用git filter-repo批量修改(推荐)
git filter-repo是Git官方推荐的批量历史修改工具(替代已弃用的git filter-branch),效率更高且更安全。
步骤:
- 创建Python脚本
update_messages.py,内容如下:
import sys # 加载哈希-新信息的映射关系 update_map = {} with open('commit_updates.txt', 'r') as f: for line in f: line = line.strip() if not line: continue split_line = line.split(' ', 1) if len(split_line) != 2: continue commit_hash, new_msg = split_line update_map[commit_hash.lower()] = new_msg # 遍历并修改提交 for line in sys.stdin: line = line.rstrip('\n') if line.startswith('commit '): current_hash = line.split(' ')[1].lower() if current_hash in update_map: # 输出提交头,替换信息 print(f'commit {current_hash}') print(sys.stdin.readline().rstrip('\n')) # author行 print(sys.stdin.readline().rstrip('\n')) # committer行 print() print(update_map[current_hash]) # 跳过原提交信息内容 while True: next_line = sys.stdin.readline() if not next_line or next_line.strip() == '': break print() else: # 无匹配则原样输出 print(line) while True: next_line = sys.stdin.readline() if not next_line: break print(next_line.rstrip('\n')) else: print(line)
- 在Git仓库根目录执行命令:
git filter-repo --commit-callback "$(python update_messages.py)"
3. 替代方案:针对指定提交范围修改
如果只需要修改某一段范围的提交(比如最近10个),可以用git rebase + 脚本实现:
- 创建bash脚本
update_commit.sh,赋予执行权限(chmod +x update_commit.sh):
#!/bin/bash current_hash=$(git rev-parse HEAD) # 从映射文件查找对应新信息 new_msg=$(grep "^$current_hash" commit_updates.txt | cut -d' ' -f2-) if [ -n "$new_msg" ]; then git commit --amend --no-edit -m "$new_msg" fi
- 执行rebase命令(以修改最近10个提交为例,可替换为具体哈希范围):
git rebase -i --exec './update_commit.sh' HEAD~10
执行时,将rebase交互界面里的所有pick保留即可,脚本会自动匹配哈希并修改对应提交信息,无需手动打开VIM编辑
关键注意事项
- 执行前必须备份仓库:批量修改提交历史会改变仓库哈希链,推送远程仓库时需要用
git push --force(仅限私有仓库或团队提前协商一致的场景) - 使用
git filter-repo需确保Git版本≥2.22,且仓库无未提交修改 - Excel导出时要清除多余格式(如单元格边框、合并单元格),保证哈希和信息对应准确
内容的提问来源于stack exchange,提问作者Nav_211
相关产品推荐
相关产品推荐

