Skip to content

Commit ec7fc0b

Browse files
committed
builtin-apply.c: pay attention to -p<n> when determining the name
The patch structure has def_name component that is used to validate the sanity of a "diff --git" patch by checking pathnames that appear on the patch header lines for consistency. The git_header_name() function is used to compute this out of "diff --git a/... b/..." line, but the code always stripped one level of prefix (i.e. "a/" and "b/"), without paying attention to -p<n> option. Code in find_name() function that parses other lines in the patch header (e.g. "--- a/..." and "+++ b/..." lines) however did strip the correct number of leading paths prefixes, and the sanity check between these computed values failed. Teach git_header_name() to honor -p<n> option like find_name() function does. Found and reported by Steven J. Murdoch who also wrote tests. Signed-off-by: Junio C Hamano <[email protected]>
1 parent 4f36627 commit ec7fc0b

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

builtin-apply.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -823,12 +823,13 @@ static int gitdiff_unrecognized(const char *line, struct patch *patch)
823823

824824
static const char *stop_at_slash(const char *line, int llen)
825825
{
826+
int nslash = p_value;
826827
int i;
827828

828829
for (i = 0; i < llen; i++) {
829830
int ch = line[i];
830-
if (ch == '/')
831-
return line + i;
831+
if (ch == '/' && --nslash <= 0)
832+
return &line[i];
832833
}
833834
return NULL;
834835
}

t/t4128-apply-root.sh

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,23 @@ test_expect_success 'apply --directory (new file)' '
5757
test content = $(cat some/sub/dir/newfile)
5858
'
5959

60+
cat > patch << EOF
61+
diff --git a/c/newfile2 b/c/newfile2
62+
new file mode 100644
63+
index 0000000..d95f3ad
64+
--- /dev/null
65+
+++ b/c/newfile2
66+
@@ -0,0 +1 @@
67+
+content
68+
EOF
69+
70+
test_expect_success 'apply --directory -p (new file)' '
71+
git reset --hard initial &&
72+
git apply -p2 --directory=some/sub/dir/ --index patch &&
73+
test content = $(git show :some/sub/dir/newfile2) &&
74+
test content = $(cat some/sub/dir/newfile2)
75+
'
76+
6077
cat > patch << EOF
6178
diff --git a/delfile b/delfile
6279
deleted file mode 100644

0 commit comments

Comments
 (0)