Well, git submodules are useful and frustrating at the same time, since we have literally a few dozen of these, I finally spent time figuring out what was wrong and it comes down to two commands and making sure you do not have error:
- If you have a set of submodules, the command
git submoduled update --init --recursive
should be all you need to get all the submodules downloaded and in the right commit (albeit in detached mode, but more on that later). - The problem is that if there are any problems with the way that you created the submodules, then the above command is that if you have misconfigured the default branch when you cloned then you will have this fail. You will get an error like
fatal: Unable to fech in submodule path
message - The fix is pretty each, go find the offending submodule and look in the parent directory
.gitmodules
and you should see abranch = main
ormaster
ordev
and then look at the actual default branch and change the file. - If you just want to use actual commands, then to set the default branch, when you create the submodule make sure to add the -b option,
git submodule add git@github.com:richtong/new_module -b main
if that is the default. - Now to figure out what the default is, you can run
git rev-parse --abbrev-ref origin/HEAD | cut -d / -f 2`
and you need the cut in order to just get main or master - If you want to add a tracking branch after a setup, either edit the .gitmodules or run
git config -f .gitmodules submodule.asubmodule.branch main`
Now that this is set, by default you are in detached state, you are not tracking the actual branch, so you need to run a git switch and the git pull –ff-only to get everything up to the latst branch:
- So the magic is
git submodule foreach
which will run the command for every submodule - So a good example wout be
git submodule foreach --recursive git switch `git rev-parse --abbrev-ref origin/HEAD | cut -d / -f 2` which will get you to the tracking branch from detached mode
- Finally a
git submodule foreach --recursive git pull --ff-only
and you are set!
Leave a Reply