I had a situation where I had a git repo. consisting of a Java project and a C# project (a small monorepo), we decided that permissions for each project needed to differ (i.e. the admin of those projects) and maybe more importantly in a way, changes to one were causing “Pending” changes to the other within CI/CD, in this case TeamCity.
So we need to split the project. Ofcourse it’s easy to create a new project and copy the code, but we wanted to keep the commit history etc.
What I’m going to list below are the steps that worked for me, but I owe a lot to this post Move files from one repository to another, preserving git history.
Use case
To reiterate, we have a Java library and C# library sitting in the same git code base and we want to move the C# library into it’s own repository whilst keeping the commit history.
Steps
- Clone the repository (i.e. the code we’re wanting to move)
- CD into it
- From a command line, run
git remote rm origin
This will remove the remote url and means we’re not going to accidently commit to the original/source repository.
- Now we want to filter our anything that’s not part of the code we want to keep. It’s hoped that the C# code, like ours, was in it’s own folder (otherwise things will be much more complicated). So run
git filter-branch --subdirectory-filter <directory> -- --all
Replace
with the relative folder, i.e. subfolder1/subfolder2/FOLDER_TO_KEEP -
Run the following commands
git reset --hard git gc --aggressive git prune git clean -fd
- Now, if you haven’t already create a remote repository, do so and then run
git remote add origin <YOUR REMOTE REPO>
-
git push -u origin --all git push origin --tags
// this should have been handled by step 6 git remote set-url origin https://youreposerver/yourepo.git