0

Assume the following git structure with submodules:

root
|-- .gitmodules
|-- X
    |-- submodule 1
    |-- submodule 2
    ..
    |-- submodule N

Assume that I am working on a branch feature_B from the top module and I am manually creating a branch called feature_B in every submodule.

At some point (assume all the changes in every submodule are pushed to the remote) I need to run some tests with the master topmodule, so what I do:

cd $TOPMODULE
git checkout master 
git pull #just to be sure
git submodule update --init --recursive --force

# do all the testing I need on master

The last command however has reset every submodule to the commit specified by the topmodule. Now I want to go back to feature_B for every submodule that has such branch. How can I do?

Of course I can manually cd into every submodule and git checkout feature_B but assume I have lots of submodules, or heck, even only 5, I'd love a programmatic way for doing it.

What I come up with is the following code, but I would like to know if there is a git command to do the trick

#!/bin/bash
#set -x
#set -e

cd $TOPMODULE

BRANCH_NAME=$1
SUBS=$( cat .gitmodules | grep -Po "(?<=path = )keyword.*" )
git show-ref --verify --quiet refs/heads/${BRANCH_NAME}

for SUBMODULE_PATH in ${SUBS}
do
    cd $SUBMODULE_PATH
    
    if git show-ref --verify --quiet refs/heads/${BRANCH_NAME}; then
        #echo "checkout " $BRANCH_NAME "in" $SUBMODULE_PATH 
        git checkout $BRANCH_NAME
        git pull
    else 
        echo $BRANCH_NAME "does not exist in" $SUBMODULE_PATH  
    fi
    cd - 
done

Thanks for your help!

Fra93
  • 1,992
  • 1
  • 9
  • 18

1 Answers1

1
git submodule foreach git fetch
git submodule foreach git checkout origin/feature_B

or if you know your feature_B updates are always "clean", they're always direct descendants of the existing tip,

git submodule foreach git pull --ff-only origin feature_B

or see here to tell Git about the upstream branches.

jthill
  • 55,082
  • 5
  • 77
  • 137
  • Thanks a lot! Would this command fail if `feature_B` is not a branch in one submodule? – Fra93 Nov 22 '22 at 14:33
  • 1
    Yes, see the linked answer for one way to configure the branches per-submodule. – jthill Nov 22 '22 at 14:37
  • So if not all the submodules have the feature branch I need, I still need to use the bash script I added in my question, or I configure each branch manually. Fair enough, I can't expect git alone to cover all possible scenarios. Thanks! – Fra93 Nov 22 '22 at 14:44
  • Another way is to configure the fetch spec in each submodule to map the upstream branch you want to a particular tracking ref. – jthill Nov 22 '22 at 15:00