Gil's profile at Stack Overflow Coding challenges at Project Euler



Git: Committed on master instead of forking a branch

Sometimes we start working on a feature but mistakenly commit on the master branch. We realize the mistake too late and would like to "move" this commit or commits to a new feature branch. In this post I explain the fastest way to do this, if the commits have not been pushed to upstream yet.

First, if you already pushed the commit to upstream, you should first git revert the commit and then read about git server-side hooks to prevent you to push directly on master again. I won't explain this scenario in detail nor discuss direct pushes on master.

Next, let's see how to solve our problem. The situation is not really complicated, especially if you keep in mind that branches in git are just pointers to commits. You can see this for example just typing from the repo's root directory:

cat .git/refs/heads/master

which will print the commit the master branch is pointing at. In a picture our situation is as follow:

--- o ----------- o
 we want to     master
 fork here       HEAD

The solution is:

  1. Create a new branch pointing at master/HEAD
  2. Move the master branch (pointer) back one commit

In git commands this becomes:

git branch my-branch
git checkout master
git reset --hard HEAD~1

Note in the last command we need the '--hard' option otherwise the changes in the bad commit will be left as unstaged/untracked in our working directory.