Skip to content

Commit a10a6fe

Browse files
committed
built-in add -p: coalesce hunks after splitting them
This is considered "the right thing to do", according to 933e44d ("add -p": work-around an old laziness that does not coalesce hunks, 2011-04-06). Note: we cannot simply modify the hunks while merging them; Once we implement hunk editing, we will call `reassemble_patch()` whenever a hunk is edited, therefore we must not modify the hunks (because the user might e.g. hit `K` and change their mind whether to stage the previous hunk). Signed-off-by: Johannes Schindelin <[email protected]>
1 parent b767aa7 commit a10a6fe

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

add-patch.c

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,48 @@ static void render_diff_header(struct add_p_state *s,
396396
}
397397
}
398398

399+
/* Coalesce hunks again that were split */
400+
static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
401+
size_t *hunk_index, struct hunk *temp)
402+
{
403+
size_t i = *hunk_index;
404+
struct hunk *hunk = file_diff->hunk + i;
405+
struct hunk_header *header = &temp->header, *next;
406+
407+
if (hunk->use != USE_HUNK)
408+
return 0;
409+
410+
memcpy(temp, hunk, sizeof(*temp));
411+
/* We simply skip the colored part (if any) when merging hunks */
412+
temp->colored_start = temp->colored_end = 0;
413+
414+
for (; i + 1 < file_diff->hunk_nr; i++) {
415+
hunk++;
416+
next = &hunk->header;
417+
418+
if (hunk->use != USE_HUNK ||
419+
header->new_offset >= next->new_offset ||
420+
header->new_offset + header->new_count < next->new_offset ||
421+
temp->start >= hunk->start ||
422+
temp->end < hunk->start)
423+
break;
424+
425+
temp->end = hunk->end;
426+
temp->colored_end = hunk->colored_end;
427+
428+
header->old_count = next->old_offset + next->old_count
429+
- header->old_offset;
430+
header->new_count = next->new_offset + next->new_count
431+
- header->new_offset;
432+
}
433+
434+
if (i == *hunk_index)
435+
return 0;
436+
437+
*hunk_index = i;
438+
return 1;
439+
}
440+
399441
static void reassemble_patch(struct add_p_state *s,
400442
struct file_diff *file_diff, struct strbuf *out)
401443
{
@@ -406,12 +448,19 @@ static void reassemble_patch(struct add_p_state *s,
406448
render_diff_header(s, file_diff, 0, out);
407449

408450
for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
451+
struct hunk temp = { 0 };
452+
409453
hunk = file_diff->hunk + i;
410454
if (hunk->use != USE_HUNK)
411455
delta += hunk->header.old_count
412456
- hunk->header.new_count;
413-
else
457+
else {
458+
/* merge overlapping hunks into a temporary hunk */
459+
if (merge_hunks(s, file_diff, &i, &temp))
460+
hunk = &temp;
461+
414462
render_hunk(s, hunk, delta, 0, out);
463+
}
415464
}
416465
}
417466

0 commit comments

Comments
 (0)