I want to create a new git repository of a folder under an existing git repository. I want the history to be preserved in the new repository. How do I create this new git repository?
3 Answers
You can clone it, and then apply on the clone a filter-branch in order to split that repository, extracting only the directory you want (with its full history).
See Detach subdirectory into separate Git repository
Note the git clone --no-hardlinks /XYZ /ABC
used during the cloning step:
The
--no-hardlinks
switch makes git use real file copies instead of hardlinking when cloning a local repository.
Assuming you only want to keep the subdirectory as a separate project: you can use git filter-branch
for that.
- Create a new branch
- Define a "tree filter" that rearranges a checked out copy the way you want, ideally as a separate script
- Run
git filter-branch --tree-filter=/path/to/script thebranch
You now have a separate branch that is not related to the normal development stream, containing just the subdirectory. Whoever clones the new branch gets only the subproject history.

- 28,572
- 1
- 42
- 64
-
1You don't need to define a (custom) tree filter here. The built-in subdirectory filter does exactly this, as described in the answer linked to in [VonC's answer](http://stackoverflow.com/questions/5421386/how-do-i-create-a-new-git-repository-from-a-folder-in-an-existing-git-repository/5421581#5421581). You also don't want to do this on a new branch in the same repo, but rather in separate clone. If a repo contained both the subdirectory and full project on separate branches, an initial clone would fetch both, creating remote tracking branches for each. Wasteful! – Cascabel Mar 24 '11 at 15:30
You can clone it and keep the files you want; history will then be preserved.

- 86,532
- 28
- 194
- 218