如何重写提交历史记录?

时间:2019-07-21 03:32:44

标签: git git-branch

从工作分支Y创建分支X后,我删除了一些文件,以减少视觉噪音,因为在分支Y上工作时,FS周围看不到这些文件。这些文件将在分支X中进行更改。

这是场景:

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

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

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


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

2 个答案:

答案 0 :(得分:1)

正如评论中提到的@ 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>

此外,如果要恢复多个文件,此answer显示了一些方法,例如可以多次运行git checkout命令。

答案 1 :(得分:1)

为了以防万一,我将给您提供一个简单的方法作为备用。假设您的分支名为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

应该可以