简体   繁体   English

Git-将另一个分支的最后提交移到主分支的顶部

[英]Git - move the last commit of another branch on top of the main branch

All the related questions ask about moving commits from the main branch to another branch. 所有相关问题都询问有关将提交从主分支移动到另一个分支的问题。

My problem is somehow opposite: 我的问题正好相反:

M(n)-M(n+1)-M(n+2)-M(n+3)
\
B(1)-B(2)-B(3)-B(4)-B(5)

Consider that M stands for a commit on master and B for a commit on a secondary branch. 考虑到M代表对master的提交, B代表对次要分支的提交。 The contents of the parantheses are indexes. 括号的内容是索引。

I want to merge the branches and move B(5) on top of the main branch, so right after M(n+3) , disregarding any change made from M(n) to M(n+3) . 我想合并分支并将B(5)移动到主分支的顶部,因此紧随M(n+3) ,而不管从M(n)M(n+3)任何更改。

I'm avoiding to use git rebase , as the structure of my repo is the same as that of a shared repo, and I don't know what will happen if I would rewrite the history with git rebase in this context. 我避免使用git rebase ,因为我的存储库的结构与共享存储库的结构相同,而且我不知道如果在这种情况下用git rebase重写历史记录会发生什么。

Try this sequence of git commands: 尝试以下git命令序列:

 git checkout M
 git reset --hard HEAD~3
 git merge B

If your commits are pushed to a remote repository, you can't just move things around. 如果将提交内容推送到远程存储库,则不能随便移动内容。 If the commits on branch M are only local then you can rollback to M(n) and merge branch B to it which will get you what you want. 如果分支M上的提交仅是本地的,则可以回滚到M(n)并将分支B合并到该分支,这将为您提供所需的东西。

However, if the commits have been pushed you should avoid this because you have rewritten history and will have to do a git push -f . 但是,如果提交已被推送,则应避免这种情况,因为您已经重写了历史记录,并且必须执行git push -f If anyone else has pulled the changes then it will cause a lot of problems. 如果其他人取消了更改,则将导致很多问题。 In this case you will need to revert the changes from M(n+1) to M(n+3). 在这种情况下,您需要将更改从M(n + 1)还原为M(n + 3)。

Using this answer: https://stackoverflow.com/a/1470452/498699 使用此答案: https : //stackoverflow.com/a/1470452/498699

git revert --no-commit M(n+3)
git revert --no-commit M(n+2)
git revert --no-commit M(n+1)
git commit

Now you can merge branch B and have the changes applied correctly and anyone else that has pulled the changes will not have any difficulties pulling your changes. 现在,您可以合并分支B并正确应用更改,并且其他任何撤消更改的人都不会遇到任何困难。

If you just want to have B(5) (and none of B(1) to B(4)) right after M(n+3) then you can just run 如果您只想在M(n + 3)之后紧接B(5)(而B(1)至B(4)都没有),则可以运行

git checkout master
git cherry-pick B(5)

If you want all of B(1) to B(5) after M(n+3) but do not want to change the history of B, no worry, just create a new C branch. 如果您希望B(1)至B(5)都在M(n + 3)之后,但又不想更改B的历史记录,请放心,只需创建一个新的C分支即可。

git checkout -b C_branch B_branch
git rebase --onto master `git merge-base C_branch master` C_branch

That will give 那会给

M(n)-M(n+1)-M(n+2)-M(n+3)
\                        \
B(1)-B(2)-B(3)-B(4)-B(5)  C(1)-C(2)-C(3)-C(4)-C(5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM