How to create new git repo from sub-directory of an exisiting repo

tl;dr

In the existing repo

cd existing/repo  
git subtree split -P <subdirectory> -b <branch-name>

cd new/repo  
git init  
git fetch /path/to/old/repo <branch-name>  
git checkout -b master FETCH_HEAD  

Long version

I recently spent some time creating a npm module. It was a relative simply thing, I had hacked some code into this ghost instance and wanted to do it right.

As I was developing it morphed into an exploration of writing npm modules and I split the functionality out into various sub-modules. I am now at the point where I want to publish them. The are separate modules so to do it right they should really be in their own repos. The are however all in one.

I looked at a couple of options such as sparse-checkout which can be used as such

mkdir myrepo  
cd myrepo  
git init  
git config core.sparseCheckout true  
git remote add -f origin git://...  
echo path/to/subdir/*> .git/info/sparse-checkout  
git pull origin master  

The will filter out everything but path/to/subdir however what I want is that the contents of that directory become the root of my repo.

What worked for me was:

In the existing repo

git subtree split -P <prefix> -b <branch-name>  

The prefix will be the subdirectory you want to split. This creates a branch in your repo from that directory

Next; create your new repo

mkdir myrepo  
cd myrepo  
git init  

Then fetch/checkout (pull works too) the branch into your new repo

git fetch /path/to/old/repo <branch-name>  
git checkout -b master FETCH_HEAD  

You can clean up the extra branches with (-D to force):

git branch -d <branch-name>