Move directory between repos while preserving git history


Tue May 10 2022 10:13:05 GMT+0000 (UTC)

Saved by @Rohith #bash

# in source repo

git checkout -b <new branch> <source branch>

git filter-branch --subdirectory-filter <sub-directory path> -- -- all

git remote add <remote name> <remote URL>
git fetch <remote name>
git push <-U> <new remote> <new branch>
# or merge unrelated history and then push

git merge <new remote> --allow-unrelated-histories

Snippet explains pushing to new repo from an already existing repo, can be improved by creating new repo locally, cloning old repo into it, filter-branch on the source branch (mostly master), add a new remote, fetch, merge unrelated history if any and push to new repo.