Search code examples
gitgit-subtree

git subtree add: change prefix preserving local commits


is there an easy way to move a subtree added using the following cmd

git subtree add --prefix=<prefix> <repository> <commit>

in other terms, is it possible to change prefix from dir1 to dir2.

the answer to git subtree: possible to change subtree branch/path in a forked repository? suggests to remove the subtree then add it back.

It doesn't work for me because I need to preserve local commits, is there another way?


Solution

  • One alternative is splitting from your current commit that include the local commits you want to preserve:

    git subtree split --prefix=dir1 HEAD
    
    # Create a branch with the printed commit just to use it later
    git branch split_dir_1 <split_commit>
    

    And then do what was described it in the question you mentioned, delete the subdirectory and re-add the subtree.

    git rm dir1
    git commit
    git subtree add --prefix=dir2 . split_commit
    

    Bear in mind that by doing this you will still be able to see in the repository history when the first subtree was created and deleted and re-added.