New Git Repository from an Existing Subdirectory

In this situation, I had been working in a git repository which had become to large and needed to be split into separate sub-modules. In this case, I really just needed to take out a subdirectory and make it a brand new repository. The great thing is that you can preserve all the history that had happened for that subdirectory if you decide that you want to keep it. There are a number of ways to do this process so this is just the way that I decided and liked the best.

Create new repository from existing subdirectory
First step I did was to make a clone of my existing repository (either by doing a regular copy/paste or a git clone).

Now by doing a filter-branch command we can use the existing git repository starting at the level of the subdirectory:

1
git filter-branch --subdirectory-filter foodir -- --all

After this is complete I needed to clean up and compact the repository:

1
2
3
git clean -d -f  //clean up untracked files
git gc --aggressive //clean up the repository packing
git prune

Done!

Remove history from existing full repository
This is optional if you want to re-write history from your existing repository. Some might just want to do a remove on the directory and then commit. I wanted to go back and re-write history to remove the commits to the subdirectory.

Then I did another clone of the repository which will clean from the history the subdirectory since I didn’t want that information to be in the repository anymore.

1
git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch dir' -- --all

Run a git gc again in this repository just to clean up everything.