Git Submodules with Detached HEAD

This week we at Sprout Venture migrated our largest project to git. Without going into detail about our process we ran into a problem with our superproject’s submodules initialized with detached HEADs; regardless if they’re added with the branch set.

The .gitmodules file would properly show the branch, e.g.

[code language=”text”]
[submodule “wordpress”]
path = wordpress
url = git://github.com/WordPress/WordPress.git
branch = 3.7-branch
[/code]

But when a branch would be checked out the branch for each submodule wouldn’t be set (or worse at times reset to detached). Not a big deal if the branch has a few submodules but ours has 100s.

I found out about $git submodule foreach and created a little command/script that would recursively loop through all of the projects submodules and checkout the branch according to the branch set in the submodules config file (see above).

[code language=”bash”]
git submodule foreach -q –recursive ‘branch=”$(git config -f .gitmodules submodule.$name.branch)”; git checkout $branch’
[/code]

Just change to the absolute path of where the .gitmodules file can be found.