Checking out a branch that contains a new submodule reference
If I clone a repository with git --clone-recursive to checkout the repo and all referenced submodules and then attempt to checkout a branch that contains a new submodule reference, an error prevents me from checking that branch out.
Initial configuration
Create a new main module repo at https://gitlab.com/<company>/<project>/mainmodule with a README.md at gitlab.com.
Create a new child submodule repo at https://gitlab.com/<company>/<project>/childsubmodule with a README.md at gitlab.com.
In the childsubmodule project, Settings -> CI/CD -> Job token permissions add <company>/<project>/mainmodule entry so that mainmodule can access childsubmodule in CI pipelines.
Clone https://gitlab.com/<company>/<project>/mainmodule to a new local folder using:
git clone --recurse-submodules git@gitlab.com:<company>/<project>/mainmodule.git
Create a new branch:
cd mainmodule
git checkout -b demo/add_a_submodule
Add a relative path submodule reference using:
git submodule add ../childsubmodule
Add the changes (the .gitmodules and new submodule folder) and commit and push the new branch to the remote:
git add -u
git commit -m "Add a submodule to branch"
git push -u origin demo/add_a_submodule
Failure Case: Cloning mainmodule recursively getting submodules
Clone https://gitlab.com/<company>/<project>/mainmodule to another new local folder using:
git clone --recurse-submodules git@gitlab.com:<company>/<project>/mainmodule.git test
Try and checkout the branch:
cd test
git checkout demo/add_a_submodule
Failure: The .gitmodules file is updated but the branch doesn't change and these errors are shown:
fatal: not a git repository: ../.git/modules/childsubmodule
fatal: could not reset submodule index
Success Case: Cloning mainmodule and then getting submodules explicitly
Clone https://gitlab.com/<company>/<project>/mainmodule to another new local folder without getting submodules using:
git clone git@gitlab.com:<company>/<project>/mainmodule.git test2
Before changing branch, get the submodules with:
cd test2
git submodule update --init --recursive
Try and checkout the branch:
git checkout demo/add_a_submodule
Update the submodule:
git submodule update --init --recursive
Success: The branch switch is successful and the new submodule is added / updated.
I have repeated the steps using a local Gitea server and in the failure case I do not see the same failure to checkout the branch. Instead the checkout succeeds and then I'm able to update the newly added submodule.