From charlesreid1

Scenario:

  • You have a fork of a remote repositoroy
  • You've prepared a commit, but you accidentally pushed the commit to the master branch instead of creating a branch for all your fixes
  • You need to keep the master branch clean

Here's what this solution does:

  • ASSUMPTION: You have your commit/changes backed up somewhere
  • Replace the master branch of your fork (the remote branch that you own) with the master branch of the upstream (the master branch of the remote repo that you forked)

This shares some similarities with Git/Delete Remote Branch.

The procedure

Here's what the procedure will look like:

Check out a non-master branch (this might be the new branch that you are going to do your work on, or it might be a dummy branch you'll delete when this is all over):

$ git checkout -b not-the-master

Delete the master branch (MAKE SURE YOU BACK UP YOUR COMMITS TO MASTER!!!):

$ git branch -d master

At this point, if you try to push this (deleted) master to the remote, it will fail:

$ git push origin --delete master
To https://github.com/ours/repo.git
 ! [remote rejected] master (refusing to delete the current branch: refs/heads/master)
error: failed to push some refs to 'https://github.com/ours/repo.git'

So instead, what we'll do is we'll make a new master branch directly from the upstream master (again, that's the master branch of the original repo that we forked):

$ git checkout -b master remotes/open/master
Branch master set up to track remote branch master from open.
Switched to a new branch 'master'

Now we have a fresh copy of master that looks just like the master branch of the upstream repo that we forked. You're almost there!

The last step is to push this new master to the master branch of your repository. You'll have to piss off all the git purists by using the --force flag, and pushing the local master branch to the remote master branch:

$ git push --force origin master:master
Total 0 (delta 0), reused 0 (delta 0)
To https://github.com/ours/repo.git
 + e526633...dc3cfea master -> master (forced update)

As a side note, the force flag says "Ignore any errors due to the current master branch in the remote repository being ahead of the local master branch that we're trying to push." If you don't include the force flag, here's what will happen:

$ git push origin master:master
To https://github.com/ours/repo.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/ours/repo.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</pr>