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 against 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 rebase, one of my favorite tools.

First, make sure you’re on master (or whatever the default upstream branch is) and save a reference to your current local HEAD as master-backup:

git checkout -b master-backup master
git checkout master

Add the upstream repository as a remote and fetch upstream’s commits.

git remote add upstream https://github.com/..../whatever.git
git fetch upstream

Revert the local HEAD to the upstream HEAD. Now master should match upstream/master and master-backup should still retain your original commits.

git reset --hard upstream/master

Create a new topic branch for your fix, based on our old master branch.

git checkout -b topic-branch master-backup

Rebase the new topic branch against master.

git rebase 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.

Once you’re done, you can delete the old backup master using:

git branch -D master-backup

If you found this post useful, please consider supporting my work with a street taco 🌮.