How to make a Git repo out of a directory in another Git repo

Recently, I’ve been working on a project whose origins started under SVN. In those bad old days, you’d usually want to deal with as few repositories and branches as possible. You locked files so others couldn’t touch them, because merging was like the plague. So as it happens, the iOS client code and the backend server code were stored in the same repository that was eventually migrated to Git.

After inheriting this project, I took it upon myself to complain about this choice until I finally decided to do something about it. Apparently, this is an incredibly easy problem to solve.

  1. Checkout out your repo and all its branches:
$ git clone ssh://git@my.domain.net:4567/proj/my-project.git
$ cat << "EOF" > checkout.sh
#!/bin/bash
for branch in `git branch -a | grep remotes | grep -v HEAD `; do
   git branch --track ${branch#remotes/origin/} $branch
done
EOF
$ chmod 755 ./checkout.sh && ./checkout.sh
  1. Use git to rewrite history:
$ git filter-branch -f --prune-empty --tag-name-filter cat --subdirectory-filter your/directory/here -- --all
  1. Change origin to a new repo:
$ git remote remove origin
$ git remote add origin ssh://git@my.domain.net:4567/proj/my-project-new.git
  1. Push all the branches:
$ git push origin --all
$ git push origin --tags

Congratulations! You’ve now made a new repo out of a specific directory in an existing repo and removed all irrelevant history.