How to split a git repository into two

First of all, as a disclaimer: I am not a git guru but. It seems this subject is somehow obscure and it required googling around almost one day. Well, let's get started. I assume that we have the following structure:

repo1.git/
                .git/
                directory1/
                directory2/
                directory3/

and we want:

repo2.git/
                .git/
                directory2/
repo3.git/
                .git/
                directory1/
                directory3/

Please note that only step one will be carried out on server and the rest of them on client.

Step 1. Create two new empty repositories

git init --bare repo2.git
git init --bare repo3.git

Step 2. Clone the original repositories

git clone --no-hardlinks git@server:repo1.git repo2
git clone --no-hardlinks git@server:repo1.git repo3

Step 3. Filter-branch and reset to exclude other files, so they can be pruned. This step is actually very time consuming. So, depending how large your repository is, you will have to go to buy a coffee or not :)

cd repo2/
git filter-branch --subdirectory-filter directory2 HEAD -- --all
git reset --hard
git gc --aggressive
git prune

Step 4. Replace remote origin to point to new repo2.git and push the changes

git remote rm origin
git remote add origin git@server:repo2.git
git push origin master

Step 5. Remove directory2/ from the repo3. You finished your coffee? If yes, go and buy another one :)

cd ../repo3
git filter-branch --index-filter "git rm -r -f --cached --ignore-unmatch directory2" --prune-empty HEAD
git reset --hard
git gc --aggressive
git prune

Step 6. Replace remote origin to point to new repo3.git and push the changes.

git remote rm origin
git remote add origin git@server:repo3.git
git push origin master

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.