Incorporate one git repository into another with preserving history

March 15, 2025 · 184 words · One minute

This is an operation that I’m doing too often lately, so wanna record the commands to do that.

  1. Usually I’d migrate from submodule, and it could be done inside one, but it’s safer to clone the repo separately
git clone sub-module
  1. Rewrite the paths inside submodule, so they can be safely included into the main repo
cd sub-module
git filter-repo --to-subdirectory "sub-module-path-in-main-repo" --force
  1. Switch to main-repository
# git clone main-repo
cd main-repo
  1. Remove submodule, so that we can re-use the same path
git rm path/to/submodule
git c -m "Remove submodule"
  1. Incorporate the edited history
git remote add sub-origin path/to/submodule/checkout
git checkout sub-origin/<submodule-branch> <new-branch-in-main>
  1. Now that we have all pieces ready, we can incorporate the data in two ways

    1. Merge the history, pretend it all happened in the main repo
    # Given that we're on <new-branch-in-main>
    git rebase <main-branch>
    git checkout <main-branch>
    git rebase <new-branch-in-main>
    git push
    
    1. To have a separate merge commit in the main repo
    git checkout <main-branch>
    git merge --allow-unrelated-histories <new-branch-in-main>
    
  2. We’re done, cleanup?

git remote rm sub-origin
git branch -D <new-branch-in-main>
rm -rf path/to/submodule-checkout

Enjoy and don’t forget to push :)