Split a subfolder out into a new repository

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.

Merge existing repository into a subdirectory/subfolder

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:

  1. git remote add -f ExRepo /path/to/ex/repo
  2. git merge -s ours –no-commit ExRepo/master
  3. git read-tree –prefix=SubDir/ -u ExRepo/master
  4. git commit -m “Merge ExRepo as our subdirectory SubDir

It’s done! Just four lines. What do these steps mean?

  1. fetch the other project “ExRepo
  2. prepare for the later step to record the result as a merge
  3. read “master” branch of ExRepo to the subdirectory “SubDir
  4. 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:

  1. git pull -s subtree ExRepo master

Enjoy & Good lock!