gitfilenamespatchgit-patchgit-am

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 file ./hello.test. I commit the changes and create a patch from that commit with git format-patch -1 HEAD. Now, I have a second repository that contains 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 do I go about applying the aforementioned patch to the hi.test file? I tried git am --directory='blue/red' < patch_file but that of course complains that the files are not named the same (which I thought Git didn't care about?). I know I could probably edit the diff to apply to that specific file but I'm looking for a command solution.


Solution

  • You could create the patch using git diff and then apply it using the patch utility, which allows you to specify the file you want to apply the diff to.

    For example:

    cd first-repo
    git diff HEAD^ -- hello.test > ~/patch_file
    
    cd ../second-repo
    patch -p1 blue/red/hi.test ~/patch_file