Home > Software design >  How to tell `git diff` to make a diff usable with `patch -p0`?
How to tell `git diff` to make a diff usable with `patch -p0`?

Time:02-15

I have a file in a git repo. I checked it out from branch release, edited it to fix a problem, and checked it in to a new branch bugfix. I now want to make a diff file which captures this edit. I want to apply this diff file, using patch -p0, to a separate copy of the release branch, which is outside of git control. After the patch, I want the file to match what I have in branch bugfix.

I tried using the command git diff release bugfix -- myfile.m4. It gave me a .diff file which begins,

index 17641f7482..2b31725fae 100644
--- a/myfile.m4
    b/myfile.m4
[… rest of diff elided …]

When I apply this diff to my separate repo using patch -p0, it fails. Patch is unable to find paths a/myfile.m4 and b/myfile.m4, because of course they don't exist. There are no directories a and b in my source. Note, if I could use patch -p1, then the diff would work as a patch. But, because of tooling constraints, I am not easily able to use patch -p1.

I would like the .diff file to leave out the a/ and b/ prefixes. I would like the diff file to read something like:

index 87641f7482..2821725fae 100644
--- myfile.m4
    myfile.m4
[… rest of diff elided …]

Is there a way to make git diff produce a diff without those non-existent path prefixes?

There is a workaround: checkout the file from the release branch, rename it myfile.m4.orig, then checkout the modified file from the bugfix branch, then do diff -u myfile.m4.orig myfile.m4. This gives me a diff which I can use with patch -p0. But I want to avoid making a separate file with a contrived file name.

CodePudding user response:

You can use --dst-prefix= and --src-prefix= to specify the destination and source prefixes, I guess that you might be able to set them to an empty string:

$ git diff --src-prefix= --dst-prefix= release bugfix -- myfile.m4

As pointed out in the comments, you can also use --no-prefix:

$ git diff --no-prefix release bugfix -- myfile.m4
  • Related