Home > Net >  Pull all submodules to a specific branch
Pull all submodules to a specific branch

Time:11-22

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!

CodePudding user response:

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.

  • Related