Search code examples
gitgit-submodules

add existing unversioned directory as git submodule in place (while avoiding moving and copying as much as possible)


I'm trying to convert a unversioned subdirectory of a git project clone into a submodule. The straightforward way would be to move it out, create a project and re-add this project as a submodule. Is there a way to do this in place, e.g. avoid moving, copying locally and transferring most of the data again from the server?

Example:

I have a git project named "test" cloned to a directory "test", where the only versioned file is readme.md. Hoewver, there's a huge subdirectory testsm which i'd like to create a git project "testsm" for and then add it as a submodule in the folder "test/testsm".

/test
/readme.md (versioned)
/testsm/* (yet unversioned)

Solution

  • You can add an existing git repository with git submodule add.

    In your case, you first need to create a new git repo with git init in the testsm directory. You will also need to create at least one commit.

    You will then have this structure:

    base
    `- .git
    `- readme.md
    `- testsm
       `- .git
       `- other files...
    

    Once you are there, you can add the submodule with:

    git submodule add ./testsm
    git commit # To actually commit the changes
    

    The following steps are optional.

    If you need to set an upstream url, you can use the git submodule set-url command to set the submodule URL to what you want.

    You can also move the testsm/.git repository to the parent .git repository with git submodule absorbgitdirs.