如何在 git 中将推送的常规合并转换为挤压合并?

How to convert pushed regular merge into squash-merge in git?

我不小心将使用 regular commit 的 20 次提交从 feature branch 合并到了 main 分支。有什么方法可以将其恢复为 squash and merge 吗?目的是使 main 分支干净。我在 feature branch.

中的 20 次提交应该只有一次提交

首先,免责声明。 Git 中的标准经验法则是:

Don't force push shared branches, because it can mess up other people.

当然,如果您愿意处理后果,则经验法则可以有例外,在您的情况下,听起来您是:

Everyone in the group notice that, so we would like to figure out this first.

所以这个问题的修复相当简单:

# tell everyone you are going to rewrite the main branch
git checkout main
git pull main
# look at main and make sure other people didn't add more commits after yours
git reset --hard <last-good-commit-id-before-your-feature-branch>
git merge feature-branch --squash
# at this point a single squashed commit is staged and ready to be committed
git commit -m "Merge and squash feature branch"
# now replace the remote main branch with your copy
git push --force-with-lease
# now tell everyone it is fixed and they can resume work

注意:您问的是“还原”,但在 Git 中,术语“还原”是指创建一个新的提交来撤消先前的现有提交。这将使历史保持不变并改变功能。你实际上想要相反的东西,因为你想保持功能完好无损并改变历史。要更改历史记录,您需要“重写”提交,在本例中包括向后重置以删除提交,并重新创建新提交。

旁注:您可能需要考虑在 main 上设置分支策略并使用合并请求合并到 main。然后(让我们希望)审查您的代码的人会在您的 PR 中看到很多提交,并且可以告诉您先压缩它们。或者,您可以设置一个 squash 合并策略,以便在 PR 完成时自动发生。