Accidentally commited on master branch before switching to local branch and pushing incomplete- how to revert and merge

Viewed 530

So I've been a bit of a moron here. I was working on the master branch, made a bunch of commits, realised I was on the master branch, checked out to another branch assuming that the commits would be brought over, committed once in the branch and then pushed. Upon checking the github repo I see that only the last commit was pushed.

Sooo how do I undo this, merge all the commits on to the local branch, and re-push it?

My commit history:

commit 9dc4373ea546dd90e27d3c0a75b39c2656799638 (HEAD -> feature/implement-checkout, origin/feature/implement-checkout, master)
    Implement checkout service

commit 0cf3ec312c94d0b6a9d94f37b439ff4bea70199f
    Add seeds

commit b6bcabcf15eacad8c94e96e4e325f5b2695a8ade
    Add bills and bill discounts

commit a7cf1c5261b1fbbd2cadc0bf8899ab5729ea5ed7
    Add bill item model

commit 52a812a5f495f9950efee887bfe7678355c56f18
    Create bill model

commit 7b17847d45c1d04ed86928599ed7e16770f19fcc
    Add item model

commit 188e82a1b36fe8439457c3a8f85609fb4f2c9f40
    Add Rspec

commit 9b4c9393d19339a5264ce1d51db935f73a9a84ea
    Initialize app
1 Answers

The safe way to proceed here would be to just revert the single commit to your other branch, and then rebuild it the way you want.

# from other_branch
git revert HEAD
git cherry-pick master~6^..master
git cherry-pick HEAD~8

At this point, your other_branch should look like this:

other_branch: ... A -- A_R -- M1 -- M2 -- M3 -- M4 -- M5 -- M6 -- M7 -- A'

Here A is the initial single commit you made to this branch, and A_R is the revert commit. At this point, before we have cherry picked M1 from master, your branch is as if you never even made that commit. Next, we cherry pick the 7 most recent commits to master as M1 through M7. Finally, we reapply your single commit in A'.

Now you may do a regular push of this branch to GitHub:

git push origin other_branch

Finally, for cleanup we need to remove the commits you made to master. Assuming you have not yet pushed master, we can simply do a hard reset:

# from master
git reset --hard HEAD~7
Related