简体   繁体   中英

Git push to wrong branch

Working with git, after some 'commit', and a couple of 'push', I realized that am using the wrong branch!

Now I have to remove in some way my changes in wrong_branch and commit and push the changes in right_branch

What's the best (and simple) way to do that?

switch to that branch, check the git log and git revert those commits individually. Once you have done that, switch back to the desired branch and there you can then use git cherry-pick to pick specific commits from the git refs and merge it into the right branch.

git checkout wrong_branch
git revert commitsha1
git revert commitsha2
git checkout right_branch
git cherry-pick commitsha1
git cherry-pick commitsha2

If the commits are grouped together and there are no commits pushed after your dirty commits, you can even use git reset to get that wrong branch to a state just before your commits and then follow that again using git cherry-pick to get your commits into the right branch.

git checkout wrong_branch
git reset commitsha3 #commit just before commitsha2
git checkout right_branch
git cherry-pick commitsha1
git cherry-pick commitsha2

The simplest way is using git rebase . Suppose that you have that setting:

A -- B -- C -- C1 -- C2 # right branch
          \
           \-- D -- C3 -- C4 # wrong branch

You want to move change C3,C4 to the right branch.

git checkout -b new_wrong_branch D
git checkout wrong_branch
git rebase D --onto right_branch
git checkout right_branch
git merge right_branch wrong_branch
git branch -d wrong_branch
git branch rename new_wrong_branch wrong_branch

Now the setting is

A -- B -- C -- C1 -- C2 -- C3 -- C4 # right_branch
          \
           \ -- D # wrong_branch

Then you have to push your results with force (IF nobody has synchronized with your remote repo yet):

git push -f remote:right_branch

A bit of shortcut adding to Dhruva's answer

git checkout wrong_branch
git revert commitsha1

git checkout right_branch
git push right_branch

git checkout wrong_branch
git reset commitsha2 #commit just before commitsha1
git push wrong_branch -f

I find flow this easier if the correct branch hasn't been created yet or doesnt have any new commits and is a direct child of the wrong branch:

  • first delete right-branch if it already exists,
  • git checkout right-branch
  • git push right-branch
  • git checkout wrong-branch
  • git revert commitsha2 (or the commit before wrong commits)
  • git push -f on wrong branch

and you have everything as if u never made any wrong commits in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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