1

Merging one file from one branch to another has been asked before with the rather concise solution to do:

git checkout A
git checkout --patch B f

But how does one do this effectively across two repositories?

Community
  • 1
  • 1
cfi
  • 10,915
  • 8
  • 57
  • 103
  • Push or fetch the commits. – jthill Sep 08 '15 at 15:36
  • @jthill: It's not that easy: You could cherrypick the individual commits, but if one of those affects more than the file of interest, you import/merge unwanted changes. The fetch alone imports the full history of one branch of the remote/source repository. If the two repos are unrelated with unrelated files and unrelated history, then this is a huge disk space overhead which you have to cleanup afterwards. – cfi Sep 09 '15 at 06:16

1 Answers1

1

There is a simple solution, too and it involves patching. git can handles patches sent in by email very well. That is one of the important initial use cases by Linus Torvalds. So we first generate such a patchfile in the source repo, then consume it in the destination:

cd source_repository/
git log --reverse --follow -p --format=email   filename  > patch

cd other_repository/
git am --whitespace=nowarn source_repository/patch

rm source_repository/patch

Some explanation:

  • git am stands for “git apply mailbox file” and is used to integrate patches that someone sends by email
  • git log –p can create such a patch file with option --format=email
  • The --follow is used to keep track of the full history of the file even if it got renamed. --follow prevents git log from accepting multiple file names. But it is an important switch and that is why I recommend to use this method in a loop for multiple files.
  • The --reverse is required because git am requires the commits to be in chronological order with git log by default does not output.
  • By default git am warns about lines with trailing whitespaces. --whitespace=nowarn suppresses those warnings. You might want to not use this and clean you whitespaces, but that's a matter of style guidelines
cfi
  • 10,915
  • 8
  • 57
  • 103