Search code examples
gitgit-submodules

What is the proper workflow for being able to update code within a Git Submodule?


I'm trying to implement a shared library as a Git submodule and I'm struggling with the best practice for pushing changes within the submodule folder. I can get it to work but it feels awkward.

This is my test repo https://github.com/rupe120/submodule-test

I setup the submodules to track a given branch but that doesn't help after a fresh clone and submodule update. I understand that the sub module reference is a gitlink but when I go into the submodule I am unable to push because the "branch" it references is not a branch but seemingly the gitlink.

I either need to checkout the tracked branch in the submodule, so I can push the changes and pull down them down in a separate clone (performing a git pull and git submodule update). The problem is that any time I want to make a change a file in the submodule folder after performing a submodule update, I need to first checkout the tracked branch to get it off of the gitlink or push using git push origin HEAD:<name-of-tracked-branch>

It seems that I should not need to specify the name of the tracked branch in my push when its already part of the configuration. Is there something I'm missing?


Solution

  • A git clone --recurse-submodules should clone, checkout and update both submodule to their latest commits of their respective remote trakcing branches.

    But they would still be checked out at a SHA1, not in a branch.

    You would need a foreach command to check their branch:

    git submodule foreach -q --recursive 'git switch $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo main)'
    

    multiple lines:

    git submodule foreach -q --recursive \
      'git switch \
      $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo main)'
    

    The OP Josh Russo points out in the comments to this gist:

    git pull
    git submodule update --init --remote
    git submodule foreach  -q --recursive 'git switch $(git config -f $toplevel/.gitmodules submodule $name.branch || echo main)'
    git submodule foreach  -q --recursive 'git pull'