3

Recently I got to know git submodules. They appear to be self-sufficient projects with their own git structure and branches.

When I switch main project's branch, does this also switch submodule's branch? How does git handle this situation?

Paul
  • 25,812
  • 38
  • 124
  • 247

1 Answers1

7

I recently came across a similar question. (I'll let you read the content of this answer as it gives you the background to my answer).

A submodule is just a reference to a repo and a commit in this repo.
When you switch branch, the reference may change (if the branch you're switching to uses a different reference) but the filesystem of the submobule will remain untouched.
So writing git status will yield a result showing that your submodule status differs from the one in your current HEAD.

To make the submodule point to the right commit for HEAD, simply invoke:

$ git submodule update 

In addition, the branch of your submodule is not interesting to the enclosing repo as the reference is always added toward a commit and not toward a branch. The branches in your submodule will therefore only reflect your branching strategy for the submodule and do not need to match the enclosing repository's branching strategy.

Community
  • 1
  • 1
Thibault D.
  • 10,041
  • 3
  • 25
  • 56
  • Could I freely switch current branch in submodule without having effect on main project? I did this recently and on `git add .` some changes (I didn't understand what exactly) in submodule have been added too. – Paul Oct 24 '16 at 21:40
  • 1
    My answer was limited to switching branch but your question is a legitimate one since the behavior is a bit different (but still logical). If you switch branch in the submodule and then do `git add .` on the enclosing submodule, then you will add this submodule change to your commit. Always do `git status` before you commit as it will clearly show you what changes are stages for commit and you will be able to see that you are committing some changes in the submodule. – Thibault D. Oct 25 '16 at 06:21
  • 1
    If so is the case and you did not want that, simply _unstage_ the submodule changes by doing `git reset HEAD path/to/submodule` (this will not change anything in the submodule's file system) – Thibault D. Oct 25 '16 at 06:21
  • 1
    It's logical that `git add` will stage your submodule changes because that's the only way you can add your submodule changes to a commit. You can also invoke `git submodule update` before doing `git add` to ensure that your submodule is updated to your HEAD's status if you want to avoid to `reset` after you `add`. – Thibault D. Oct 25 '16 at 06:23