Skip to main content

Git: Moving old commits to a new branch

Before I started judiciously applying the topic branch workflow in git, I did a lot of commits in master and my pull requests were really messed up. I needed to clean this up the other day. The idea is that I wanted to be able to move a couple of really old commits off into their own topic branch, but my local repository and upstream had diverged significantly. For some reason, it wasn’t possible to just cherry-pick everything, and exporting the commits as patches to apply later didn’t seem to work either. Instead I found a pretty good solution with interactive rebase, one of my favorite tools. Here’s what I did:

# Make sure you're on master and save a reference to your current
# local HEAD as master-backup

git checkout master
git checkout master-backup

# Add the upstream repository as a remote and fetch their commits

git remote add upstream
git fetch upstream

# Move the local HEAD to the upstream HEAD

git reset --hard upstream/master

# Create a new topic branch for your fix, based on our old master
# branch (the new branch is pointing upstream)

git checkout -b topic-branch master-backup

# Interactively rebase the new topic branch against master

git rebase -i master

Then you can just force push everything up to Github and open a pull request like normal against the topic branch. In my case I had several different commits tangled up into master, so I had to repeat the last two steps a few times.