Skip to content

Commit a1c0dca

Browse files
committed
Merge branch 'jc/maint-apply-match-beginning'
* jc/maint-apply-match-beginning: Fix "git apply" to correctly enforce "match at the beginning"
2 parents aba201c + ee5a317 commit a1c0dca

File tree

2 files changed

+29
-13
lines changed

2 files changed

+29
-13
lines changed

builtin-apply.c

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1937,21 +1937,24 @@ static int apply_one_fragment(struct image *img, struct fragment *frag,
19371937
trailing = frag->trailing;
19381938

19391939
/*
1940-
* If we don't have any leading/trailing data in the patch,
1941-
* we want it to match at the beginning/end of the file.
1940+
* A hunk to change lines at the beginning would begin with
1941+
* @@ -1,L +N,M @@
19421942
*
1943-
* But that would break if the patch is generated with
1944-
* --unified=0; sane people wouldn't do that to cause us
1945-
* trouble, but we try to please not so sane ones as well.
1943+
* And a hunk to add to an empty file would begin with
1944+
* @@ -0,0 +N,M @@
1945+
*
1946+
* In other words, a hunk that is (frag->oldpos <= 1) with or
1947+
* without leading context must match at the beginning.
19461948
*/
1947-
if (unidiff_zero) {
1948-
match_beginning = (!leading && !frag->oldpos);
1949-
match_end = 0;
1950-
}
1951-
else {
1952-
match_beginning = !leading && (frag->oldpos == 1);
1953-
match_end = !trailing;
1954-
}
1949+
match_beginning = frag->oldpos <= 1;
1950+
1951+
/*
1952+
* A hunk without trailing lines must match at the end.
1953+
* However, we simply cannot tell if a hunk must match end
1954+
* from the lack of trailing lines if the patch was generated
1955+
* with unidiff without any context.
1956+
*/
1957+
match_end = !unidiff_zero && !trailing;
19551958

19561959
pos = frag->newpos ? (frag->newpos - 1) : 0;
19571960
preimage.buf = oldlines;

t/t4104-apply-boundary.sh

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,17 @@ do
112112
'
113113
done
114114

115+
test_expect_success 'two lines' '
116+
117+
>file &&
118+
git add file &&
119+
echo aaa >file &&
120+
git diff >patch &&
121+
git add file &&
122+
echo bbb >file &&
123+
git add file &&
124+
test_must_fail git apply --check patch
125+
126+
'
127+
115128
test_done

0 commit comments

Comments
 (0)