dev: git submodule magic

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:

  1. 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).
  2. 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
  3. The fix is pretty each, go find the offending submodule and look in the parent directory .gitmodules and you should see a branch = main or master or dev and then look at the actual default branch and change the file.
  4. 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.
  5. 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
  6. 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:

  1. So the magic is git submodule foreach which will run the command for every submodule
  2. 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
  3. Finally a git submodule foreach --recursive git pull --ff-only and you are set!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I’m Rich & Co.

Welcome to Tongfamily, our cozy corner of the internet dedicated to all things technology and interesting. Here, we invite you to join us on a journey of tips, tricks, and traps. Let’s get geeky!

Let’s connect

Recent posts

Loading Mastodon feed…