JAM
JAM

Reputation: 770

How to checkout a branch with submodule from a branch without it

I have three branches on my local machine:

The branch without submodule used to have a submodule, and I removed the submodule by following instructions from this SO post. I did not want to remove submodule from master and feature-branch-with-submodule.

However, now that I am done with feature-branch-without-submodule, I want to switch to feature-branch-with-submodule. So I do git checkout, but got the error:

fatal: not a git repository: src/vendor/mysubmodule/../../../../../.git/modules/src/vendor/mysubmodule

How do I fix it so that the branch with submodule has it, and the branch without does not, and that I can freely switch back and forth using git checkout?

Upvotes: 9

Views: 4475

Answers (2)

kikeenrique
kikeenrique

Reputation: 2669

For 1-2 days I've been wondering what's the problem. Here is a link with the most approximate (and really awful) answer I've found so far:

Checkout branch with different submodules is not working

And for a quick answer:

Supposing, for example, branch master has submodule A and branch alpha has submodule B.

To properly checkout master you should, essentially
git submodule deinit .
git checkout master
git submodule update --init --recursive

To go back to alpha, again
git submodule deinit .
git checkout alpha
git submodule update --init --recursive

Upvotes: 6

TrebledJ
TrebledJ

Reputation: 8987

feature-without-submodule to feature-with-submodule

If you've completed removed the submodule (i.e. even the cache in .git/modules/path/to/submodule), then here's one way that seems to work.

(I assume you're working with a clean working tree. That is, no modified files to begin with.)

rm -rf <path> # Optional: if you have files in the path.
git submodule add [--name <name>] <repository> <path>
git submodule deinit -f <path>
git checkout -f feature-branch-with-submodule
  1. Delete existing files in the submodule path.

  2. Reintroduce the deleted submodule. The objective is to initialise the .git/modules/<name> folder to the repository so that git merge is happy. You'll need:

    • the repository of the submodule
    • the path to the submodule
    • the name passed to --name (not needed if same as path)

    You can find these by looking at your diffs of .gitmodules.

  3. De-initialise the submodule.

  4. Forcefully checkout!

feature-with-submodule to feature-without-submodule

To return to the original state, checkout to feature-branch-without-submodule, then run the following to remove cached files:

rm -rf .git/modules/<name>

This is so that in the future you can git submodule add a submodule with the same name.

Additionally, if you want the submodule folder to be removed entirely, run:

rm -rf <path>

(Not needed if files already exist in submodule folder.)

Upvotes: 1

Related Questions