Detach subdirectory into a separate Git repository

  • git
git-commands.jpg
None

When you are working with Git repositories, sometimes you want to separate out a folder into its own repository, removing it from history in the parent repository, but keeping history for the folder in the newly create repository. Here are the steps.

First of all, you want to clone your repository and then use git filter-branch to mark everything but the subdirectory you want in your new repo to be garbage-collected. To clone your local repository:

$ git clone --no-hardlinks https://review.tkanemoto.com/a/web/xampp apache
The --no-hardlinks switch makes git use real file copies instead of hardlinking when cloning a local repository. The garbage collection and pruning actions will only work on blobs (file contents), not links. Then just filter-branch and reset to exclude the other files, so they can be pruned:
$ git filter-branch --subdirectory-filter apache HEAD -- --all $ git reset --hard $ git gc --aggressive $ git prune
and now you have a local git repository of the apache sub-directory with all its history preserved. Note: For most uses, git filter-branch should have the added parameter -- --all. (Yes that's really dash dash space dash dash all. This needs to be the last parameters for the command.) This keeps the project branches and tags included in the new repo.

-- Source: http://stackoverflow.com/questions/359424/detach-subdirectory-into-separate-git-repository

Now for the parent git. We need to remove the directory from history.

$ git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch apache' HEAD $ git gc --aggressive --prune=now $ echo "apache/" >> .gitignore $ git add .gitignore $ git commit -m "Add apache/ to .gitignore"
-- Source: http://help.github.com/removing-sensitive-data/