Export subtree in Git with history

GitImportExportHistory

Git Problem Overview


I have a folder in my Git repository that I'd like to move out in to its own repository. Is it possible to move the history of that folder along with the folder?

I've previously been doing just a git rm -r --cached subfolder/ and then git init on the subfolder. However, the history is not imported in to the new repository.

Git Solutions


Solution 1 - Git

Quoting an example from git-filter-branch(1)

> To rewrite the repository to look as if foodir/ has been its project root, and discard all other history:

git filter-branch --subdirectory-filter foodir -- --all

> Thus you can, e.g., turn a library subdirectory into a repository of its own. Note the -- that separates filter-branch options from revision options, and the --all to rewrite all branches and tags.

Solution 2 - Git

For anyone else arriving here in 2021 (or later), git filter-branch is not strongly recommended by the core git team.

> WARNING git filter-branch has a plethora of pitfalls that can produce non-obvious manglings of the intended history rewrite (and can leave you with little time to investigate such problems since it has such abysmal performance). These safety and performance issues cannot be backward compatibly fixed and as such, its use is not recommended. Please use an alternative history filtering tool such as git filter-repo. If you still need to use git filter-branch, please carefully read SAFETY (and PERFORMANCE) to learn about the land mines of filter-branch, and then vigilantly avoid as many of the hazards listed there as reasonably possible.

Instead the recommended tool is git-filter-repo which makes easy work of this problem

git filter-repo --path subfolder/   # Filter the repo to just the sub-dir
git mv subfolder/* .                # Move the contents of the sub-dir to the root
git commit -m "Filtered from main repo"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmatpieView Question on Stackoverflow
Solution 1 - GitjamessanView Answer on Stackoverflow
Solution 2 - GitJamie CookView Answer on Stackoverflow