gitgit-subtree

how to migrate multiple branches of a subfolder to another repo with git subtree


I like to migrate a subfolder with full history from repository 1:

a -> b -> c (branch 1)
      \-> d (branch 2)

to the same target folder in repository 2:

          old -> merged_subfolder (master)
              /
a* -> b* -> c* (branch 1)
        \-> d* (branch 2)

with * denoting the limitation to subfolder.

So far I have used

git subtree split -P subfolder -b branch_1
git subtree split -P subfolder -b branch_2
git subtree add -P target_folder repo_1 branch_1

Then I created branch 2 at b* in repository 2, but

git subtree add -P ./ repo_1 branch_2

does not work, because

prefix './' already exists.

Any suggestions to solve the problem?

And later, how to merge branch 2 with master in repository 2?


Solution

  • The -b option to git subtree split specifies a new branch to be created that contains the new history, not the branch to create the history from. You created two new branches branch_1 and branch_2 which both contain the new history for the branch you were currently in.

    Then I created branch 2 at b* in repository 2

    This doesn't have any effect. git subtree add fetches a commit and its history from a repository and merges it into the current branch; it doesn't look at other branch names at all.

    prefix './' already exists.

    You can't add a subtree for an existing directory. Adding a subtree without merging it would just be an ordinary fetch; you can obviously still add (and merge) a subtree and revert the merge afterwards.

    In summary, to do the full migration:

    # in repository 1
    git subtree split -P subfolder -b branch_1_new branch_1
    git subtree split -P subfolder -b branch_2_new branch_2
    
    # in repository 2
    git subtree add -P target_folder repo_1 branch_2_new
    git branch branch_2 HEAD^2
    git reset --hard HEAD^
    git subtree add -P target_folder repo_1 branch_1_new
    git branch branch_1 HEAD^2
    

    If you later decide to merge the second branch into the main project, do

    git subtree merge -P target_folder branch_2