add -p: fix counting empty context lines in edited patches

recount_edited_hunk() introduced in commit 2b8ea7f3c7 ("add -p: calculate offset delta for edited patches", 2018-03-05) required all context lines to start with a space, empty lines are not counted. This was intended to avoid any recounting problems if the user had introduced empty lines at the end when editing the patch. However this introduced a regression into 'git add -p' as it seems it is common for editors to strip the trailing whitespace from empty context lines when patches are edited thereby introducing empty lines that should be counted. 'git apply' knows how to deal with such empty lines and POSIX states that whether or not there is an space on an empty context line is implementation defined [1]. Fix the regression by counting lines that consist solely of a newline as well as lines starting with a space as context lines and add a test to prevent future regressions. [1] http://pubs.opengroup.org/onlinepubs/9699919799/utilities/diff.html Reported-by: Mahmoud Al-Qudsi <mqudsi@neosmart.net> Reported-by: Oliver Joseph Ash <oliverjash@gmail.com> Reported-by: Jeff Felchner <jfelchner1@gmail.com> Signed-off-by: Phillip Wood <phillip.wood@dunelm.org.uk> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Phillip Wood committed Jun 11, 2018 at 10:46 UTC f4d35a6b49621348c73222e7017a434551799308
2 files changed +44 -1
git-add--interactive.perl
+1 -1
@@ -1047,7 +1047,7 @@ sub recount_edited_hunk {
1047 $o_cnt++;
1048 } elsif ($mode eq '+') {
1049 $n_cnt++;
1050 - } elsif ($mode eq ' ') {
1050 + } elsif ($mode eq ' ' or $mode eq "\n") {
1051 $o_cnt++;
1052 $n_cnt++;
1053 }
t/t3701-add-interactive.sh
+43
@@ -175,6 +175,49 @@ test_expect_success 'real edit works' '
175 diff_cmp expected output
176 '
177
178 +test_expect_success 'setup file' '
179 + test_write_lines a "" b "" c >file &&
180 + git add file &&
181 + test_write_lines a "" d "" c >file
182 +'
183 +
184 +test_expect_success 'setup patch' '
185 + SP=" " &&
186 + NULL="" &&
187 + cat >patch <<-EOF
188 + @@ -1,4 +1,4 @@
189 + a
190 + $NULL
191 + -b
192 + +f
193 + $SP
194 + c
195 + EOF
196 +'
197 +
198 +test_expect_success 'setup expected' '
199 + cat >expected <<-EOF
200 + diff --git a/file b/file
201 + index b5dd6c9..f910ae9 100644
202 + --- a/file
203 + +++ b/file
204 + @@ -1,5 +1,5 @@
205 + a
206 + $SP
207 + -f
208 + +d
209 + $SP
210 + c
211 + EOF
212 +'
213 +
214 +test_expect_success 'edit can strip spaces from empty context lines' '
215 + test_write_lines e n q | git add -p 2>error &&
216 + test_must_be_empty error &&
217 + git diff >output &&
218 + diff_cmp expected output
219 +'
220 +
221 test_expect_success 'skip files similarly as commit -a' '
222 git reset &&
223 echo file >.gitignore &&