git rebase 修改历史提交信息
·
git rebase 修改提交信息
在仓库迁移中,有需求要修改提交记录的时间,查询资料可以使用git rebase -i来修改历史的提交信息,包括备注和时间都能修改,原链接如下:
原链接(单次交互修改)
由于要修改的记录过多,在上文的操作流程基础上写成linux脚本,方便我们批量修改,脚本如下:
#!/bin/bash
DATE_MAPPING_FILE="date_mapping.txt"
git rev-list HEAD --reverse > "$TMP_FILE"
while read commit_hash; do
# 获取提交的日期和时间
commit_date=$(git show -s --format=%ci "$commit_hash" | awk '{print $1}')
commit_time=$(git show -s --format=%ci "$commit_hash" | awk '{print $2}')
# 执行非交互式 rebase,使用 sed 替换 pick 为 e
git rebase --root --onto "$commit_hash"^ --exec "sed -i 's/pick/e/'"
# 打印 commit_hash 和 commit_date
echo "$commit_hash $commit_date"
# 标记是否找到映射
found_mapping=0
while IFS= read -r line; do
OLD_DATE=$(echo "$line" | awk '{print $1}')
NEW_DATE=$(echo "$line" | awk '{print $2}')
# 检查是否在映射中
if [ "$commit_date" == "$OLD_DATE" ]; then
# # 打印 时间映射
echo "$OLD_DATE $NEW_DATE"
# 标记找到映射
found_mapping=1
new_date="${NEW_DATE}T$commit_time"
# 使用 git rebase 修改对应的 commit_hash 的 提交时间
GIT_COMMITTER_DATE="$new_date" git commit --amend --date="$new_date" --no-edit --allow-empty
echo "更新成功 $commit_hash $commit_date -> $new_date"
# 完成 rebase
git rebase --continue
break
fi
done < "$DATE_MAPPING_FILE"
# 未找到映射
if [ "$found_mapping" == 0 ]; then
# 打印 未找到映射 的 commit_hash 和 commit_date
echo "Not found mapping for $commit_hash $commit_date"
fi
done < "$TMP_FILE"
# 删除临时文件
rm "$TMP_FILE"
执行完成后,本地可以发现已经完成批量修改了,之后直接执行:git push -f 即可
另外,由于rebase需要待修改的版本的前一个版本号,因此无法修改第一个提交记录,如需修改首次提交信息中的时间,可以执行git 命令如下:
git filter-branch --env-filter '
if [ $GIT_COMMIT = $(git rev-list --max-parents=0 HEAD) ]
then
export GIT_AUTHOR_DATE="2023-01-01T00:00:00+0000"
export GIT_COMMITTER_DATE="2023-01-01T00:00:00+0000"
fi
' -- --all
–max-parents=0 选项用于找到根提交(最早的提交),然后通过 --env-filter 选项修改提交的作者和提交者的日期。
请注意,以上脚本操作将修改所有分支和标签中的历史记录,因此请谨慎使用,并确保你对仓库有充分的备份。
更多推荐


所有评论(0)