Git reset master to to some other branch's code

434 Views Asked by At

few days back I merged a dev branch to master by mistake & pushed with lot of commits. than for time being I created new branch from an old commit of master (before dev merge) named "master_old" & used this for deployment.

say master has commits 1,2,3,4,5 (3,4,5 are unwanted ones from dev)

master_old has commits 1,2,6,7,8 

I want the master to have 1,2,6,7,8

now I want to switch back to master but I want master to be exact copy of current master_old (without changes from dev merge)

How to kind of reset master to master_old's code?

3

There are 3 best solutions below

0
On

Let's keep it simple :

# start from master
git checkout master

# create a backup
git branch backup_master

# move master's ref
git reset --hard master_old
0
On

First, you need to determine if you want to rewrite the history of the master branch, or add a new commit to make the state of master as it should be. If you have published the master branch (pushed to origin) and it is likely someone may have pulled the master branch, you should not rewrite history.

If it is okay to rewrite history, follow RomainValeri's answer.

To add a new commit, and not rewrite history, do the following:

git checkout master
git reset master_old .
git commit

Explanation: The command 'git reset master_old .' loads the index (staging area) with the state of the commit at master_old. Then when you commit, a new commit is added to master using that index state.

Master now looks like this: 1,2,3,4,5,9, Where commit 9 undoes 3,4,5 and adds the changes from 6,7,8

0
On
  1. You have to reset the head of the master. 3 is there in command to take back the head to 2 commit. You have to be on master while running this command.
  • git reset --soft HEAD~3
  1. Stash the changes to avoid conflicts.
  • git stash
  1. Now rebase with master_old while you are on master.
  • git rebase master_old
  1. You can pop the stashed changes
  • git stash pop
  1. Now your master will be - 1, 2, 6, 7, 8