2 #include "add-interactive.h"
4 #include "run-command.h"
5 #include "argv-array.h"
10 enum prompt_mode_type {
11 PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_HUNK,
12 PROMPT_MODE_MAX, /* must be last */
17 * The magic constant 4 is chosen such that all patch modes
18 * provide enough space for three command-line arguments followed by a
21 const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
22 unsigned is_reverse:1, apply_for_checkout:1;
23 const char *prompt_mode[PROMPT_MODE_MAX];
24 const char *edit_hunk_hint, *help_patch_text;
27 static struct patch_mode patch_mode_add = {
28 .diff_cmd = { "diff-files", NULL },
29 .apply_args = { "--cached", NULL },
30 .apply_check_args = { "--cached", NULL },
32 N_("Stage mode change [y,n,q,a,d%s,?]? "),
33 N_("Stage deletion [y,n,q,a,d%s,?]? "),
34 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
36 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
37 "will immediately be marked for staging."),
39 N_("y - stage this hunk\n"
40 "n - do not stage this hunk\n"
41 "q - quit; do not stage this hunk or any of the remaining "
43 "a - stage this hunk and all later hunks in the file\n"
44 "d - do not stage this hunk or any of the later hunks in "
49 unsigned long old_offset, old_count, new_offset, new_count;
51 * Start/end offsets to the extra text after the second `@@` in the
52 * hunk header, e.g. the function signature. This is expected to
53 * include the newline.
55 size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
59 size_t start, end, colored_start, colored_end, splittable_into;
61 enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
62 struct hunk_header header;
67 struct strbuf answer, buf;
70 struct strbuf plain, colored;
74 size_t hunk_nr, hunk_alloc;
75 unsigned deleted:1, mode_change:1,binary:1;
80 struct patch_mode *mode;
84 static void err(struct add_p_state *s, const char *fmt, ...)
89 fputs(s->s.error_color, stderr);
90 vfprintf(stderr, fmt, args);
91 fputs(s->s.reset_color, stderr);
96 static void setup_child_process(struct add_p_state *s,
97 struct child_process *cp, ...)
103 while ((arg = va_arg(ap, const char *)))
104 argv_array_push(&cp->args, arg);
108 argv_array_pushf(&cp->env_array,
109 INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
112 static int parse_range(const char **p,
113 unsigned long *offset, unsigned long *count)
117 *offset = strtoul(*p, &pend, 10);
125 *count = strtoul(pend + 1, (char **)p, 10);
126 return *p == pend + 1 ? -1 : 0;
129 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
131 struct hunk_header *header = &hunk->header;
132 const char *line = s->plain.buf + hunk->start, *p = line;
133 char *eol = memchr(p, '\n', s->plain.len - hunk->start);
136 eol = s->plain.buf + s->plain.len;
138 if (!skip_prefix(p, "@@ -", &p) ||
139 parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
140 !skip_prefix(p, " +", &p) ||
141 parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
142 !skip_prefix(p, " @@", &p))
143 return error(_("could not parse hunk header '%.*s'"),
144 (int)(eol - line), line);
146 hunk->start = eol - s->plain.buf + (*eol == '\n');
147 header->extra_start = p - s->plain.buf;
148 header->extra_end = hunk->start;
150 if (!s->colored.len) {
151 header->colored_extra_start = header->colored_extra_end = 0;
155 /* Now find the extra text in the colored diff */
156 line = s->colored.buf + hunk->colored_start;
157 eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
159 eol = s->colored.buf + s->colored.len;
160 p = memmem(line, eol - line, "@@ -", 4);
162 return error(_("could not parse colored hunk header '%.*s'"),
163 (int)(eol - line), line);
164 p = memmem(p + 4, eol - p - 4, " @@", 3);
166 return error(_("could not parse colored hunk header '%.*s'"),
167 (int)(eol - line), line);
168 hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
169 header->colored_extra_start = p + 3 - s->colored.buf;
170 header->colored_extra_end = hunk->colored_start;
175 static int is_octal(const char *p, size_t len)
181 if (*p < '0' || *(p++) > '7')
186 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
188 struct argv_array args = ARGV_ARRAY_INIT;
189 struct strbuf *plain = &s->plain, *colored = NULL;
190 struct child_process cp = CHILD_PROCESS_INIT;
191 char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
192 size_t file_diff_alloc = 0, i, color_arg_index;
193 struct file_diff *file_diff = NULL;
194 struct hunk *hunk = NULL;
197 argv_array_pushv(&args, s->mode->diff_cmd);
199 struct object_id oid;
200 argv_array_push(&args,
201 /* could be on an unborn branch */
202 !strcmp("HEAD", s->revision) &&
203 get_oid("HEAD", &oid) ?
204 empty_tree_oid_hex() : s->revision);
206 color_arg_index = args.argc;
207 /* Use `--no-color` explicitly, just in case `diff.color = always`. */
208 argv_array_pushl(&args, "--no-color", "-p", "--", NULL);
209 for (i = 0; i < ps->nr; i++)
210 argv_array_push(&args, ps->items[i].original);
212 setup_child_process(s, &cp, NULL);
214 res = capture_command(&cp, plain, 0);
216 argv_array_clear(&args);
217 return error(_("could not parse diff"));
220 argv_array_clear(&args);
223 strbuf_complete_line(plain);
225 if (want_color_fd(1, -1)) {
226 struct child_process colored_cp = CHILD_PROCESS_INIT;
228 setup_child_process(s, &colored_cp, NULL);
229 xsnprintf((char *)args.argv[color_arg_index], 8, "--color");
230 colored_cp.argv = args.argv;
231 colored = &s->colored;
232 res = capture_command(&colored_cp, colored, 0);
233 argv_array_clear(&args);
235 return error(_("could not parse colored diff"));
236 strbuf_complete_line(colored);
237 colored_p = colored->buf;
238 colored_pend = colored_p + colored->len;
240 argv_array_clear(&args);
242 /* parse files and hunks */
244 pend = p + plain->len;
246 char *eol = memchr(p, '\n', pend - p);
247 const char *deleted = NULL, *mode_change = NULL;
252 if (starts_with(p, "diff ")) {
254 ALLOC_GROW(s->file_diff, s->file_diff_nr,
256 file_diff = s->file_diff + s->file_diff_nr - 1;
257 memset(file_diff, 0, sizeof(*file_diff));
258 hunk = &file_diff->head;
259 hunk->start = p - plain->buf;
261 hunk->colored_start = colored_p - colored->buf;
263 } else if (p == plain->buf)
264 BUG("diff starts with unexpected line:\n"
265 "%.*s\n", (int)(eol - p), p);
266 else if (file_diff->deleted)
267 ; /* keep the rest of the file in a single "hunk" */
268 else if (starts_with(p, "@@ ") ||
269 (hunk == &file_diff->head &&
270 skip_prefix(p, "deleted file", &deleted))) {
271 if (marker == '-' || marker == '+')
273 * Should not happen; previous hunk did not end
274 * in a context line? Handle it anyway.
276 hunk->splittable_into++;
278 file_diff->hunk_nr++;
279 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
280 file_diff->hunk_alloc);
281 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
282 memset(hunk, 0, sizeof(*hunk));
284 hunk->start = p - plain->buf;
286 hunk->colored_start = colored_p - colored->buf;
289 file_diff->deleted = 1;
290 else if (parse_hunk_header(s, hunk) < 0)
294 * Start counting into how many hunks this one can be
298 } else if (hunk == &file_diff->head &&
299 skip_prefix(p, "old mode ", &mode_change) &&
300 is_octal(mode_change, eol - mode_change)) {
301 if (file_diff->mode_change)
302 BUG("double mode change?\n\n%.*s",
303 (int)(eol - plain->buf), plain->buf);
304 if (file_diff->hunk_nr++)
305 BUG("mode change in the middle?\n\n%.*s",
306 (int)(eol - plain->buf), plain->buf);
309 * Do *not* change `hunk`: the mode change pseudo-hunk
310 * is _part of_ the header "hunk".
312 file_diff->mode_change = 1;
313 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
314 file_diff->hunk_alloc);
315 memset(file_diff->hunk, 0, sizeof(struct hunk));
316 file_diff->hunk->start = p - plain->buf;
318 file_diff->hunk->colored_start =
319 colored_p - colored->buf;
320 } else if (hunk == &file_diff->head &&
321 skip_prefix(p, "new mode ", &mode_change) &&
322 is_octal(mode_change, eol - mode_change)) {
325 * Extend the "mode change" pseudo-hunk to include also
326 * the "new mode" line.
328 if (!file_diff->mode_change)
329 BUG("'new mode' without 'old mode'?\n\n%.*s",
330 (int)(eol - plain->buf), plain->buf);
331 if (file_diff->hunk_nr != 1)
332 BUG("mode change in the middle?\n\n%.*s",
333 (int)(eol - plain->buf), plain->buf);
334 if (p - plain->buf != file_diff->hunk->end)
335 BUG("'new mode' does not immediately follow "
336 "'old mode'?\n\n%.*s",
337 (int)(eol - plain->buf), plain->buf);
338 } else if (hunk == &file_diff->head &&
339 starts_with(p, "Binary files "))
340 file_diff->binary = 1;
342 if (file_diff->deleted && file_diff->mode_change)
343 BUG("diff contains delete *and* a mode change?!?\n%.*s",
344 (int)(eol - (plain->buf + file_diff->head.start)),
345 plain->buf + file_diff->head.start);
347 if ((marker == '-' || marker == '+') && *p == ' ')
348 hunk->splittable_into++;
349 if (marker && *p != '\\')
352 p = eol == pend ? pend : eol + 1;
353 hunk->end = p - plain->buf;
356 char *colored_eol = memchr(colored_p, '\n',
357 colored_pend - colored_p);
359 colored_p = colored_eol + 1;
361 colored_p = colored_pend;
363 hunk->colored_end = colored_p - colored->buf;
367 if (file_diff->hunk_nr != 1)
368 BUG("mode change in hunk #%d???",
369 (int)file_diff->hunk_nr);
370 /* Adjust the end of the "mode change" pseudo-hunk */
371 file_diff->hunk->end = hunk->end;
373 file_diff->hunk->colored_end = hunk->colored_end;
377 if (marker == '-' || marker == '+')
379 * Last hunk ended in non-context line (i.e. it appended lines
380 * to the file, so there are no trailing context lines).
382 hunk->splittable_into++;
387 static size_t find_next_line(struct strbuf *sb, size_t offset)
391 if (offset >= sb->len)
392 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
393 (int)offset, (int)sb->len, sb->buf);
395 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
398 return eol - sb->buf + 1;
401 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
402 ssize_t delta, int colored, struct strbuf *out)
404 struct hunk_header *header = &hunk->header;
406 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
408 * Generate the hunk header dynamically, except for special
409 * hunks (such as the diff header).
413 unsigned long old_offset = header->old_offset;
414 unsigned long new_offset = header->new_offset;
417 p = s->plain.buf + header->extra_start;
418 len = header->extra_end - header->extra_start;
420 strbuf_addstr(out, s->s.fraginfo_color);
421 p = s->colored.buf + header->colored_extra_start;
422 len = header->colored_extra_end
423 - header->colored_extra_start;
426 if (s->mode->is_reverse)
431 strbuf_addf(out, "@@ -%lu,%lu +%lu,%lu @@",
432 old_offset, header->old_count,
433 new_offset, header->new_count);
435 strbuf_add(out, p, len);
437 strbuf_addf(out, "%s\n", GIT_COLOR_RESET);
439 strbuf_addch(out, '\n');
443 strbuf_add(out, s->colored.buf + hunk->colored_start,
444 hunk->colored_end - hunk->colored_start);
446 strbuf_add(out, s->plain.buf + hunk->start,
447 hunk->end - hunk->start);
450 static void render_diff_header(struct add_p_state *s,
451 struct file_diff *file_diff, int colored,
455 * If there was a mode change, the first hunk is a pseudo hunk that
456 * corresponds to the mode line in the header. If the user did not want
457 * to stage that "hunk", we actually have to cut it out from the header.
459 int skip_mode_change =
460 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
461 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
463 if (!skip_mode_change) {
464 render_hunk(s, head, 0, colored, out);
469 const char *p = s->colored.buf;
471 strbuf_add(out, p + head->colored_start,
472 first->colored_start - head->colored_start);
473 strbuf_add(out, p + first->colored_end,
474 head->colored_end - first->colored_end);
476 const char *p = s->plain.buf;
478 strbuf_add(out, p + head->start, first->start - head->start);
479 strbuf_add(out, p + first->end, head->end - first->end);
483 /* Coalesce hunks again that were split */
484 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
485 size_t *hunk_index, int use_all, struct hunk *merged)
487 size_t i = *hunk_index, delta;
488 struct hunk *hunk = file_diff->hunk + i;
489 /* `header` corresponds to the merged hunk */
490 struct hunk_header *header = &merged->header, *next;
492 if (!use_all && hunk->use != USE_HUNK)
496 /* We simply skip the colored part (if any) when merging hunks */
497 merged->colored_start = merged->colored_end = 0;
499 for (; i + 1 < file_diff->hunk_nr; i++) {
501 next = &hunk->header;
504 * Stop merging hunks when:
506 * - the hunk is not selected for use, or
507 * - the hunk does not overlap with the already-merged hunk(s)
509 if ((!use_all && hunk->use != USE_HUNK) ||
510 header->new_offset >= next->new_offset + merged->delta ||
511 header->new_offset + header->new_count
512 < next->new_offset + merged->delta)
516 * If the hunks were not edited, and overlap, we can simply
517 * extend the line range.
519 if (merged->start < hunk->start && merged->end > hunk->start) {
520 merged->end = hunk->end;
521 merged->colored_end = hunk->colored_end;
524 const char *plain = s->plain.buf;
525 size_t overlapping_line_count = header->new_offset
526 + header->new_count - merged->delta
528 size_t overlap_end = hunk->start;
529 size_t overlap_start = overlap_end;
530 size_t overlap_next, len, j;
533 * One of the hunks was edited: the modified hunk was
534 * appended to the strbuf `s->plain`.
536 * Let's ensure that at least the last context line of
537 * the first hunk overlaps with the corresponding line
538 * of the second hunk, and then merge.
540 for (j = 0; j < overlapping_line_count; j++) {
541 overlap_next = find_next_line(&s->plain,
544 if (overlap_next > hunk->end)
545 BUG("failed to find %d context lines "
547 (int)overlapping_line_count,
548 (int)(hunk->end - hunk->start),
549 plain + hunk->start);
551 if (plain[overlap_end] != ' ')
552 return error(_("expected context line "
557 plain + hunk->start);
559 overlap_start = overlap_end;
560 overlap_end = overlap_next;
562 len = overlap_end - overlap_start;
564 if (len > merged->end - merged->start ||
565 memcmp(plain + merged->end - len,
566 plain + overlap_start, len))
567 return error(_("hunks do not overlap:\n%.*s\n"
568 "\tdoes not end with:\n%.*s"),
569 (int)(merged->end - merged->start),
570 plain + merged->start,
571 (int)len, plain + overlap_start);
574 * Since the start-end ranges are not adjacent, we
575 * cannot simply take the union of the ranges. To
576 * address that, we temporarily append the union of the
577 * lines to the `plain` strbuf.
579 if (merged->end != s->plain.len) {
580 size_t start = s->plain.len;
582 strbuf_add(&s->plain, plain + merged->start,
583 merged->end - merged->start);
584 plain = s->plain.buf;
585 merged->start = start;
586 merged->end = s->plain.len;
589 strbuf_add(&s->plain,
591 hunk->end - overlap_end);
592 merged->end = s->plain.len;
593 merged->splittable_into += hunk->splittable_into;
594 delta = merged->delta;
595 merged->delta += hunk->delta;
598 header->old_count = next->old_offset + next->old_count
599 - header->old_offset;
600 header->new_count = next->new_offset + delta
601 + next->new_count - header->new_offset;
604 if (i == *hunk_index)
611 static void reassemble_patch(struct add_p_state *s,
612 struct file_diff *file_diff, int use_all,
616 size_t save_len = s->plain.len, i;
619 render_diff_header(s, file_diff, 0, out);
621 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
622 struct hunk merged = { 0 };
624 hunk = file_diff->hunk + i;
625 if (!use_all && hunk->use != USE_HUNK)
626 delta += hunk->header.old_count
627 - hunk->header.new_count;
629 /* merge overlapping hunks into a temporary hunk */
630 if (merge_hunks(s, file_diff, &i, use_all, &merged))
633 render_hunk(s, hunk, delta, 0, out);
636 * In case `merge_hunks()` used `plain` as a scratch
637 * pad (this happens when an edited hunk had to be
638 * coalesced with another hunk).
640 strbuf_setlen(&s->plain, save_len);
642 delta += hunk->delta;
647 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
650 int colored = !!s->colored.len, first = 1;
651 struct hunk *hunk = file_diff->hunk + hunk_index;
652 size_t splittable_into;
653 size_t end, colored_end, current, colored_current = 0, context_line_count;
654 struct hunk_header remaining, *header;
657 if (hunk_index >= file_diff->hunk_nr)
658 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
659 (int)hunk_index, (int)file_diff->hunk_nr);
661 if (hunk->splittable_into < 2)
663 splittable_into = hunk->splittable_into;
666 colored_end = hunk->colored_end;
668 remaining = hunk->header;
670 file_diff->hunk_nr += splittable_into - 1;
671 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
672 if (hunk_index + splittable_into < file_diff->hunk_nr)
673 memmove(file_diff->hunk + hunk_index + splittable_into,
674 file_diff->hunk + hunk_index + 1,
675 (file_diff->hunk_nr - hunk_index - splittable_into)
677 hunk = file_diff->hunk + hunk_index;
678 hunk->splittable_into = 1;
679 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
681 header = &hunk->header;
682 header->old_count = header->new_count = 0;
684 current = hunk->start;
686 colored_current = hunk->colored_start;
688 context_line_count = 0;
690 while (splittable_into > 1) {
691 ch = s->plain.buf[current];
694 BUG("buffer overrun while splitting hunks");
697 * Is this the first context line after a chain of +/- lines?
698 * Then record the start of the next split hunk.
700 if ((marker == '-' || marker == '+') && ch == ' ') {
702 hunk[1].start = current;
704 hunk[1].colored_start = colored_current;
705 context_line_count = 0;
709 * Was the previous line a +/- one? Alternatively, is this the
710 * first line (and not a +/- one)?
712 * Then just increment the appropriate counter and continue
713 * with the next line.
715 if (marker != ' ' || (ch != '-' && ch != '+')) {
717 /* Comment lines are attached to the previous line */
719 ch = marker ? marker : ' ';
721 /* current hunk not done yet */
723 context_line_count++;
729 BUG("unhandled diff marker: '%c'", ch);
731 current = find_next_line(&s->plain, current);
734 find_next_line(&s->colored,
740 * We got us the start of a new hunk!
742 * This is a context line, so it is shared with the previous
747 if (header->old_count || header->new_count)
748 BUG("counts are off: %d/%d",
749 (int)header->old_count,
750 (int)header->new_count);
752 header->old_count = context_line_count;
753 header->new_count = context_line_count;
754 context_line_count = 0;
759 remaining.old_offset += header->old_count;
760 remaining.old_count -= header->old_count;
761 remaining.new_offset += header->new_count;
762 remaining.new_count -= header->new_count;
764 /* initialize next hunk header's offsets */
765 hunk[1].header.old_offset =
766 header->old_offset + header->old_count;
767 hunk[1].header.new_offset =
768 header->new_offset + header->new_count;
770 /* add one split hunk */
771 header->old_count += context_line_count;
772 header->new_count += context_line_count;
776 hunk->colored_end = colored_current;
779 hunk->splittable_into = 1;
780 hunk->use = hunk[-1].use;
781 header = &hunk->header;
783 header->old_count = header->new_count = context_line_count;
784 context_line_count = 0;
790 /* last hunk simply gets the rest */
791 if (header->old_offset != remaining.old_offset)
792 BUG("miscounted old_offset: %lu != %lu",
793 header->old_offset, remaining.old_offset);
794 if (header->new_offset != remaining.new_offset)
795 BUG("miscounted new_offset: %lu != %lu",
796 header->new_offset, remaining.new_offset);
797 header->old_count = remaining.old_count;
798 header->new_count = remaining.new_count;
801 hunk->colored_end = colored_end;
806 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
808 const char *plain = s->plain.buf;
809 size_t current, eol, next;
814 hunk->colored_start = s->colored.len;
815 for (current = hunk->start; current < hunk->end; ) {
816 for (eol = current; eol < hunk->end; eol++)
817 if (plain[eol] == '\n')
819 next = eol + (eol < hunk->end);
820 if (eol > current && plain[eol - 1] == '\r')
823 strbuf_addstr(&s->colored,
824 plain[current] == '-' ?
825 s->s.file_old_color :
826 plain[current] == '+' ?
827 s->s.file_new_color :
829 strbuf_add(&s->colored, plain + current, eol - current);
830 strbuf_addstr(&s->colored, GIT_COLOR_RESET);
832 strbuf_add(&s->colored, plain + eol, next - eol);
835 hunk->colored_end = s->colored.len;
838 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
842 strbuf_reset(&s->buf);
843 strbuf_commented_addf(&s->buf, _("Manual hunk edit mode -- see bottom for "
844 "a quick guide.\n"));
845 render_hunk(s, hunk, 0, 0, &s->buf);
846 strbuf_commented_addf(&s->buf,
848 "To remove '%c' lines, make them ' ' lines "
850 "To remove '%c' lines, delete them.\n"
851 "Lines starting with %c will be removed.\n"),
852 s->mode->is_reverse ? '+' : '-',
853 s->mode->is_reverse ? '-' : '+',
855 strbuf_commented_addf(&s->buf, "%s", _(s->mode->edit_hunk_hint));
857 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
860 strbuf_commented_addf(&s->buf,
861 _("If it does not apply cleanly, you will be "
862 "given an opportunity to\n"
863 "edit again. If all lines of the hunk are "
864 "removed, then the edit is\n"
865 "aborted and the hunk is left unchanged.\n"));
867 if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
870 /* strip out commented lines */
871 hunk->start = s->plain.len;
872 for (i = 0; i < s->buf.len; ) {
873 size_t next = find_next_line(&s->buf, i);
875 if (s->buf.buf[i] != comment_line_char)
876 strbuf_add(&s->plain, s->buf.buf + i, next - i);
880 hunk->end = s->plain.len;
881 if (hunk->end == hunk->start)
882 /* The user aborted editing by deleting everything */
885 recolor_hunk(s, hunk);
888 * If the hunk header is intact, parse it, otherwise simply use the
889 * hunk header prior to editing (which will adjust `hunk->start` to
890 * skip the hunk header).
892 if (s->plain.buf[hunk->start] == '@' &&
893 parse_hunk_header(s, hunk) < 0)
894 return error(_("could not parse hunk header"));
899 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
900 size_t orig_old_count, size_t orig_new_count)
902 struct hunk_header *header = &hunk->header;
905 header->old_count = header->new_count = 0;
906 for (i = hunk->start; i < hunk->end; ) {
907 switch (s->plain.buf[i]) {
914 case ' ': case '\r': case '\n':
920 i = find_next_line(&s->plain, i);
923 return orig_old_count - orig_new_count
924 - header->old_count + header->new_count;
927 static int run_apply_check(struct add_p_state *s,
928 struct file_diff *file_diff)
930 struct child_process cp = CHILD_PROCESS_INIT;
932 strbuf_reset(&s->buf);
933 reassemble_patch(s, file_diff, 1, &s->buf);
935 setup_child_process(s, &cp,
936 "apply", "--check", NULL);
937 argv_array_pushv(&cp.args, s->mode->apply_check_args);
938 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
939 return error(_("'git apply --cached' failed"));
944 static int prompt_yesno(struct add_p_state *s, const char *prompt)
947 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
949 if (strbuf_getline(&s->answer, stdin) == EOF)
951 strbuf_trim_trailing_newline(&s->answer);
952 switch (tolower(s->answer.buf[0])) {
959 static int edit_hunk_loop(struct add_p_state *s,
960 struct file_diff *file_diff, struct hunk *hunk)
962 size_t plain_len = s->plain.len, colored_len = s->colored.len;
968 int res = edit_hunk_manually(s, hunk);
977 recount_edited_hunk(s, hunk,
978 backup.header.old_count,
979 backup.header.new_count);
980 if (!run_apply_check(s, file_diff))
984 /* Drop edits (they were appended to s->plain) */
985 strbuf_setlen(&s->plain, plain_len);
986 strbuf_setlen(&s->colored, colored_len);
990 * TRANSLATORS: do not translate [y/n]
991 * The program will only accept that input at this point.
992 * Consider translating (saying "no" discards!) as
993 * (saying "n" for "no" discards!) if the translation
994 * of the word "no" does not start with n.
996 res = prompt_yesno(s, _("Your edited hunk does not apply. "
997 "Edit again (saying \"no\" discards!) "
1004 #define SUMMARY_HEADER_WIDTH 20
1005 #define SUMMARY_LINE_WIDTH 80
1006 static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1009 struct hunk_header *header = &hunk->header;
1010 struct strbuf *plain = &s->plain;
1011 size_t len = out->len, i;
1013 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1014 header->old_offset, header->old_count,
1015 header->new_offset, header->new_count);
1016 if (out->len - len < SUMMARY_HEADER_WIDTH)
1017 strbuf_addchars(out, ' ',
1018 SUMMARY_HEADER_WIDTH + len - out->len);
1019 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1020 if (plain->buf[i] != ' ')
1023 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1024 if (out->len - len > SUMMARY_LINE_WIDTH)
1025 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1026 strbuf_complete_line(out);
1029 #define DISPLAY_HUNKS_LINES 20
1030 static size_t display_hunks(struct add_p_state *s,
1031 struct file_diff *file_diff, size_t start_index)
1033 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1035 if (end_index > file_diff->hunk_nr)
1036 end_index = file_diff->hunk_nr;
1038 while (start_index < end_index) {
1039 struct hunk *hunk = file_diff->hunk + start_index++;
1041 strbuf_reset(&s->buf);
1042 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1043 : hunk->use == SKIP_HUNK ? '-' : ' ',
1045 summarize_hunk(s, hunk, &s->buf);
1046 fputs(s->buf.buf, stdout);
1052 static const char help_patch_remainder[] =
1053 N_("j - leave this hunk undecided, see next undecided hunk\n"
1054 "J - leave this hunk undecided, see next hunk\n"
1055 "k - leave this hunk undecided, see previous undecided hunk\n"
1056 "K - leave this hunk undecided, see previous hunk\n"
1057 "g - select a hunk to go to\n"
1058 "/ - search for a hunk matching the given regex\n"
1059 "s - split the current hunk into smaller hunks\n"
1060 "e - manually edit the current hunk\n"
1061 "? - print help\n");
1063 static int patch_update_file(struct add_p_state *s,
1064 struct file_diff *file_diff)
1066 size_t hunk_index = 0;
1067 ssize_t i, undecided_previous, undecided_next;
1070 struct child_process cp = CHILD_PROCESS_INIT;
1071 int colored = !!s->colored.len, quit = 0;
1072 enum prompt_mode_type prompt_mode_type;
1074 if (!file_diff->hunk_nr)
1077 strbuf_reset(&s->buf);
1078 render_diff_header(s, file_diff, colored, &s->buf);
1079 fputs(s->buf.buf, stdout);
1081 if (hunk_index >= file_diff->hunk_nr)
1083 hunk = file_diff->hunk + hunk_index;
1085 undecided_previous = -1;
1086 for (i = hunk_index - 1; i >= 0; i--)
1087 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1088 undecided_previous = i;
1092 undecided_next = -1;
1093 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1094 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1099 /* Everything decided? */
1100 if (undecided_previous < 0 && undecided_next < 0 &&
1101 hunk->use != UNDECIDED_HUNK)
1104 strbuf_reset(&s->buf);
1105 render_hunk(s, hunk, 0, colored, &s->buf);
1106 fputs(s->buf.buf, stdout);
1108 strbuf_reset(&s->buf);
1109 if (undecided_previous >= 0)
1110 strbuf_addstr(&s->buf, ",k");
1112 strbuf_addstr(&s->buf, ",K");
1113 if (undecided_next >= 0)
1114 strbuf_addstr(&s->buf, ",j");
1115 if (hunk_index + 1 < file_diff->hunk_nr)
1116 strbuf_addstr(&s->buf, ",J");
1117 if (file_diff->hunk_nr > 1)
1118 strbuf_addstr(&s->buf, ",g,/");
1119 if (hunk->splittable_into > 1)
1120 strbuf_addstr(&s->buf, ",s");
1121 if (hunk_index + 1 > file_diff->mode_change &&
1122 !file_diff->deleted)
1123 strbuf_addstr(&s->buf, ",e");
1125 if (file_diff->deleted)
1126 prompt_mode_type = PROMPT_DELETION;
1127 else if (file_diff->mode_change && !hunk_index)
1128 prompt_mode_type = PROMPT_MODE_CHANGE;
1130 prompt_mode_type = PROMPT_HUNK;
1132 color_fprintf(stdout, s->s.prompt_color,
1133 "(%"PRIuMAX"/%"PRIuMAX") ",
1134 (uintmax_t)hunk_index + 1,
1135 (uintmax_t)file_diff->hunk_nr);
1136 color_fprintf(stdout, s->s.prompt_color,
1137 _(s->mode->prompt_mode[prompt_mode_type]),
1140 if (strbuf_getline(&s->answer, stdin) == EOF)
1142 strbuf_trim_trailing_newline(&s->answer);
1146 ch = tolower(s->answer.buf[0]);
1148 hunk->use = USE_HUNK;
1150 hunk_index = undecided_next < 0 ?
1151 file_diff->hunk_nr : undecided_next;
1152 } else if (ch == 'n') {
1153 hunk->use = SKIP_HUNK;
1154 goto soft_increment;
1155 } else if (ch == 'a') {
1156 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1157 hunk = file_diff->hunk + hunk_index;
1158 if (hunk->use == UNDECIDED_HUNK)
1159 hunk->use = USE_HUNK;
1161 } else if (ch == 'd' || ch == 'q') {
1162 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1163 hunk = file_diff->hunk + hunk_index;
1164 if (hunk->use == UNDECIDED_HUNK)
1165 hunk->use = SKIP_HUNK;
1171 } else if (s->answer.buf[0] == 'K') {
1175 err(s, _("No previous hunk"));
1176 } else if (s->answer.buf[0] == 'J') {
1177 if (hunk_index + 1 < file_diff->hunk_nr)
1180 err(s, _("No next hunk"));
1181 } else if (s->answer.buf[0] == 'k') {
1182 if (undecided_previous >= 0)
1183 hunk_index = undecided_previous;
1185 err(s, _("No previous hunk"));
1186 } else if (s->answer.buf[0] == 'j') {
1187 if (undecided_next >= 0)
1188 hunk_index = undecided_next;
1190 err(s, _("No next hunk"));
1191 } else if (s->answer.buf[0] == 'g') {
1193 unsigned long response;
1195 if (file_diff->hunk_nr < 2) {
1196 err(s, _("No other hunks to goto"));
1199 strbuf_remove(&s->answer, 0, 1);
1200 strbuf_trim(&s->answer);
1201 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1202 if (i < file_diff->mode_change)
1203 i = file_diff->mode_change;
1204 while (s->answer.len == 0) {
1205 i = display_hunks(s, file_diff, i);
1206 printf("%s", i < file_diff->hunk_nr ?
1207 _("go to which hunk (<ret> to see "
1208 "more)? ") : _("go to which hunk? "));
1210 if (strbuf_getline(&s->answer,
1213 strbuf_trim_trailing_newline(&s->answer);
1216 strbuf_trim(&s->answer);
1217 response = strtoul(s->answer.buf, &pend, 10);
1218 if (*pend || pend == s->answer.buf)
1219 err(s, _("Invalid number: '%s'"),
1221 else if (0 < response && response <= file_diff->hunk_nr)
1222 hunk_index = response - 1;
1224 err(s, Q_("Sorry, only %d hunk available.",
1225 "Sorry, only %d hunks available.",
1226 file_diff->hunk_nr),
1227 (int)file_diff->hunk_nr);
1228 } else if (s->answer.buf[0] == '/') {
1232 if (file_diff->hunk_nr < 2) {
1233 err(s, _("No other hunks to search"));
1236 strbuf_remove(&s->answer, 0, 1);
1237 strbuf_trim_trailing_newline(&s->answer);
1238 if (s->answer.len == 0) {
1239 printf("%s", _("search for regex? "));
1241 if (strbuf_getline(&s->answer,
1244 strbuf_trim_trailing_newline(&s->answer);
1245 if (s->answer.len == 0)
1248 ret = regcomp(®ex, s->answer.buf,
1249 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1253 regerror(ret, ®ex, errbuf, sizeof(errbuf));
1254 err(s, _("Malformed search regexp %s: %s"),
1255 s->answer.buf, errbuf);
1260 /* render the hunk into a scratch buffer */
1261 render_hunk(s, file_diff->hunk + i, 0, 0,
1263 if (regexec(®ex, s->buf.buf, 0, NULL, 0)
1267 if (i == file_diff->hunk_nr)
1269 if (i != hunk_index)
1271 err(s, _("No hunk matches the given pattern"));
1275 } else if (s->answer.buf[0] == 's') {
1276 size_t splittable_into = hunk->splittable_into;
1277 if (splittable_into < 2)
1278 err(s, _("Sorry, cannot split this hunk"));
1279 else if (!split_hunk(s, file_diff,
1280 hunk - file_diff->hunk))
1281 color_fprintf_ln(stdout, s->s.header_color,
1282 _("Split into %d hunks."),
1283 (int)splittable_into);
1284 } else if (s->answer.buf[0] == 'e') {
1285 if (hunk_index + 1 == file_diff->mode_change)
1286 err(s, _("Sorry, cannot edit this hunk"));
1287 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1288 hunk->use = USE_HUNK;
1289 goto soft_increment;
1292 const char *p = _(help_patch_remainder), *eol = p;
1294 color_fprintf(stdout, s->s.help_color, "%s",
1295 _(s->mode->help_patch_text));
1298 * Show only those lines of the remainder that are
1299 * actually applicable with the current hunk.
1301 for (; *p; p = eol + (*eol == '\n')) {
1302 eol = strchrnul(p, '\n');
1305 * `s->buf` still contains the part of the
1306 * commands shown in the prompt that are not
1309 if (*p != '?' && !strchr(s->buf.buf, *p))
1312 color_fprintf_ln(stdout, s->s.help_color,
1313 "%.*s", (int)(eol - p), p);
1318 /* Any hunk to be used? */
1319 for (i = 0; i < file_diff->hunk_nr; i++)
1320 if (file_diff->hunk[i].use == USE_HUNK)
1323 if (i < file_diff->hunk_nr) {
1324 /* At least one hunk selected: apply */
1325 strbuf_reset(&s->buf);
1326 reassemble_patch(s, file_diff, 0, &s->buf);
1328 discard_index(s->s.r->index);
1329 setup_child_process(s, &cp, "apply", NULL);
1330 argv_array_pushv(&cp.args, s->mode->apply_args);
1331 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1333 error(_("'git apply' failed"));
1334 if (!repo_read_index(s->s.r))
1335 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
1336 1, NULL, NULL, NULL);
1343 int run_add_p(struct repository *r, enum add_p_mode mode,
1344 const char *revision, const struct pathspec *ps)
1346 struct add_p_state s = {
1347 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1349 size_t i, binary_count = 0;
1351 init_add_i_state(&s.s, r);
1353 s.mode = &patch_mode_add;
1354 s.revision = revision;
1356 if (discard_index(r->index) < 0 || repo_read_index(r) < 0 ||
1357 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1358 NULL, NULL, NULL) < 0 ||
1359 parse_diff(&s, ps) < 0) {
1360 strbuf_release(&s.plain);
1361 strbuf_release(&s.colored);
1365 for (i = 0; i < s.file_diff_nr; i++)
1366 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1368 else if (patch_update_file(&s, s.file_diff + i))
1371 if (s.file_diff_nr == 0)
1372 fprintf(stderr, _("No changes.\n"));
1373 else if (binary_count == s.file_diff_nr)
1374 fprintf(stderr, _("Only binary files changed.\n"));
1376 strbuf_release(&s.answer);
1377 strbuf_release(&s.buf);
1378 strbuf_release(&s.plain);
1379 strbuf_release(&s.colored);