Search code examples
gitgithubgit-submodules

Can I merge two git submodules


I'm working on a repo with submodules. I have a branch feature1 that was branched off of master branch. On my feature1 branch, I made changes to some files in the submodule. Now the submodule on my feature1 branch and the submodule on my master branch are pointing to two different hashes: feature_submodule -> 6c084... master_submodule -> 7b325...

Some changes were pushed into master from another branch by another dev. So to keep my feature1 branch in sync with master, I merged master into my feature1 branch. But now, my feature_submodule is no longer pointing to 6c084 but it's pointing to 7b3325, and the changes I made to the submodule files are gone.

Is there a way to have the submodules merged so that when I'll push my changes into master branch, I have the changes I made to my submodule locally while keeping the changes that are on the master branch?

Running git pull --recurse-submodules only overwrite my local submodules changes as well.


Solution

  • I wrote this text explaining how Git merge submodules, I hope it helps you: https://lucasoshiro.github.io/posts-en/2022-03-12-merge-submodule/

    I can't exactly figure out what happened with you submodules, but, if you merged master into feature1 locally and it replaced 6c084 by 7b3325, one of the following happened:

    • 7b3325 is a descendant commit of 6c084
    • there was a conflict between master and feature1 on feature_submodule (the commit that the submodule points to was diverging)

    If you keep both the changes introduced by you and the other dev on feature_submodule, then you can do this (adapt it to the contribution workflow of the submodule):

    1. enter the submodule (cd feature_submodule)
    2. git checkout to 6c084
    3. create a new branch point to it (git checkout <new branch>)
    4. push the changes to the submodule remote repository (git push <your remote> <new branch>)
    5. do whatever you do to have that branch merged onto the main branch (e.g. if you using GitHub, open a PR asking to merge the new branch onto the main branch of the submodule repository)
    6. having the changes accepted and merged on the main branch of the submodule, run git fetch to download the newest commits and branches
    7. git checkout your submodule to the main branch
    8. now, back to the parent repo, assuming you are on feature1 branch: git add feature_submodule, so now it will point to the newest changes, then git commit

    Please note that I'm assuming that the commit that feature_submodule is pointing to on the master of the parent repository is already merged on the main branch of the submodule.