Search code examples
gitgit-submodules

Should "git submodule update" or "git submodule init" be executed first?


Per this GitHub issue:

# run git submodule update and the && makes sure init is only ran if the first worked
git submodule update && git submodule init  
# https://github.com/UCSD-PL/proverbot9001/issues/73#issue-1570685156

However, I believe that the following is the correct, or more safe, or standard, way:

# - git submodule init initializes your local configuration file to track the submodules your repository uses, it just sets up the configuration so that you can use the git submodule update command to clone and update the submodules.
git submodule init
# - The --remote option tells Git to update the submodule to the commit specified in the upstream repository, rather than the commit specified in the main repository. ref: https://stackoverflow.com/questions/74988223/why-do-i-need-to-add-the-remote-to-gits-submodule-when-i-specify-the-branch?noredirect=1&lq=1
git submodule update --init --recursive --remote
# - for each submodule pull from the right branch according to .gitmodule file. ref: https://stackoverflow.com/questions/74988223/why-do-i-need-to-add-the-remote-to-gits-submodule-when-i-specify-the-branch?noredirect=1&lq=1
git submodule foreach -q --recursive 'git switch $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo master || echo main )'
# - check it's in specified branch. ref: https://stackoverflow.com/questions/74998463/why-does-git-submodule-status-not-match-the-output-of-git-branch-of-my-submodule
git submodule status

Am I correct?

Cross-posted to r/git at Reddit.


Solution

  • A simpler instruction for the UCSD-PL/proverbot9001 repository, which references a lot of submodules (cf. its .gitmodules file), would be to just use the git clone --recurse-submodules option:

    That would do everything: clone the parent repository, initialize all submodules and update them. All in one go.

    As explained in "What is the point of 'git submodule init'?", separating both steps (init and update) makes sense when you do not want all submodules (because it would take too much time/resource to clone them), and want only to work on a subset.

    In that case, yes, init must comes before update.

    This comes from commit be4d2c8, Git v1.5.6-rc0, May 2008

    submodule update: add convenience option --init

    When a submodule is not initialized and you do not want to change the defaults from .gitmodules anyway, you can now say

    $ git submodule update --init <name>
    

    When "update" is called without --init on an uninitialized submodule, a hint to use --init is printed.