Search code examples
gitgit-submodules

Copy git submodules from one repo to another


I'm developing a set of libraries that depend on a common set of other libraries.

I'd like to copy the .gitsubmodules file from one repo that has all of the necessary submodules into all of the other repos.

However I can't seem to get git to recognize the submodules file, or otherwise do anything to pull the submodules into the new repository.


Solution

  • Git needs two things to realize a submodule:

    1. the configuration from the .gitmodules file, and
    2. a corresponding commit entry in the index...which you get by running git submodule add.

    This is explicit in the documentation, which says this about the git submodule init command:

    Initialize the submodules recorded in the index (which were added and committed elsewhere) by setting submodule.$name.url in .git/config. It uses the same setting from .gitmodules as a template....

    Practically, this means you'll need to run git submodule add for each submodule. If you do this often, you could write a script that would read the submodule configuration from the .gitmodules file and run the appropriate git submodule add commands. Maybe something like:

    #!/bin/bash
    
    submodules=( $(git config -f .gitmodules --name-only --get-regexp 'submodule\..*\.path' | cut -f2 -d.) )
    for name in "${submodules[@]}"; do
        path="$(git config -f .gitmodules --get submodule."$name".path)"
        url="$(git config -f .gitmodules --get submodule."$name".url)"
    
        git submodule add "$url" "$path"
    done