3

My parent project has a couple of submodules added to it.

For deployment purposes, I want to checkout a specific branch eg master, staging, etc in each submodule and pull the latest commit of this branch in each submodule.

I've checked various answers on SO like the following:

But it's very much confusing as to what is the best practice in 2022. I've git version 2.30.1 (Apple Git-130)

So far I've understood that this command can be used to fetch the latest commit (from their respective remotes) of the branch already mentioned in .gitmodules file.

git submodule update --remote --merge

But how exactly do I use the -b option in order to switch the branches in all submodules at the same time, for diff environments deployment?

Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86

1 Answers1

2

I figured out a solution that worked for me.

Simple Solution

git submodule foreach <command>

The above command will run for each submodule.

So I ran the following 2 commands to checkout out desired branch and pull latest commit in each submodule

git submodule foreach git checkout -B staging origin/staging
git submodule foreach git pull --rebase

Complex Solution

The following command updated the target branch in the .gitmodules file

git config -f .gitmodules submodule.<submodule_path>.branch <target_branch_name>

I used the following command for the batch update for all submodules

git submodule status | awk '{ print $2 }' | xargs -I {} git config -f .gitmodules submodule.{}.branch master

Then the following command pulled(fetched & merged) the latest commits of the respective remotes of each submodule

git submodule update --remote --merge

--merge alternatives:

  • Omit - ommitting --merge will do a hard reset to submodules' remote repo
  • --rebase - this will rebase your local changes on top of the remote branch's latest commit of submodules
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86