3

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?

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
Gilroy
  • 198
  • 1
  • 2
  • 11

1 Answers1

3

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'
Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 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`, although getting that right looks tricky. – torek May 04 '17 at 17:00
  • I agree and will edit later (I am commuting) I was just proposing the beginning of a solution, mentioning the possibility of following a branch for a submodule. – VonC May 04 '17 at 17:02
  • Thank you for your responses. I've appreciated your help however I've created a script that submodules will follow the main repositories branch. – Gilroy May 09 '17 at 07:35
  • @GilroyToledano Nice: is your script available in a gist somewhere? (https://gist.github.com/) – VonC May 09 '17 at 07:53