Last Updated: February 25, 2016
·
547
· jtai

Restarting a Git Branch

I tend to think about my code a lot, even when I’m not in front of a computer. Sometimes I’ll think of a refactor or performance improvement on the train, in the shower, or as I’m lying in bed right before I get up in the morning. When I have one of these ideas, I tend to just start banging out code the moment I sit down. I often forget to pull or start a new branch first. Fortunately, git makes it relatively simple to move your commits around as long as you haven’t pushed your changes yet. (Once you push your commits, you shouldn’t alter them because someone else may have pulled them.)

The easiest case is if you have changes that haven’t been committed yet. Just create your branch before committing your changes.

git checkout -b great-train-idea
# now on branch great-train-idea
git commit -a -m "Great idea I thought of on the train"

The next-eaisest case is if you have made several commits in master that you haven’t pushed yet, but you want to move them to a new branch. Since branches are simply pointers to commits in git, you can just create a new brach that points at your new changes, then reset master to the commit before you made those changes.

# assuming current branch is master and working directory is clean
git branch genius-shower-idea
git reset --hard origin/master

The example above works with branches other than master too — if you accidentally made commits on great-train-idea that you wanted to move to a new genius-shower-idea branch, just replace master with great-train-idea in the example. Also, if you’ve never pushed great-train-idea (the branch you mistakenly committed to), you can use git log to figure out which commit to revert to instead of relying on the origin/great-train-idea reference.

The trickiest case is if you have made several commits in master, but master wasn’t up to date. The solution here is to move the commits to a new branch as before, then update master, then replay the changes in your new branch using the new updated master as a starting point.

# assuming current branch is master and working directory is clean
git branch awesome-morning-idea
git reset --hard origin/master

# update master
git pull

# make it as if awesome-morning-idea was branched from up-to-date master
git checkout awesome-morning-idea
git rebase master

Again, let me emphasize that you shouldn’t do any of this if you’ve already pushed your changes. Hopefully, if you were so wrapped up in your idea that you forgot to pull or committed to the incorrect branch, you were also too distracted to push.

This tip was reposted from my blog, jontai.me