Pushed to Wrong GIT Branch

Suppose there are multiple git branches that are in your local repo. You've done tons of work, eventually committed and pushed. Then, you found you were working at a wrong branch! And pushed changes to a wrong branch remotely too! Ooops...

What to do?

First, see which branch you're on:

$ git branch
  master
  duplicate-target
* remove-tab
  api-integration

You're on branch remove-tab, but you actually should have committed and pushed from branch api-integration. You can revert the commit you did and commit to the correct branch by doing following:

  • On the remove-tab branch, do:
$ git log

commit 984d0ccdd9c80941121dfc1e208b25efeb091111
Author: Wendy 

    Add api integration and tests

commit 0909fa4b87ddaa7d08e823f9b02f24c35a9f372a
Author: Eric

    Update server

commit ef78fcb6a1d30955210178772dcc71234c5e4012
Author: Wendy 

    Add new removed tab
  
  • Copy the hash that the latest commit this branch should be at and do:
$ git reset 0909fa4b87ddaa7d08e823f9b02f24c35a9f372a

And you'll see

M app/controllers/book_controller.rb
M app/models/post.rb
M app/models/target.rb
M db/schema.rb
  • At this point, you're reverted local repo to the state right before you did the wrong commit.
    Now you need to stash all the changes and force push to remote.
$ git stash
$ git push --force

After force push, the branch at remote is reverted to previous state. You're good on remove-tab branch.

  • Now onto the branch you should've been on.
$ git checkout api-integration

Pop up stash, commit and push again

$ git stash pop
$ git commit -a
$ git push

You're all set!