RootPhoenix
RootPhoenix

Reputation: 1767

Unable to apply patch with nested directories

I am trying to create simple patch but file is in different directory.

My Directory structure is:

/-|hello_new.c
  |-1/-|
       |-2/-|
            |-3/hello.c

//hello_new.c:
#include <stdio.h>

int main(int argc, char *argv[]) {
        printf("Hello World\n");
}

//hello.c:
#include <stdio.h>

int main()
{
        printf("Hello World\n");
}

I create the patch using:

diff -u 1/2/3/hello.c hello_new.c > hello.patch

My patch file is hello.patch:

--- 1/2/3/hello.c       2016-02-09 13:31:04.904763020 +0530
+++ hello_new.c 2016-02-08 18:35:47.299940190 +0530
@@ -1,6 +1,5 @@
 #include <stdio.h>

-int main()
-{
+int main(int argc, char *argv[]) {
        printf("Hello World\n");
 }

Now I apply patch using:

patch < hello.patch

But I get patching file hello_new.c Reversed patch detected.

Upvotes: 1

Views: 228

Answers (1)

Thomas Dickey
Thomas Dickey

Reputation: 54583

You would solve this using the -p option of patch:

-p number
--strip=number
Set the file name strip count to number. See patch Directories.

If the before/after levels in your patch-file differ, keep in mind that patch gives precedence to the number of levels in the before part (the first line of the header). So you could do

patch -p3 < hello.patch

to avoid the reversed-patch issue for this instance.

This being GNU patch, you can preview the result by adding the --dry-run option (to avoid the nuisance of giving correct responses to the reversed-patch message):

$ patch -p3 --dry-run < hello.patch
patching file hello.c
Hunk #1 succeeded at 2 with fuzz 2 (offset 1 line).

When testing patches, e.g., if they did not match exactly (such as tab/space conversion, carriage-return line-endings), I preview patches, and may add a -l option to help patch make fewer rejects.

Upvotes: 1

Related Questions