Git – wpisy w temacie

Move files between git repositories with history

From time to time it may happen usuful to move files in the project from one git repository to the other one. The simplest way to do that is of course deleting it from one repository and adding in the other one. But with such move all history of edits of such files is lost. If the classes are of a bigger size it may be valuable to keep their history. So how to do that?

We need to start with the source repository (where the files are currently) to strip it down from all other files. To do so it is best advised to create a fresh clone, for example in some C:\tmp\old-repo location. And than use git filter-repo command to strip all other files:

git filter-repo \
    --path-regex ".*$" \
    --path-regex ".*$" \
    --path-regex ".*$" \
    --path-regex ".*$" \
    --prune-empty always --force

After that command only needed files (in the example two classes and tests for them) will be kept in the old-repo repository with their history. We can git mv them now to the location which they should have in the target-repo.

Now its time to work with a target-repo. We can add new remote repo here, fetch it and merge allowing unrelated histories:

git remote add sourceRepoName C:\tmp\old-repo
git fetch sourceRepoName
git merge sourceRepoName/main --allow-unrelated-histories