使用从 main 之前的提交开始的分支中的更改更新主分支

Update main branch with changes in a branch that start from a commit before main

我推送了一个 main 分支。然后我从 main 的旧提交创建了一个分支 B,现在我希望 mainB 分支相同。

我的情况:

* B branch
|
*
|
*  * C branch
|  |
*  * main
|  |
*  * [commit-x]
| /
*
|

我想要这个:

* main
|
*
|
*  * C branch
|  |
*  * 
|  |
*  * [commit-x]
| /
*
|

我尝试在 main 中合并 B,但这样做我也从 main(例如 commit-x)得到了一些我不想要的提交:

我需要帮助。

非常感谢

我怀疑你是否想这样做,因为通常重写 main 之类的共享分支是不受欢迎的。也就是说,要回答您的问题,这就像将 main 更改为指向 B 一样简单。 (注意 B 可以是分支名称或提交 ID 哈希。)

git switch main
git reset --hard B
git push --force-with-lease

之所以可行,是因为分支只是指向提交 ID 的“书签”或“指针”。 reset 命令用于更改分支指向的提交。

如果您不想重写 main 分支,另一种选择是revert main 上的提交你不想要。所以你可以这样做:

git switch main
git revert commit-X # this is the commit ID you wish to undo.
git merge B

现在 commit-X 仍将保留在历史记录中,但更改将消失。