Search code examples
gitgit-subtree

Can I do a subtree merge from a subdirectory?


Let's assume two git repositories with some files in them:

ProjectA
+ a
+ b

ProjectB
+ foo/x
+ foo/y
+ bar/z

Now I want to include the directory foo from ProjectB into ProjectA.

As far as I understand when I do git subtree add the prefix is the path that it should have in the receiving repository, so when I do

git subtree add --prefix=project_b --squash URL_of_ProjectB

I would end up with

ProjectA
+ a
+ b
+ project_b
  + foo/x
  + foo/y
  + bar/z

Can I somehow specifiy that I only want foo fetched to get this layout?

ProjectA
+ a
+ b
+ project_b
  + x
  + y

Solution

  • I think this can't be accomplished with git subtree. Maybe git filter-branch is what you need:

    git remote add b <URL_TO_B>
    git fetch b
    git checkout -b b_master b/master
    

    Rewrite the history of b only containing foo:

    git filter-branch --prune-empty --subdirectory-filter foo b_master
    

    or use git subtree split

    git subtree split -P foo --branch foo
    

    and add it as as subtree

    git subtree add --prefix=project_b --squash b_master or foo