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.
- 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
- 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
- Switch to main-repository
# git clone main-repo
cd main-repo
- Remove submodule, so that we can re-use the same path
git rm path/to/submodule
git c -m "Remove submodule"
- Incorporate the edited history
git remote add sub-origin path/to/submodule/checkout
git checkout sub-origin/<submodule-branch> <new-branch-in-main>
-
Now that we have all pieces ready, we can incorporate the data in two ways
- 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
- To have a separate merge commit in the main repo
git checkout <main-branch> git merge --allow-unrelated-histories <new-branch-in-main>
-
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 :)