To reset / return the whole branch to the state of another branch?

I have branch A and branch B (and some other branches).

Suppose the commit history looks like this:

  • commit 5
  • commit 4
  • commit 3
  • ...

And the history of commit B:

  • some other fixations
  • commit 4
  • merging another material from branch C (to branch B)
  • commit 3
  • ...

Basically, I want to β€œdelete” all the changes made by commits, some other commits, and merging other things from branch C to branch B.

I want the working tree of branch B to be exactly the same as the branch. Working tree.

How do I achieve this?

+14
git merge reset revert
source share
3 answers

One way to achieve this is through git reset . On branch B , do

 git reset --hard A 

After that, branch B points to head commit A The --hard option resets the index and the working tree, so all monitored files are reset to version A in the branches. The old HEAD A commit id is stored in .git/ORIG_HEAD so that the change can be undone.

Alternatively - until you are on branch B - you can delete branch B and recreate it as follows:

 git branch -d B # delete branch B git branch BA # re-create branch B and let it point to the commit of branch A 

In addition to the first sentence, the index and the working tree will remain untouched.

+19
source share

If you want your branch B look exactly like branch A You can simply do a reset --hard

 git checkout branch-B git reset --hard branch-A 

Be careful, you will lose fixation in this case. Your branch-B will look exactly like branch-A, any commits that were made for branch-B that were not in branch-A will be lost . In addition, if branch-B is shared with other people, it is not recommended to perform this operation.

In this case, you can try to return those commits that are not needed in branch-B

 git revert <sha-of-"some other commit"> git revert <sha-of-"merge of other stuff from branch C (into branch B)"> 

The second commit looks like a merge commit, so you might have to pass in the parent as well.

  git revert <sha-of-"merge of other stuff from branch C (into branch B)"> -m1 
+9
source share

To complete, let's add this very simple way to achieve this:

 git branch -f branchB branchA 

It uses the fact that branches in git are just pointers. This command simply replaces the commit link from one branch to another. No need to go into complex structural changes to create what you already have.

+3
source share

All Articles