DEV Community

Cover image for How to cherry-pick from separate repos with separate paths (with history)
Cristian-Florin Calina for This is Learning

Posted on

How to cherry-pick from separate repos with separate paths (with history)

If you ever wanted to extract parts of code from one repository to another one, but you also wanted to keep the history of commits for those parts, there is a way.

You can use

git log --pretty=email --patch-with-stat --reverse --full-index --binary -- <file_path | folder_path> > ~/toggle.patch

Explained:
--pretty=email formats the output to show the hash, the date, the author, author date and subject + the commit message.

--patch-with-stat generates a diffstat for the file/folder

--reverse outputs the commits in reverse order (so that they can be applied in the correct order in the other repository).

--full-index this shows the full index of the commit when outputing the diffs (instead of showing just the first characters).

--binary outputs the diff in binary so that git-apply can use it.


This will generate a patch file with the differences that were done on the file or folder that you pass to it (and will keep commits history as well).

After that, you must mass edit the generated toggle.patch file by changing the paths in diffs to match the new paths in the new repo.

After you changed the patch, you can apply it in your new repo by using

git am --committer-date-is-author-date < ~/toggle.patch.

Explained:
--commiter-date-is-author-date allows the user to lie about the committer date by using the same value as the author date.


This way, you keep all of the history for this extracted file/folder (and you keep the dates as well when looking over the file history).

Hope this helps.

Top comments (0)