6

Reading the documentation of the git submodule command I found out that you can specify a branch for a submodule using

git submodule set-branch -branch <branch name> -- <submodule path>

This results in a config entry in the .gitmodules file

> git config --file .gitmodules --get-regex branch
...
submodule.<submodule name>.branch = <branch name>

However the documentation did not describe what this data is used for. Submodules are still checked out in the detached head state an I've failed to find a way to use this info to do a checkout for the submodule from the parent repository that sets up the submodule in a state that tracks a branch without doing a checkout inside the submodule directly.

What's the benefit of providing this info (other than the .gitmodules file containing info that could be retrieved and used by my own script)? (Or did I simply do the initialisation/update of the submodules the wrong way?)

fabian
  • 113
  • 1
  • 1
  • 7

2 Answers2

8

If you add the submodule with -branch option you can use --remote option to update your submodule to the latest commit of that branch.

git submodule add -branch example URLHERE 
git submodule init
git submodule update --recursive --remote
HoD
  • 3,277
  • 15
  • 19
  • If there is no branch given for a submodule, then `git submodule update --recursive --remote` will update the submodule the the remote branch that HEAD points to, which is usually master. – Morten Zilmer Sep 01 '21 at 08:25
1

One would use git submodules in order to maintain strict version management over your external dependencies.

Git submodules allow you to keep, as a subdirectory of your repository, another repository at a particular snapshot in time, in this way incorporating and tracking version history of the external code.

A git submodule points to a specific commit in an external repository. It is static and only tracks specific commits, but it does not track git refs or branches and is not automatically updated when that repository is updated. This is the very reason why one would use branches.

harrymc
  • 455,459
  • 31
  • 526
  • 924
  • *A git submodule points to a specific commit in an external repository.* I see no hash in `.gitmodule` file. That means Git submodules point to random position for different people. – gavenkoa May 17 '21 at 12:39
  • 2
    @gavenkoa: The repository commit contains a tree object that has reference to the specific submodule commit to use for that repository commit, whereby the submodule commit to use is specified, thus not random. – Morten Zilmer Sep 01 '21 at 08:33
  • 1
    @MortenZilmer You're right. Later I saw `git diff` for submodules containing revisions. Unlike Mercurial Git hides referencing hashes in some binary store. – gavenkoa Sep 01 '21 at 11:00