How To Move Files To Another Repo | SrishCodes

How To Move Files To Another Repo | SrishCodes

And preserve Git history while doing it

Hi everyone, welcome back to SrishCodes where I teach you interesting tech concepts that you should know about as a current or aspiring software developer. Today I will be sharing with you a quick tutorial on how to move files from one repository to another while preserving Git history.

If you are wondering why you would ever need to do this, let me tell why I am writing this article. Because I have done this twice in the last six months in my software engineering job. I wished each time that there was an article like this I could follow.

Let's get started.

Getting ready to move files from Repository 1

Step 1: Clone repo 1

This is needed because we will be making significant changes to this copy which you do not want to push.

mkdir repo1
cd repo1

git clone <repo 1 clone URL>

To prevent accidentally making changes to your remote repository, remove the link to the remote repository.

cd <repo1 location> // eg cd ~/projects/repo1
git remote rm origin

Step 3: Remove all files that you do not want to keep

This moves all your files and folders in the subdirectory that you have chosen, along with the git history and tags. If you would like to move your entire repo, just remove --subdirectory-filter <DIRECTORY_TO_MOVE>. This step generally takes a while, depending on how large your repository is.

git filter-branch --subdirectory-filter <DIRECTORY_TO_MOVE> --tag-name-filter cat -- --all

Merge files to repo2

Step 1: Clone repo2

mkdir repo2
cd repo2

git clone <repo 2 clone URL>

Step 2: Create a remote connection to repo1 as a branch in repo2

git remote add repoMove <repo 1 directory>
// repoMove is an arbitrary name
// eg. git remote add repoMove ~/projects/repo1

Step 3: Pull files from a branch in repo1 into repo2

git pull repoMove master --allow-unrelated-histories
// This merges master in repo1 into repo2

Step 4: Remove the remote connection to repo1

git remote rm repoMove

Step 5: Push your changes

git push

And your files and history from repo 1 is now in repo 2. Note that there might be more things to complete for configuring your project like Maven, npm, etc.


And that was all for this now! Make sure to follow me and subscribe for the latest posts. Until next time