add-patch: update hunk splitability after editing
If, when the user edits a hunk, they change deletion lines into context lines or vice versa, then the number of hunks that the edited hunk can be split into may differ from the unedited hunk. This means that so we should recalculate `hunk->splittable_into` after the hunk has been edited. In practice users are unlikely to hit this bug as it is doubtful that a user who has edited a hunk will split it afterwards. Signed-off-by: Phillip Wood <phillip.wood@dunelm.org.uk> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Phillip Wood committed
Sep 25, 2025 at 15:10 UTC
732650e263eb6bceda9988a8bbe75f311d908897
2 files changed
+32
-1
add-patch.c
+11
-1
@@ -1185,19 +1185,29 @@ static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1185
{
1186
struct hunk_header *header = &hunk->header;
1187
size_t i;
1188
+ char ch, marker = ' ';
1189
1190
+ hunk->splittable_into = 0;
1191
header->old_count = header->new_count = 0;
1192
for (i = hunk->start; i < hunk->end; ) {
1191
- switch(normalize_marker(&s->plain.buf[i])) {
1193
+ ch = normalize_marker(&s->plain.buf[i]);
1194
+ switch (ch) {
1195
case '-':
1196
header->old_count++;
1197
+ if (marker == ' ')
1198
+ hunk->splittable_into++;
1199
+ marker = ch;
1200
break;
1201
case '+':
1202
header->new_count++;
1203
+ if (marker == ' ')
1204
+ hunk->splittable_into++;
1205
+ marker = ch;
1206
break;
1207
case ' ':
1208
header->old_count++;
1209
header->new_count++;
1210
+ marker = ch;
1211
break;
1212
}
1213
t/t3701-add-interactive.sh
+21
@@ -1311,4 +1311,25 @@ test_expect_success 'splitting previous hunk marks split hunks as undecided' '
1311
test_cmp expect actual
1312
'
1313
1314
+test_expect_success 'splitting edited hunk' '
1315
+ # Before the first hunk is edited it can be split into two
1316
+ # hunks, after editing it can be split into three hunks.
1317
+
1318
+ write_script fake-editor.sh <<-\EOF &&
1319
+ sed "s/^ c/-c/" "$1" >"$1.tmp" &&
1320
+ mv "$1.tmp" "$1"
1321
+ EOF
1322
+
1323
+ test_write_lines a b c d e f g h i j k l m n >file &&
1324
+ git add file &&
1325
+ test_write_lines A b c d E f g h i j k l M n >file &&
1326
+ (
1327
+ test_set_editor "$(pwd)/fake-editor.sh" &&
1328
+ test_write_lines e K s j y n y q | git add -p file
1329
+ ) &&
1330
+ git cat-file blob :file >actual &&
1331
+ test_write_lines a b d e f g h i j k l M n >expect &&
1332
+ test_cmp expect actual
1333
+'
1334
+
1335
test_done