11

I'm trying to create a gitsubtree of an existing repository, for example:

-> projectA/projectB

Project A is the parent, i want to add project B as a git subtree.

git subtree -P projectB ssh://git@github.com/projectB.git master

But it fails, and shows the following message:

prefix 'projectB' already exists.

I don't want to download all the repository again, I just want to add this directory to my gitsubtree.

This directory project B isn't tracked by Project A git.

thanks in advance

ricardotk
  • 111
  • 1
  • 4
  • 1
    Do the projectB folder already exists? If so does it contain anything? Git subtree will refuse to create the subtree if the directory where it would be placed contains anything at all. – Maic López Sáenz Jul 25 '13 at 20:38
  • Seems impossible currently(git v2.0) if projectB folder already exists, and removing the exist projectB directory with `rm -rf projectB` then do `git subtree add projectB_directory git@github.com/projectB.git master` to download again is the only choice. – Allen Jan 23 '15 at 10:40

2 Answers2

9

You can add projectB as a subtree of projectA using vanilla git (you don't need git subtree).

cd projectA
git remote add projectB_remote git@github.com/projectB.git
git fetch projectB_remote
git checkout -b projectB_branch projectB_remote/master
git checkout master
git read-tree --prefix=projectB/ -u projectB_branch

Explanation

  1. Enter the local projectA repo.
  2. Add a new remote called projectB_remote with projectB's url.
  3. Fetch projectB_remote without merging.
  4. Create and checkout a projectB_branch; bring in the projectB_remote/master files.
  5. Return to projectA/master.
  6. Create a subtree in projectA/master that contains a checkout of the projectB_branch.

Resultant Directory Structure

projectA
    projectB
    other.txt
    project.txt
    A.txt
    files.txt

See http://www.git-scm.com/book/en/v1/Git-Tools-Subtree-Merging

lig
  • 3,567
  • 1
  • 24
  • 36
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • 4
    While this solution may be effective, it does NOT answer the OP question. – Joshua Wilson Jan 10 '19 at 23:24
  • 1
    Will the "virtual" directory projectB be created? – Sandburg Jan 02 '20 at 16:23
  • 1
    @Sandburg yes, "virtual" directory projectB will be created under projectA. And this is assuming you don't already have projectB folder in projectA repo. If you do, then the last `git read-tree` step would fail with "fatal: refusing to merge unrelated histories" error. – Devy Jun 01 '20 at 02:51
4

When adding a subtree, it seems that the prefix (subdirectory in which you will add the subtree) cannot already exist.

I worked around this problem by checking-out to a commit before this subdirectory existed, doing the git subtree add, and then merging with the branch that contained my old subdirectory contents.

Chris Peckham
  • 711
  • 6
  • 10