如何重写提交历史?

How to rewrite commit history?

从工作分支 X 创建分支 Y 后,在分支 Y 上工作时,我删除了一些文件以减少视觉噪音,因为在 FS 上看不到这些文件。正在分支 X.

中更改这些文件

场景如下:

A - B [origin/master]
     \
      C - D - G - H [origin/X]
           \
            E - F [Y]

来自分支 Y 的更改也被推送到 origin/Y

已在分支 Y 上提出 PR 请求以供审核。


如何重写 origin/Y 中的提交历史以取回文件?

正如@eftshift0 在评论中提到的那样,您可能会发现这个 answer 很有用。 它表明您可以恢复丢失的文件并使用以下内容重写 git 历史记录:

git rebase -i <id of the commit with the files before they were deleted>
git checkout <id of the commit previous to the one you're currently on> <filename>
git commit --amend
git rebase --continue
git tag -d originalHead

尽管如此,保持 git 历史记录不变是有价值的,因此可以在 answer 中找到另一个恢复丢失文件而不更改 git 历史记录的选项,它说这个:

git checkout <id of the commit with the files before they were deleted> <filename>

此外,如果您想恢复多个文件,此 展示了一些方法,例如 运行 多次执行 git checkout 命令。

我会给你一个简单的食谱作为备用,以防万一。假设你的分支叫 A,你删除了 A~3 上的文件(也就是 A 之后的 3 个修订版):

git checkout A~3 # we set ourselves on the revision where the files where deleted
git checkout HEAD~1 -- file1 file2 file3 # get back the files from the previous revision
git commit --amend --no-edit # commit new revision with the deleted files back in place
git cherry-pick A~3..A # replay revisions after this new revision
# if you like the results:
git branch -f A # set the branch on this new position
git checkout A
git push -f origin A

应该可行