apply: update line lengths for --inaccurate-eof

Some diff implementations don't report missing newlines at the end of files. Applying such a patch can cause a newline character to be added inadvertently. The option --inaccurate-eof of git apply can be used to remove trailing newlines if needed. apply_one_fragment() cuts it off from the buffers for preimage and postimage. Before it does, it builds an array with the lengths of each line for both. Make sure to update the length of the last line in these line info structures as well to keep them consistent with their respective buffer. Without this fix the added test fails; git apply dies and reports: fatal: BUG: caller miscounted postlen: asked 1, orig = 1, used = 2 That sanity check is only called if whitespace changes are ignored. Reported-by: Mahmoud Al-Qudsi <mqudsi@neosmart.net> Signed-off-by: Rene Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed Nov 16, 2017 at 19:50 UTC 4855de123391daab82407b44de03ba5647e97694
2 files changed +16
apply.c
+2
@@ -2941,6 +2941,8 @@ static int apply_one_fragment(struct apply_state *state,
2941 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2942 old--;
2943 strbuf_setlen(&newlines, newlines.len - 1);
2944 + preimage.line_allocated[preimage.nr - 1].len--;
2945 + postimage.line_allocated[postimage.nr - 1].len--;
2946 }
2947
2948 leading = frag->leading;
t/t4107-apply-ignore-whitespace.sh
+14
@@ -178,4 +178,18 @@ test_expect_success 'patch5 fails (--no-ignore-whitespace)' '
178 test_must_fail git apply --no-ignore-whitespace patch5.patch
179 '
180
181 +test_expect_success 'apply --ignore-space-change --inaccurate-eof' '
182 + echo 1 >file &&
183 + git apply --ignore-space-change --inaccurate-eof <<-\EOF &&
184 + diff --git a/file b/file
185 + --- a/file
186 + +++ b/file
187 + @@ -1 +1 @@
188 + -1
189 + +2
190 + EOF
191 + printf 2 >expect &&
192 + test_cmp expect file
193 +'
194 +
195 test_done