I often do this – I work away on my master branch and suddenly realise ‘damn I should have branched before I started this’. Usually this happens because what I think will be a trivial change snowballs into something much more sweeping. I thought I would record here how to deal with situations like this by retroactively creating a branch and rolling master back to a previous state. Note: backup your data first and this is only ideal if you haven’t pushed changes to a remote repo yet.
So here was the situation. My last ‘known good’ state was 8399227db and I wanted to move all subsequent work out of master and into a branch. So first lets create that branch starting from the last known good state:
git branch refactor_branch 8399227db
Next I check out the branch and merge all the changes from master into it:
git checkout refactor_branch git merge master
Now I switch back to master and chuck away all changes made since the branch point (did I mention you should backup your work first?):
git checkout master git reset --hard 8399227db
So I rebased the master branch to an older commit. Now I push my branch up to the remote repository and breath a sigh of relief that my work is backed up in the cloud and master remains usable for others working on it:
git push origin refactor_branch
As a last couple of steps, I remove my local branch and checkout the remote branch as a tracking branch:
git branch -D riab_to_inasafe git branch --track riab_to_inasafe origin/riab_to_inasafe git checkout riab_to_inasafe
Git being git, there are probably a thousand other ways to accomplish the same thing, but the above process works for me!