如何用另一个分支替换一个分支的历史记录?

How to replace the history of a branch with another branch?

我有从 Perforce 迁移到 Git 的存储库。每隔一段时间,我都会在每个存储库上执行 git p4 rebase(其中 p4 是 git-p4 的别名),以便将新的更改从 Perfoce 获取到 Git。此过程适用于所有存储库,除了这个注定要失败的存储库,将其称为 GitRepo.

出于某种原因,每次我 "sync" Git 使用 Perforce 进行回购时,我都会得到一个空的合并提交,如下所示:

碰巧最近两个月没有变化。所以历史现在看起来像这样:

注意到 2018 年 4 月 6 日和 2018 年 3 月 30 日的提交了吗?不确定为什么它们在 6/25/2018 之后(这可能是问题的根源),并且它们确实已经存在于 time-epic 的历史记录中。

长话短说,我已经检查了 6/25/2018 提交并将历史推送到新分支,Branch-A。

Branch-A 看起来正是我想要的,我怎样才能改写 master 的历史,成为 Branch-A 中的那个?

如果您确实(正如您的评论所指出的那样)单独处理此 repo,您​​可以利用 branch 命令的 -f 选项提供的可能性,并任意设置您的任何给定提交上的 master 分支(或者,如文档中所述,committish,这意味着可用于指向给定提交的任何引用,如分支、标签和还有几个):

# First you can, as a backup, set a branch where master is at the start of the process
git branch backup-master master

# Okay, now we force (-f) the master branch on the same commit where BranchA is
git branch -f master BranchA

# Local is clear, now is time to update your remote with
# your rewritten version of repo history
git push -f origin master

现在 master 与 BranchA 处于同一点,直到他们的历史,因为这是他们都指向的相同提交。分支 backupMaster 在这里,以防您因任何原因改变主意。