Adding and removing submodule from git branch

I am constantly coming back and forwards with this – my current project requires to work with submodules, which i think is a great idea when you work in distributed devops environment and you want to have better control over the infrastructure-as-code configuration. It is just a quite complex process to commit submodules to the main stream.

Most of the time I am getting into merging issues every time i do the update. Therefore for my own benefit and hopefully others in the future, I decided to list steps I follow to remove and add the submodule in a simple way:

1. Create feature branch from develop branch of the main repository that holds submodule reference.

Note: work only on feature branch till you 100% you have all latest submodule SHA in place.

2. Clone your feature branch without recursive flag, i.e

git clone  -b feature/myNewUpdate git@<IP of the branch>:<repo groupID>/<repo_name>.git

(you will have to have all git config set beforehand with ssh keys etc.)

This will download the branch but will not load any submodule files with it with is what we are looking for.

3. Remove the submodule:

  • Delete submodule definition from the .gitmodules file.
  • Add changes by executing: git add .gitmodules
  • Delete section from .git/config.
  • Execute git rm --cached <submodule directory> (no trailing slash).
  • Run rm -Rf .git/modules/<submodule directory>
  • Commit changes git commit -m "Removed submodule <name>"
  • Delete any leftovers files
    rm -rf <submodule directory>
  • push changes if this is only what you intended to do – if you want to add submodule in the same go follow steps below:
  • git submodule add git@<IP>:<repo> <new submodule directory>
  • git submodule update –init <new submodule directory>
  • git submodule update –remote –merge  <new submodule directory>
  • git add  <new submodule directory>
  • git commit  <new submodule directory>
  • git push

This above should remove and add new submodule reference to your feature branch. Test it all works by going to the repository and navigate to your submodule and see if all the latest changes match – this will also reflect in updated @SHA next to submodule directory.

The last steps is to request the merge to main branch once all is tested in your feature branch.

Good luck!

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>