Copy commits from one git repo to another

If you have done some work in one (or more) repos, that you want to transfer into a different target repo, you can of course simply copy you work to the new repo. But what if you also would like to copy the commit history?

This can be done by using git format-patch plus git am.

We’ll assume that we have two different repos; labrepo and goodrepo.

somewhere $ cd ~/repos/labrepo
labrepo $ git format-patch --root
labrepo $ cd ../goodrepo
goodrepo $ mkdir lab
goodrepo $ git am --directory=lab --whitespace=nowarn ../labrepo/*.patch
Applying: Initial TestDataProvider
Applying: One assert per test
Applying: Allow adding schedule for multiple days

This series of commands would transfer all your commits from labrepo into the subfolder “lab” in the goodrepo. And you’ll be able to move several other repos into the goodrepo this way, without conflicts. Remember that the new commits are just copies, and will have different commit-ids than the corresponding labrepo commits.

git format-patch can of course extract just a subset of the history, such as if work continues in the labrepo, you can create patches just for those commits, and run a new git am on those patches to import them.

somewhere $ cd ~/repos/labrepo
labrepo $ git format-patch -v2 commitid-of-last-transferred-commit
labrepo $ cd ../goodrepo
goodrepo $ git am --directory=lab --whitespace=nowarn ../labrepo/v2-*.patch
Applying: Never schedule Sundays
Applying: Increase test coverage

The -v2 argument to git format-patch gives the resulting files a prefix, so you know which patch files belong together (or, just remove old .patch-files before exporting new ones)

Leave a Reply

Close Menu