Search code examples
gitgit-submodulesgit-subtree

Git: Get a subfolder from a repository to a new one without losing history


I have a git repository of an application with multiple branches. The source tree consists of several directories. E.g:

main_folder
|--> .git
|--> dir0
|--> dir1
|--> dir2

Unfortunately, from the beginning of the development I didn't use git-submodules nor git-subtree. Now I want to move one of the directories, e.g dir0 to a new repository as a new stand-alone application, Of course if possible, I want to keep both history and branches of the corresponding directory.

So I have two questions:

  1. The first and obvious one is how I can do this?
  2. Also for the old repository, what would be the best practice? Just delete the folder and commit the changes, or something else?

Solution

  • use git splits

    it basically use your same git filter-branch approach but has an easier interface.

    1. install git splits. I created it as a git extension, based on jkeating's solution.
    2. Split the directories into a local branch #change into your repo's directory cd /path/to/repo #checkout the branch git checkout MyOldBranch #split directory or directories into new branch git splits -b MyNewBranch dir1 dir2 dir2...

    Stop here (you're done) if all you want is the directories copied with their history to the new MyNewBranch branch.


    If you want the new branch pushed to a standalone repo

    1. Create an empty repo somewhere. We'll assume we've created an empty repo called new_repo on GitHub that has path : git@github.com:simpliwp/new_repo.git

    2. Push to the new repo. #add a new remote origin for the empty repo so we can push to the empty repo on GitHub git remote add origin_new_repo git@github.com:simpliwp/new_repo.git #push the branch to the new repo's master branch git push origin_new_repo new_repo:master

    3. Clone the newly created remote repo into a new local directory
      #change current directory out of the old repo cd /path/to/where/you/want/the/new/local/repo #clone the remote repo you just pushed to git clone git@github.com:simpliwp/new_repo.git