How to apply a Git patch to a file with a different name and path?

I have two repositories. In one, I make changes to the ./hello.test file. I commit the changes and create a patch from this commit using git format-patch -1 HEAD . Now I have a second repository containing a file that has the same contents as hello.test but is placed in a different directory under a different name: ./blue/red/hi.test . How can I apply the above patch to the hi.test file? I tried git am --directory='blue/red' < patch_file , but of course complains that the files are not called the same (what I thought Git didn't care?). I know that I could probably edit diff to apply to this particular file, but I'm looking for a team solution.

+45
git filenames patch git-am
May 13 '13 at 15:58
source share
3 answers

You can create a patch using git diff and then apply it with patch , which allows you to specify the file to which you want to apply diff.

For example:

 cd first-repo git diff HEAD^ -- hello.test > ~/patch_file cd ../second-repo patch -p1 blue/red/hi.test ~/patch_file 
+48
May 13 '13 at 16:38
source share

There is a simple solution that does not require manual editing of patches and an external script.

In the first repository (this can also export a commit range, use -1 if you want to select only one commit):

 git format-patch --relative <committish> --stdout > ~/patch 

In the second repository:

 git am --directory blue/red/ ~/patch 

Instead of using --relative in git format-patch another solution is to use the -p<n> option in git am to remove n directories from the patch path, as indicated in answer to a similar question .

You can also run git format-patch --relative <committish> without --stdout , and it will generate a set of .patch files. These files can then be directly transferred to git am using git am --directory blue/red/ path/to/*.patch .

+21
Apr 27 '15 at 6:36
source share

Answering my question with a script that does just that: https://github.com/mprpic/apply-patch-to-file

Instead of manually modifying the patch file, it asks the user for the target file, modifies the patch and applies it to the repo you are currently in.

+7
May 17 '13 at 11:52
source share



All Articles