If you want to turn a folder within a Git repository into a brand new repository, and you don’t want to lose any of your Git history or changes, you can use git filter-branch command. For example,
git filter-branch --prune-empty --subdirectory-filter SUBFOLDER_NAME master
All the other files but the subfolder would be removed. Now you can add a new remote and then push it to your new location.
How to merge an existing repository into a new subdirectory of the current repository?
Here is the answer!
If the exist repo path is: /path/to/ex/repo, and you can give it a new name such as: ExRepo
If you want to import this repo to the current repository as sub-directory SubDir:
- git remote add -f ExRepo /path/to/ex/repo
- git merge -s ours –no-commit ExRepo/master
- git read-tree –prefix=SubDir/ -u ExRepo/master
- git commit -m “Merge ExRepo as our subdirectory SubDir“
It’s done! Just four lines. What do these steps mean?
- fetch the other project “ExRepo“
- prepare for the later step to record the result as a merge
- read “master” branch of ExRepo to the subdirectory “SubDir“
- record the merge result
You may commit exist changes first if you have got the error “Merge with strategy ours failed“.
One more thing, how to update SubDir after merging is simple the same. Just type:
- git pull -s subtree ExRepo master
Enjoy & Good lock!