Home > front end >  How to merge two branches, while deleting one from a graph and history in Git?
How to merge two branches, while deleting one from a graph and history in Git?

Time:08-12

I have following situation on my local and remote Git repo:

enter image description here

But I realized that this orange branch is redundant and I want to remove that branch and its two commits "Add Servers" and "Add comments for developers", but wish to preserve all green branch's commits and connect it right to the grey branch's "Add server" commit, so my graph would look like that:

enter image description here

When I do git merge it doesn't change graph as expected, but at the same time I cannot delete this "Servers" branch since "Java-Servers" branch is forked from it. Which Git command/s should I use to perform this?

CodePudding user response:

Merge Servers and Java-Server branches, since Java-Server is the one to be left, so:

 git checkout Java-Server

 git merge Servers

It could also display you

Already up-to date.

Since you are sure that none of the "Servers" branch's commits affects your "Java-Server" branch then go to git interactive rebase:

git rebase -i HEAD~N

Where N is the number of commits you made to Servers and Java-Servers branch in total. In your case N is 5. There would be a list of commits like:

pick ... Add Servers
pick ... Add comments for developers
pick ... create new branch
pick ... Add HTTPS
pick ... Fix bugs

Change it to:

d ... Add Servers
d ... Add comments for developers
pick ... create new branch
pick ... Add HTTPS
pick ... Fix bugs

This will delete these commits. After you done you will get:

Successfully rebased and updated ...

Then you can delete your local "Servers" branch:

git branch -D Servers

As well as you remote "Servers" branch - go to GitHub, GitLab, BitBucket or wherever your Git project is and delete "Servers" branch from there.

Then you will get exactly the same graph as you've asked for with the exact commits history.

  • Related