Home > Software design >  Update main branch with changes in a branch that start from a commit before main
Update main branch with changes in a branch that start from a commit before main

Time:05-11

I have a main branch pushed. Then I created a branch B from an old commit of main and now I want main to be the same as the B branch.

My situation:

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

And I would like to have this:

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

I tried merging B in main but doing so I get also some commits from main (example commit-x) that I don't want:

I need help.

Thank you very much

CodePudding user response:

I question whether you want to do this, since generally rewriting shared branches such as main is frowned upon. That being said, to answer your question, this is as simple as changing main to point to B. (Note B could be a branch name or a commit ID hash.)

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

This works because branches are just "bookmarks" or "pointers" to a commit ID. The reset command is used to change what commit a branch points to.

If you don't wish to rewrite the main branch, another option would be to revert the commits on main that you don't want. So you could do this instead:

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

Now commit-X will still be in the history but the changes will be gone.

  •  Tags:  
  • git
  • Related