built-in add -p: prepare for patch modes other than "stage"
[git] / add-patch.c
1 #include "cache.h"
2 #include "add-interactive.h"
3 #include "strbuf.h"
4 #include "run-command.h"
5 #include "argv-array.h"
6 #include "pathspec.h"
7 #include "color.h"
8 #include "diff.h"
9
10 enum prompt_mode_type {
11         PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_HUNK,
12         PROMPT_MODE_MAX, /* must be last */
13 };
14
15 struct patch_mode {
16         /*
17          * The magic constant 4 is chosen such that all patch modes
18          * provide enough space for three command-line arguments followed by a
19          * trailing `NULL`.
20          */
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;
25 };
26
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 },
31         .prompt_mode = {
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,?]? ")
35         },
36         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
37                              "will immediately be marked for staging."),
38         .help_patch_text =
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 "
42                         "ones\n"
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 "
45                         "the file\n")
46 };
47
48 struct hunk_header {
49         unsigned long old_offset, old_count, new_offset, new_count;
50         /*
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.
54          */
55         size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
56 };
57
58 struct hunk {
59         size_t start, end, colored_start, colored_end, splittable_into;
60         ssize_t delta;
61         enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
62         struct hunk_header header;
63 };
64
65 struct add_p_state {
66         struct add_i_state s;
67         struct strbuf answer, buf;
68
69         /* parsed diff */
70         struct strbuf plain, colored;
71         struct file_diff {
72                 struct hunk head;
73                 struct hunk *hunk;
74                 size_t hunk_nr, hunk_alloc;
75                 unsigned deleted:1, mode_change:1,binary:1;
76         } *file_diff;
77         size_t file_diff_nr;
78
79         /* patch mode */
80         struct patch_mode *mode;
81         const char *revision;
82 };
83
84 static void err(struct add_p_state *s, const char *fmt, ...)
85 {
86         va_list args;
87
88         va_start(args, fmt);
89         fputs(s->s.error_color, stderr);
90         vfprintf(stderr, fmt, args);
91         fputs(s->s.reset_color, stderr);
92         fputc('\n', stderr);
93         va_end(args);
94 }
95
96 static void setup_child_process(struct add_p_state *s,
97                                 struct child_process *cp, ...)
98 {
99         va_list ap;
100         const char *arg;
101
102         va_start(ap, cp);
103         while ((arg = va_arg(ap, const char *)))
104                 argv_array_push(&cp->args, arg);
105         va_end(ap);
106
107         cp->git_cmd = 1;
108         argv_array_pushf(&cp->env_array,
109                          INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
110 }
111
112 static int parse_range(const char **p,
113                        unsigned long *offset, unsigned long *count)
114 {
115         char *pend;
116
117         *offset = strtoul(*p, &pend, 10);
118         if (pend == *p)
119                 return -1;
120         if (*pend != ',') {
121                 *count = 1;
122                 *p = pend;
123                 return 0;
124         }
125         *count = strtoul(pend + 1, (char **)p, 10);
126         return *p == pend + 1 ? -1 : 0;
127 }
128
129 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
130 {
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);
134
135         if (!eol)
136                 eol = s->plain.buf + s->plain.len;
137
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);
145
146         hunk->start = eol - s->plain.buf + (*eol == '\n');
147         header->extra_start = p - s->plain.buf;
148         header->extra_end = hunk->start;
149
150         if (!s->colored.len) {
151                 header->colored_extra_start = header->colored_extra_end = 0;
152                 return 0;
153         }
154
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);
158         if (!eol)
159                 eol = s->colored.buf + s->colored.len;
160         p = memmem(line, eol - line, "@@ -", 4);
161         if (!p)
162                 return error(_("could not parse colored hunk header '%.*s'"),
163                              (int)(eol - line), line);
164         p = memmem(p + 4, eol - p - 4, " @@", 3);
165         if (!p)
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;
171
172         return 0;
173 }
174
175 static int is_octal(const char *p, size_t len)
176 {
177         if (!len)
178                 return 0;
179
180         while (len--)
181                 if (*p < '0' || *(p++) > '7')
182                         return 0;
183         return 1;
184 }
185
186 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
187 {
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;
195         int res;
196
197         argv_array_pushv(&args, s->mode->diff_cmd);
198         if (s->revision) {
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);
205         }
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);
211
212         setup_child_process(s, &cp, NULL);
213         cp.argv = args.argv;
214         res = capture_command(&cp, plain, 0);
215         if (res) {
216                 argv_array_clear(&args);
217                 return error(_("could not parse diff"));
218         }
219         if (!plain->len) {
220                 argv_array_clear(&args);
221                 return 0;
222         }
223         strbuf_complete_line(plain);
224
225         if (want_color_fd(1, -1)) {
226                 struct child_process colored_cp = CHILD_PROCESS_INIT;
227
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);
234                 if (res)
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;
239         }
240         argv_array_clear(&args);
241
242         /* parse files and hunks */
243         p = plain->buf;
244         pend = p + plain->len;
245         while (p != pend) {
246                 char *eol = memchr(p, '\n', pend - p);
247                 const char *deleted = NULL, *mode_change = NULL;
248
249                 if (!eol)
250                         eol = pend;
251
252                 if (starts_with(p, "diff ")) {
253                         s->file_diff_nr++;
254                         ALLOC_GROW(s->file_diff, s->file_diff_nr,
255                                    file_diff_alloc);
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;
260                         if (colored_p)
261                                 hunk->colored_start = colored_p - colored->buf;
262                         marker = '\0';
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 == '+')
272                                 /*
273                                  * Should not happen; previous hunk did not end
274                                  * in a context line? Handle it anyway.
275                                  */
276                                 hunk->splittable_into++;
277
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));
283
284                         hunk->start = p - plain->buf;
285                         if (colored)
286                                 hunk->colored_start = colored_p - colored->buf;
287
288                         if (deleted)
289                                 file_diff->deleted = 1;
290                         else if (parse_hunk_header(s, hunk) < 0)
291                                 return -1;
292
293                         /*
294                          * Start counting into how many hunks this one can be
295                          * split
296                          */
297                         marker = *p;
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);
307
308                         /*
309                          * Do *not* change `hunk`: the mode change pseudo-hunk
310                          * is _part of_ the header "hunk".
311                          */
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;
317                         if (colored_p)
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)) {
323
324                         /*
325                          * Extend the "mode change" pseudo-hunk to include also
326                          * the "new mode" line.
327                          */
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;
341
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);
346
347                 if ((marker == '-' || marker == '+') && *p == ' ')
348                         hunk->splittable_into++;
349                 if (marker && *p != '\\')
350                         marker = *p;
351
352                 p = eol == pend ? pend : eol + 1;
353                 hunk->end = p - plain->buf;
354
355                 if (colored) {
356                         char *colored_eol = memchr(colored_p, '\n',
357                                                    colored_pend - colored_p);
358                         if (colored_eol)
359                                 colored_p = colored_eol + 1;
360                         else
361                                 colored_p = colored_pend;
362
363                         hunk->colored_end = colored_p - colored->buf;
364                 }
365
366                 if (mode_change) {
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;
372                         if (colored)
373                                 file_diff->hunk->colored_end = hunk->colored_end;
374                 }
375         }
376
377         if (marker == '-' || marker == '+')
378                 /*
379                  * Last hunk ended in non-context line (i.e. it appended lines
380                  * to the file, so there are no trailing context lines).
381                  */
382                 hunk->splittable_into++;
383
384         return 0;
385 }
386
387 static size_t find_next_line(struct strbuf *sb, size_t offset)
388 {
389         char *eol;
390
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);
394
395         eol = memchr(sb->buf + offset, '\n', sb->len - offset);
396         if (!eol)
397                 return sb->len;
398         return eol - sb->buf + 1;
399 }
400
401 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
402                         ssize_t delta, int colored, struct strbuf *out)
403 {
404         struct hunk_header *header = &hunk->header;
405
406         if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
407                 /*
408                  * Generate the hunk header dynamically, except for special
409                  * hunks (such as the diff header).
410                  */
411                 const char *p;
412                 size_t len;
413                 unsigned long old_offset = header->old_offset;
414                 unsigned long new_offset = header->new_offset;
415
416                 if (!colored) {
417                         p = s->plain.buf + header->extra_start;
418                         len = header->extra_end - header->extra_start;
419                 } else {
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;
424                 }
425
426                 if (s->mode->is_reverse)
427                         old_offset -= delta;
428                 else
429                         new_offset += delta;
430
431                 strbuf_addf(out, "@@ -%lu,%lu +%lu,%lu @@",
432                             old_offset, header->old_count,
433                             new_offset, header->new_count);
434                 if (len)
435                         strbuf_add(out, p, len);
436                 else if (colored)
437                         strbuf_addf(out, "%s\n", GIT_COLOR_RESET);
438                 else
439                         strbuf_addch(out, '\n');
440         }
441
442         if (colored)
443                 strbuf_add(out, s->colored.buf + hunk->colored_start,
444                            hunk->colored_end - hunk->colored_start);
445         else
446                 strbuf_add(out, s->plain.buf + hunk->start,
447                            hunk->end - hunk->start);
448 }
449
450 static void render_diff_header(struct add_p_state *s,
451                                struct file_diff *file_diff, int colored,
452                                struct strbuf *out)
453 {
454         /*
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.
458          */
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;
462
463         if (!skip_mode_change) {
464                 render_hunk(s, head, 0, colored, out);
465                 return;
466         }
467
468         if (colored) {
469                 const char *p = s->colored.buf;
470
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);
475         } else {
476                 const char *p = s->plain.buf;
477
478                 strbuf_add(out, p + head->start, first->start - head->start);
479                 strbuf_add(out, p + first->end, head->end - first->end);
480         }
481 }
482
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)
486 {
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;
491
492         if (!use_all && hunk->use != USE_HUNK)
493                 return 0;
494
495         *merged = *hunk;
496         /* We simply skip the colored part (if any) when merging hunks */
497         merged->colored_start = merged->colored_end = 0;
498
499         for (; i + 1 < file_diff->hunk_nr; i++) {
500                 hunk++;
501                 next = &hunk->header;
502
503                 /*
504                  * Stop merging hunks when:
505                  *
506                  * - the hunk is not selected for use, or
507                  * - the hunk does not overlap with the already-merged hunk(s)
508                  */
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)
513                         break;
514
515                 /*
516                  * If the hunks were not edited, and overlap, we can simply
517                  * extend the line range.
518                  */
519                 if (merged->start < hunk->start && merged->end > hunk->start) {
520                         merged->end = hunk->end;
521                         merged->colored_end = hunk->colored_end;
522                         delta = 0;
523                 } else {
524                         const char *plain = s->plain.buf;
525                         size_t  overlapping_line_count = header->new_offset
526                                 + header->new_count - merged->delta
527                                 - next->new_offset;
528                         size_t overlap_end = hunk->start;
529                         size_t overlap_start = overlap_end;
530                         size_t overlap_next, len, j;
531
532                         /*
533                          * One of the hunks was edited: the modified hunk was
534                          * appended to the strbuf `s->plain`.
535                          *
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.
539                          */
540                         for (j = 0; j < overlapping_line_count; j++) {
541                                 overlap_next = find_next_line(&s->plain,
542                                                               overlap_end);
543
544                                 if (overlap_next > hunk->end)
545                                         BUG("failed to find %d context lines "
546                                             "in:\n%.*s",
547                                             (int)overlapping_line_count,
548                                             (int)(hunk->end - hunk->start),
549                                             plain + hunk->start);
550
551                                 if (plain[overlap_end] != ' ')
552                                         return error(_("expected context line "
553                                                        "#%d in\n%.*s"),
554                                                      (int)(j + 1),
555                                                      (int)(hunk->end
556                                                            - hunk->start),
557                                                      plain + hunk->start);
558
559                                 overlap_start = overlap_end;
560                                 overlap_end = overlap_next;
561                         }
562                         len = overlap_end - overlap_start;
563
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);
572
573                         /*
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.
578                          */
579                         if (merged->end != s->plain.len) {
580                                 size_t start = s->plain.len;
581
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;
587                         }
588
589                         strbuf_add(&s->plain,
590                                    plain + overlap_end,
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;
596                 }
597
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;
602         }
603
604         if (i == *hunk_index)
605                 return 0;
606
607         *hunk_index = i;
608         return 1;
609 }
610
611 static void reassemble_patch(struct add_p_state *s,
612                              struct file_diff *file_diff, int use_all,
613                              struct strbuf *out)
614 {
615         struct hunk *hunk;
616         size_t save_len = s->plain.len, i;
617         ssize_t delta = 0;
618
619         render_diff_header(s, file_diff, 0, out);
620
621         for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
622                 struct hunk merged = { 0 };
623
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;
628                 else {
629                         /* merge overlapping hunks into a temporary hunk */
630                         if (merge_hunks(s, file_diff, &i, use_all, &merged))
631                                 hunk = &merged;
632
633                         render_hunk(s, hunk, delta, 0, out);
634
635                         /*
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).
639                          */
640                         strbuf_setlen(&s->plain, save_len);
641
642                         delta += hunk->delta;
643                 }
644         }
645 }
646
647 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
648                        size_t hunk_index)
649 {
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;
655         char marker, ch;
656
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);
660
661         if (hunk->splittable_into < 2)
662                 return 0;
663         splittable_into = hunk->splittable_into;
664
665         end = hunk->end;
666         colored_end = hunk->colored_end;
667
668         remaining = hunk->header;
669
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)
676                         * sizeof(*hunk));
677         hunk = file_diff->hunk + hunk_index;
678         hunk->splittable_into = 1;
679         memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
680
681         header = &hunk->header;
682         header->old_count = header->new_count = 0;
683
684         current = hunk->start;
685         if (colored)
686                 colored_current = hunk->colored_start;
687         marker = '\0';
688         context_line_count = 0;
689
690         while (splittable_into > 1) {
691                 ch = s->plain.buf[current];
692
693                 if (!ch)
694                         BUG("buffer overrun while splitting hunks");
695
696                 /*
697                  * Is this the first context line after a chain of +/- lines?
698                  * Then record the start of the next split hunk.
699                  */
700                 if ((marker == '-' || marker == '+') && ch == ' ') {
701                         first = 0;
702                         hunk[1].start = current;
703                         if (colored)
704                                 hunk[1].colored_start = colored_current;
705                         context_line_count = 0;
706                 }
707
708                 /*
709                  * Was the previous line a +/- one? Alternatively, is this the
710                  * first line (and not a +/- one)?
711                  *
712                  * Then just increment the appropriate counter and continue
713                  * with the next line.
714                  */
715                 if (marker != ' ' || (ch != '-' && ch != '+')) {
716 next_hunk_line:
717                         /* Comment lines are attached to the previous line */
718                         if (ch == '\\')
719                                 ch = marker ? marker : ' ';
720
721                         /* current hunk not done yet */
722                         if (ch == ' ')
723                                 context_line_count++;
724                         else if (ch == '-')
725                                 header->old_count++;
726                         else if (ch == '+')
727                                 header->new_count++;
728                         else
729                                 BUG("unhandled diff marker: '%c'", ch);
730                         marker = ch;
731                         current = find_next_line(&s->plain, current);
732                         if (colored)
733                                 colored_current =
734                                         find_next_line(&s->colored,
735                                                        colored_current);
736                         continue;
737                 }
738
739                 /*
740                  * We got us the start of a new hunk!
741                  *
742                  * This is a context line, so it is shared with the previous
743                  * hunk, if any.
744                  */
745
746                 if (first) {
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);
751
752                         header->old_count = context_line_count;
753                         header->new_count = context_line_count;
754                         context_line_count = 0;
755                         first = 0;
756                         goto next_hunk_line;
757                 }
758
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;
763
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;
769
770                 /* add one split hunk */
771                 header->old_count += context_line_count;
772                 header->new_count += context_line_count;
773
774                 hunk->end = current;
775                 if (colored)
776                         hunk->colored_end = colored_current;
777
778                 hunk++;
779                 hunk->splittable_into = 1;
780                 hunk->use = hunk[-1].use;
781                 header = &hunk->header;
782
783                 header->old_count = header->new_count = context_line_count;
784                 context_line_count = 0;
785
786                 splittable_into--;
787                 marker = ch;
788         }
789
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;
799         hunk->end = end;
800         if (colored)
801                 hunk->colored_end = colored_end;
802
803         return 0;
804 }
805
806 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
807 {
808         const char *plain = s->plain.buf;
809         size_t current, eol, next;
810
811         if (!s->colored.len)
812                 return;
813
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')
818                                 break;
819                 next = eol + (eol < hunk->end);
820                 if (eol > current && plain[eol - 1] == '\r')
821                         eol--;
822
823                 strbuf_addstr(&s->colored,
824                               plain[current] == '-' ?
825                               s->s.file_old_color :
826                               plain[current] == '+' ?
827                               s->s.file_new_color :
828                               s->s.context_color);
829                 strbuf_add(&s->colored, plain + current, eol - current);
830                 strbuf_addstr(&s->colored, GIT_COLOR_RESET);
831                 if (next > eol)
832                         strbuf_add(&s->colored, plain + eol, next - eol);
833                 current = next;
834         }
835         hunk->colored_end = s->colored.len;
836 }
837
838 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
839 {
840         size_t i;
841
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,
847                               _("---\n"
848                                 "To remove '%c' lines, make them ' ' lines "
849                                 "(context).\n"
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 ? '-' : '+',
854                               comment_line_char);
855         strbuf_commented_addf(&s->buf, "%s", _(s->mode->edit_hunk_hint));
856         /*
857          * TRANSLATORS: 'it' refers to the patch mentioned in the previous
858          * messages.
859          */
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"));
866
867         if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
868                 return -1;
869
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);
874
875                 if (s->buf.buf[i] != comment_line_char)
876                         strbuf_add(&s->plain, s->buf.buf + i, next - i);
877                 i = next;
878         }
879
880         hunk->end = s->plain.len;
881         if (hunk->end == hunk->start)
882                 /* The user aborted editing by deleting everything */
883                 return 0;
884
885         recolor_hunk(s, hunk);
886
887         /*
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).
891          */
892         if (s->plain.buf[hunk->start] == '@' &&
893             parse_hunk_header(s, hunk) < 0)
894                 return error(_("could not parse hunk header"));
895
896         return 1;
897 }
898
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)
901 {
902         struct hunk_header *header = &hunk->header;
903         size_t i;
904
905         header->old_count = header->new_count = 0;
906         for (i = hunk->start; i < hunk->end; ) {
907                 switch (s->plain.buf[i]) {
908                 case '-':
909                         header->old_count++;
910                         break;
911                 case '+':
912                         header->new_count++;
913                         break;
914                 case ' ': case '\r': case '\n':
915                         header->old_count++;
916                         header->new_count++;
917                         break;
918                 }
919
920                 i = find_next_line(&s->plain, i);
921         }
922
923         return orig_old_count - orig_new_count
924                 - header->old_count + header->new_count;
925 }
926
927 static int run_apply_check(struct add_p_state *s,
928                            struct file_diff *file_diff)
929 {
930         struct child_process cp = CHILD_PROCESS_INIT;
931
932         strbuf_reset(&s->buf);
933         reassemble_patch(s, file_diff, 1, &s->buf);
934
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"));
940
941         return 0;
942 }
943
944 static int prompt_yesno(struct add_p_state *s, const char *prompt)
945 {
946         for (;;) {
947                 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
948                 fflush(stdout);
949                 if (strbuf_getline(&s->answer, stdin) == EOF)
950                         return -1;
951                 strbuf_trim_trailing_newline(&s->answer);
952                 switch (tolower(s->answer.buf[0])) {
953                 case 'n': return 0;
954                 case 'y': return 1;
955                 }
956         }
957 }
958
959 static int edit_hunk_loop(struct add_p_state *s,
960                           struct file_diff *file_diff, struct hunk *hunk)
961 {
962         size_t plain_len = s->plain.len, colored_len = s->colored.len;
963         struct hunk backup;
964
965         backup = *hunk;
966
967         for (;;) {
968                 int res = edit_hunk_manually(s, hunk);
969                 if (res == 0) {
970                         /* abandonded */
971                         *hunk = backup;
972                         return -1;
973                 }
974
975                 if (res > 0) {
976                         hunk->delta +=
977                                 recount_edited_hunk(s, hunk,
978                                                     backup.header.old_count,
979                                                     backup.header.new_count);
980                         if (!run_apply_check(s, file_diff))
981                                 return 0;
982                 }
983
984                 /* Drop edits (they were appended to s->plain) */
985                 strbuf_setlen(&s->plain, plain_len);
986                 strbuf_setlen(&s->colored, colored_len);
987                 *hunk = backup;
988
989                 /*
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.
995                  */
996                 res = prompt_yesno(s, _("Your edited hunk does not apply. "
997                                         "Edit again (saying \"no\" discards!) "
998                                         "[y/n]? "));
999                 if (res < 1)
1000                         return -1;
1001         }
1002 }
1003
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,
1007                            struct strbuf *out)
1008 {
1009         struct hunk_header *header = &hunk->header;
1010         struct strbuf *plain = &s->plain;
1011         size_t len = out->len, i;
1012
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] != ' ')
1021                         break;
1022         if (i < hunk->end)
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);
1027 }
1028
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)
1032 {
1033         size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1034
1035         if (end_index > file_diff->hunk_nr)
1036                 end_index = file_diff->hunk_nr;
1037
1038         while (start_index < end_index) {
1039                 struct hunk *hunk = file_diff->hunk + start_index++;
1040
1041                 strbuf_reset(&s->buf);
1042                 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1043                             : hunk->use == SKIP_HUNK ? '-' : ' ',
1044                             (int)start_index);
1045                 summarize_hunk(s, hunk, &s->buf);
1046                 fputs(s->buf.buf, stdout);
1047         }
1048
1049         return end_index;
1050 }
1051
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");
1062
1063 static int patch_update_file(struct add_p_state *s,
1064                              struct file_diff *file_diff)
1065 {
1066         size_t hunk_index = 0;
1067         ssize_t i, undecided_previous, undecided_next;
1068         struct hunk *hunk;
1069         char ch;
1070         struct child_process cp = CHILD_PROCESS_INIT;
1071         int colored = !!s->colored.len, quit = 0;
1072         enum prompt_mode_type prompt_mode_type;
1073
1074         if (!file_diff->hunk_nr)
1075                 return 0;
1076
1077         strbuf_reset(&s->buf);
1078         render_diff_header(s, file_diff, colored, &s->buf);
1079         fputs(s->buf.buf, stdout);
1080         for (;;) {
1081                 if (hunk_index >= file_diff->hunk_nr)
1082                         hunk_index = 0;
1083                 hunk = file_diff->hunk + hunk_index;
1084
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;
1089                                 break;
1090                         }
1091
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) {
1095                                 undecided_next = i;
1096                                 break;
1097                         }
1098
1099                 /* Everything decided? */
1100                 if (undecided_previous < 0 && undecided_next < 0 &&
1101                     hunk->use != UNDECIDED_HUNK)
1102                         break;
1103
1104                 strbuf_reset(&s->buf);
1105                 render_hunk(s, hunk, 0, colored, &s->buf);
1106                 fputs(s->buf.buf, stdout);
1107
1108                 strbuf_reset(&s->buf);
1109                 if (undecided_previous >= 0)
1110                         strbuf_addstr(&s->buf, ",k");
1111                 if (hunk_index)
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");
1124
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;
1129                 else
1130                         prompt_mode_type = PROMPT_HUNK;
1131
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]),
1138                               s->buf.buf);
1139                 fflush(stdout);
1140                 if (strbuf_getline(&s->answer, stdin) == EOF)
1141                         break;
1142                 strbuf_trim_trailing_newline(&s->answer);
1143
1144                 if (!s->answer.len)
1145                         continue;
1146                 ch = tolower(s->answer.buf[0]);
1147                 if (ch == 'y') {
1148                         hunk->use = USE_HUNK;
1149 soft_increment:
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;
1160                         }
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;
1166                         }
1167                         if (ch == 'q') {
1168                                 quit = 1;
1169                                 break;
1170                         }
1171                 } else if (s->answer.buf[0] == 'K') {
1172                         if (hunk_index)
1173                                 hunk_index--;
1174                         else
1175                                 err(s, _("No previous hunk"));
1176                 } else if (s->answer.buf[0] == 'J') {
1177                         if (hunk_index + 1 < file_diff->hunk_nr)
1178                                 hunk_index++;
1179                         else
1180                                 err(s, _("No next hunk"));
1181                 } else if (s->answer.buf[0] == 'k') {
1182                         if (undecided_previous >= 0)
1183                                 hunk_index = undecided_previous;
1184                         else
1185                                 err(s, _("No previous hunk"));
1186                 } else if (s->answer.buf[0] == 'j') {
1187                         if (undecided_next >= 0)
1188                                 hunk_index = undecided_next;
1189                         else
1190                                 err(s, _("No next hunk"));
1191                 } else if (s->answer.buf[0] == 'g') {
1192                         char *pend;
1193                         unsigned long response;
1194
1195                         if (file_diff->hunk_nr < 2) {
1196                                 err(s, _("No other hunks to goto"));
1197                                 continue;
1198                         }
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? "));
1209                                 fflush(stdout);
1210                                 if (strbuf_getline(&s->answer,
1211                                                    stdin) == EOF)
1212                                         break;
1213                                 strbuf_trim_trailing_newline(&s->answer);
1214                         }
1215
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'"),
1220                                     s->answer.buf);
1221                         else if (0 < response && response <= file_diff->hunk_nr)
1222                                 hunk_index = response - 1;
1223                         else
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] == '/') {
1229                         regex_t regex;
1230                         int ret;
1231
1232                         if (file_diff->hunk_nr < 2) {
1233                                 err(s, _("No other hunks to search"));
1234                                 continue;
1235                         }
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? "));
1240                                 fflush(stdout);
1241                                 if (strbuf_getline(&s->answer,
1242                                                    stdin) == EOF)
1243                                         break;
1244                                 strbuf_trim_trailing_newline(&s->answer);
1245                                 if (s->answer.len == 0)
1246                                         continue;
1247                         }
1248                         ret = regcomp(&regex, s->answer.buf,
1249                                       REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1250                         if (ret) {
1251                                 char errbuf[1024];
1252
1253                                 regerror(ret, &regex, errbuf, sizeof(errbuf));
1254                                 err(s, _("Malformed search regexp %s: %s"),
1255                                     s->answer.buf, errbuf);
1256                                 continue;
1257                         }
1258                         i = hunk_index;
1259                         for (;;) {
1260                                 /* render the hunk into a scratch buffer */
1261                                 render_hunk(s, file_diff->hunk + i, 0, 0,
1262                                             &s->buf);
1263                                 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1264                                     != REG_NOMATCH)
1265                                         break;
1266                                 i++;
1267                                 if (i == file_diff->hunk_nr)
1268                                         i = 0;
1269                                 if (i != hunk_index)
1270                                         continue;
1271                                 err(s, _("No hunk matches the given pattern"));
1272                                 break;
1273                         }
1274                         hunk_index = i;
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;
1290                         }
1291                 } else {
1292                         const char *p = _(help_patch_remainder), *eol = p;
1293
1294                         color_fprintf(stdout, s->s.help_color, "%s",
1295                                       _(s->mode->help_patch_text));
1296
1297                         /*
1298                          * Show only those lines of the remainder that are
1299                          * actually applicable with the current hunk.
1300                          */
1301                         for (; *p; p = eol + (*eol == '\n')) {
1302                                 eol = strchrnul(p, '\n');
1303
1304                                 /*
1305                                  * `s->buf` still contains the part of the
1306                                  * commands shown in the prompt that are not
1307                                  * always available.
1308                                  */
1309                                 if (*p != '?' && !strchr(s->buf.buf, *p))
1310                                         continue;
1311
1312                                 color_fprintf_ln(stdout, s->s.help_color,
1313                                                  "%.*s", (int)(eol - p), p);
1314                         }
1315                 }
1316         }
1317
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)
1321                         break;
1322
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);
1327
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,
1332                                  NULL, 0, NULL, 0))
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);
1337         }
1338
1339         putchar('\n');
1340         return quit;
1341 }
1342
1343 int run_add_p(struct repository *r, enum add_p_mode mode,
1344               const char *revision, const struct pathspec *ps)
1345 {
1346         struct add_p_state s = {
1347                 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1348         };
1349         size_t i, binary_count = 0;
1350
1351         init_add_i_state(&s.s, r);
1352
1353         s.mode = &patch_mode_add;
1354         s.revision = revision;
1355
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);
1362                 return -1;
1363         }
1364
1365         for (i = 0; i < s.file_diff_nr; i++)
1366                 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1367                         binary_count++;
1368                 else if (patch_update_file(&s, s.file_diff + i))
1369                         break;
1370
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"));
1375
1376         strbuf_release(&s.answer);
1377         strbuf_release(&s.buf);
1378         strbuf_release(&s.plain);
1379         strbuf_release(&s.colored);
1380         return 0;
1381 }