Yesterday, I posted on how to contribute to a project that uses Git. But what if you forgot the last step in that process? What if you started working, making multiple commits, and never created a feature branch for your code? In that case, you would have been committing to the master branch of the repository: a big no-no.
However, all is not lost! You can go back in time, create your feature branch, and move all of your commits over to it from the master branch with only a few commands.
The first two pieces of information you will need are the SHA hashes (basically the commit IDs) for the last commit you made and the last commit before you want your feature branch to start. Note that the earlier commit should be the commit just before the first one of your new branch.
With those two hashes in hand, here are the git commands to move all of your commits over to a new feature branch.
git branch branchname sha_of_starting_commit git checkout branchname git cherry-pick sha_of_starting_commit...sha_of_ending_commit git checkout master git reset --hard sha_of_starting_commit git checkout branchname
Here is a breakdown of what’s going on above.
git branch branchname sha_of_starting_commit git checkout branchname
First, we create a new feature branch at the point just before we started making all of our commits. Then switch to it.
git cherry-pick sha_of_starting_commit...sha_of_ending_commit
Here is where the magic happens. In the feature branch, we want to copy all of the commits starting just before our first one (i.e. the point we branched from) through the most recent commit. The “…” here is important! It tells Git to include—in order—all of the commits between the two hashes you specified. This is especially handy if you have made dozens (or hundreds, but I really hope you caught yourself before then) of commits before realizing you needed to branch.
git checkout master git reset --hard sha_of_starting_commit git checkout branchname
The last batch of commands switch you back to the master branch, reset the code there to the point from which you branched, and re-checkout your feature branch so that you can continue your work.
That’s it! With 6 lines of Git commands and a little initial legwork to look up two SHA hashes, you can easily create a feature branch after the fact.
Have you ever done this? Let me know your horror stories in the comments. Or, if you have suggestions, I’ll take those too!