Search code examples
gitgit-submodulesbamboo

Is it possible to checkout branches of main repository in sync with submodules?


What I want to achieve is whenever I use git checkout on my main repository for example:

git checkout my-branch

my submodules will follow my-branch instead of a detached head.

Is it possible, and if yes, how?


Solution

  • If those submodule repositories have a my-branch of their own, they can be declared to follow that branch

    cd /path/to/your/parent/repo/Foo
    git config -f .gitmodules submodule.bar1.branch my-branch
    git config -f .gitmodules submodule.bar2.branch my-branch
    
    git submodule update --remote
    

    But that involves repeating that each time you checkout a branch in the parent repo.

    torek points out in the comments that those submodules might have submodules of their own, hence the need for the --recursive option.

    You might also want to add --recursive and/or --no-fetch to your git submodule update --remote command.
    Rather than individual git config -f operations, you might want git submodule foreach, again maybe with --recursive.

    git submodule foreach -q --recursive 'git config -f $toplevel/.gitmodules submodule.$name.branch my_branch'
    

    In multiple lines for readability:

    git submodule foreach -q --recursive \
      'git config -f $toplevel/.gitmodules submodule.$name.branch my_branch'
    

    Then you can checkout each submodule to that branch:

    git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git checkout $branch'
    

    In multiple lines for readability:

    git submodule foreach -q --recursive \
      'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; \
       git checkout $branch'