Merge branch 'jt/cdn-offload'
[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 #include "compat/terminal.h"
10 #include "prompt.h"
11
12 enum prompt_mode_type {
13         PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_ADDITION, PROMPT_HUNK,
14         PROMPT_MODE_MAX, /* must be last */
15 };
16
17 struct patch_mode {
18         /*
19          * The magic constant 4 is chosen such that all patch modes
20          * provide enough space for three command-line arguments followed by a
21          * trailing `NULL`.
22          */
23         const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
24         unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
25         const char *prompt_mode[PROMPT_MODE_MAX];
26         const char *edit_hunk_hint, *help_patch_text;
27 };
28
29 static struct patch_mode patch_mode_add = {
30         .diff_cmd = { "diff-files", NULL },
31         .apply_args = { "--cached", NULL },
32         .apply_check_args = { "--cached", NULL },
33         .prompt_mode = {
34                 N_("Stage mode change [y,n,q,a,d%s,?]? "),
35                 N_("Stage deletion [y,n,q,a,d%s,?]? "),
36                 N_("Stage addition [y,n,q,a,d%s,?]? "),
37                 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
38         },
39         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
40                              "will immediately be marked for staging."),
41         .help_patch_text =
42                 N_("y - stage this hunk\n"
43                    "n - do not stage this hunk\n"
44                    "q - quit; do not stage this hunk or any of the remaining "
45                         "ones\n"
46                    "a - stage this hunk and all later hunks in the file\n"
47                    "d - do not stage this hunk or any of the later hunks in "
48                         "the file\n")
49 };
50
51 static struct patch_mode patch_mode_stash = {
52         .diff_cmd = { "diff-index", "HEAD", NULL },
53         .apply_args = { "--cached", NULL },
54         .apply_check_args = { "--cached", NULL },
55         .prompt_mode = {
56                 N_("Stash mode change [y,n,q,a,d%s,?]? "),
57                 N_("Stash deletion [y,n,q,a,d%s,?]? "),
58                 N_("Stash addition [y,n,q,a,d%s,?]? "),
59                 N_("Stash this hunk [y,n,q,a,d%s,?]? "),
60         },
61         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
62                              "will immediately be marked for stashing."),
63         .help_patch_text =
64                 N_("y - stash this hunk\n"
65                    "n - do not stash this hunk\n"
66                    "q - quit; do not stash this hunk or any of the remaining "
67                         "ones\n"
68                    "a - stash this hunk and all later hunks in the file\n"
69                    "d - do not stash this hunk or any of the later hunks in "
70                         "the file\n"),
71 };
72
73 static struct patch_mode patch_mode_reset_head = {
74         .diff_cmd = { "diff-index", "--cached", NULL },
75         .apply_args = { "-R", "--cached", NULL },
76         .apply_check_args = { "-R", "--cached", NULL },
77         .is_reverse = 1,
78         .index_only = 1,
79         .prompt_mode = {
80                 N_("Unstage mode change [y,n,q,a,d%s,?]? "),
81                 N_("Unstage deletion [y,n,q,a,d%s,?]? "),
82                 N_("Unstage addition [y,n,q,a,d%s,?]? "),
83                 N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
84         },
85         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
86                              "will immediately be marked for unstaging."),
87         .help_patch_text =
88                 N_("y - unstage this hunk\n"
89                    "n - do not unstage this hunk\n"
90                    "q - quit; do not unstage this hunk or any of the remaining "
91                         "ones\n"
92                    "a - unstage this hunk and all later hunks in the file\n"
93                    "d - do not unstage this hunk or any of the later hunks in "
94                         "the file\n"),
95 };
96
97 static struct patch_mode patch_mode_reset_nothead = {
98         .diff_cmd = { "diff-index", "-R", "--cached", NULL },
99         .apply_args = { "--cached", NULL },
100         .apply_check_args = { "--cached", NULL },
101         .index_only = 1,
102         .prompt_mode = {
103                 N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
104                 N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
105                 N_("Apply addition to index [y,n,q,a,d%s,?]? "),
106                 N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
107         },
108         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
109                              "will immediately be marked for applying."),
110         .help_patch_text =
111                 N_("y - apply this hunk to index\n"
112                    "n - do not apply this hunk to index\n"
113                    "q - quit; do not apply this hunk or any of the remaining "
114                         "ones\n"
115                    "a - apply this hunk and all later hunks in the file\n"
116                    "d - do not apply this hunk or any of the later hunks in "
117                         "the file\n"),
118 };
119
120 static struct patch_mode patch_mode_checkout_index = {
121         .diff_cmd = { "diff-files", NULL },
122         .apply_args = { "-R", NULL },
123         .apply_check_args = { "-R", NULL },
124         .is_reverse = 1,
125         .prompt_mode = {
126                 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
127                 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
128                 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
129                 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
130         },
131         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
132                              "will immediately be marked for discarding."),
133         .help_patch_text =
134                 N_("y - discard this hunk from worktree\n"
135                    "n - do not discard this hunk from worktree\n"
136                    "q - quit; do not discard this hunk or any of the remaining "
137                         "ones\n"
138                    "a - discard this hunk and all later hunks in the file\n"
139                    "d - do not discard this hunk or any of the later hunks in "
140                         "the file\n"),
141 };
142
143 static struct patch_mode patch_mode_checkout_head = {
144         .diff_cmd = { "diff-index", NULL },
145         .apply_for_checkout = 1,
146         .apply_check_args = { "-R", NULL },
147         .is_reverse = 1,
148         .prompt_mode = {
149                 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
150                 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
151                 N_("Discard addition from index and worktree [y,n,q,a,d%s,?]? "),
152                 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
153         },
154         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
155                              "will immediately be marked for discarding."),
156         .help_patch_text =
157                 N_("y - discard this hunk from index and worktree\n"
158                    "n - do not discard this hunk from index and worktree\n"
159                    "q - quit; do not discard this hunk or any of the remaining "
160                         "ones\n"
161                    "a - discard this hunk and all later hunks in the file\n"
162                    "d - do not discard this hunk or any of the later hunks in "
163                         "the file\n"),
164 };
165
166 static struct patch_mode patch_mode_checkout_nothead = {
167         .diff_cmd = { "diff-index", "-R", NULL },
168         .apply_for_checkout = 1,
169         .apply_check_args = { NULL },
170         .prompt_mode = {
171                 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
172                 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
173                 N_("Apply addition to index and worktree [y,n,q,a,d%s,?]? "),
174                 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
175         },
176         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
177                              "will immediately be marked for applying."),
178         .help_patch_text =
179                 N_("y - apply this hunk to index and worktree\n"
180                    "n - do not apply this hunk to index and worktree\n"
181                    "q - quit; do not apply this hunk or any of the remaining "
182                         "ones\n"
183                    "a - apply this hunk and all later hunks in the file\n"
184                    "d - do not apply this hunk or any of the later hunks in "
185                         "the file\n"),
186 };
187
188 static struct patch_mode patch_mode_worktree_head = {
189         .diff_cmd = { "diff-index", NULL },
190         .apply_args = { "-R", NULL },
191         .apply_check_args = { "-R", NULL },
192         .is_reverse = 1,
193         .prompt_mode = {
194                 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
195                 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
196                 N_("Discard addition from index and worktree [y,n,q,a,d%s,?]? "),
197                 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
198         },
199         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
200                              "will immediately be marked for discarding."),
201         .help_patch_text =
202                 N_("y - discard this hunk from worktree\n"
203                    "n - do not discard this hunk from worktree\n"
204                    "q - quit; do not discard this hunk or any of the remaining "
205                         "ones\n"
206                    "a - discard this hunk and all later hunks in the file\n"
207                    "d - do not discard this hunk or any of the later hunks in "
208                         "the file\n"),
209 };
210
211 static struct patch_mode patch_mode_worktree_nothead = {
212         .diff_cmd = { "diff-index", "-R", NULL },
213         .apply_args = { NULL },
214         .apply_check_args = { NULL },
215         .prompt_mode = {
216                 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
217                 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
218                 N_("Apply addition to index and worktree [y,n,q,a,d%s,?]? "),
219                 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
220         },
221         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
222                              "will immediately be marked for applying."),
223         .help_patch_text =
224                 N_("y - apply this hunk to worktree\n"
225                    "n - do not apply this hunk to worktree\n"
226                    "q - quit; do not apply this hunk or any of the remaining "
227                         "ones\n"
228                    "a - apply this hunk and all later hunks in the file\n"
229                    "d - do not apply this hunk or any of the later hunks in "
230                         "the file\n"),
231 };
232
233 struct hunk_header {
234         unsigned long old_offset, old_count, new_offset, new_count;
235         /*
236          * Start/end offsets to the extra text after the second `@@` in the
237          * hunk header, e.g. the function signature. This is expected to
238          * include the newline.
239          */
240         size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
241 };
242
243 struct hunk {
244         size_t start, end, colored_start, colored_end, splittable_into;
245         ssize_t delta;
246         enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
247         struct hunk_header header;
248 };
249
250 struct add_p_state {
251         struct add_i_state s;
252         struct strbuf answer, buf;
253
254         /* parsed diff */
255         struct strbuf plain, colored;
256         struct file_diff {
257                 struct hunk head;
258                 struct hunk *hunk;
259                 size_t hunk_nr, hunk_alloc;
260                 unsigned deleted:1, added:1, mode_change:1,binary:1;
261         } *file_diff;
262         size_t file_diff_nr;
263
264         /* patch mode */
265         struct patch_mode *mode;
266         const char *revision;
267 };
268
269 static void err(struct add_p_state *s, const char *fmt, ...)
270 {
271         va_list args;
272
273         va_start(args, fmt);
274         fputs(s->s.error_color, stderr);
275         vfprintf(stderr, fmt, args);
276         fputs(s->s.reset_color, stderr);
277         fputc('\n', stderr);
278         va_end(args);
279 }
280
281 static void setup_child_process(struct add_p_state *s,
282                                 struct child_process *cp, ...)
283 {
284         va_list ap;
285         const char *arg;
286
287         va_start(ap, cp);
288         while ((arg = va_arg(ap, const char *)))
289                 argv_array_push(&cp->args, arg);
290         va_end(ap);
291
292         cp->git_cmd = 1;
293         argv_array_pushf(&cp->env_array,
294                          INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
295 }
296
297 static int parse_range(const char **p,
298                        unsigned long *offset, unsigned long *count)
299 {
300         char *pend;
301
302         *offset = strtoul(*p, &pend, 10);
303         if (pend == *p)
304                 return -1;
305         if (*pend != ',') {
306                 *count = 1;
307                 *p = pend;
308                 return 0;
309         }
310         *count = strtoul(pend + 1, (char **)p, 10);
311         return *p == pend + 1 ? -1 : 0;
312 }
313
314 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
315 {
316         struct hunk_header *header = &hunk->header;
317         const char *line = s->plain.buf + hunk->start, *p = line;
318         char *eol = memchr(p, '\n', s->plain.len - hunk->start);
319
320         if (!eol)
321                 eol = s->plain.buf + s->plain.len;
322
323         if (!skip_prefix(p, "@@ -", &p) ||
324             parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
325             !skip_prefix(p, " +", &p) ||
326             parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
327             !skip_prefix(p, " @@", &p))
328                 return error(_("could not parse hunk header '%.*s'"),
329                              (int)(eol - line), line);
330
331         hunk->start = eol - s->plain.buf + (*eol == '\n');
332         header->extra_start = p - s->plain.buf;
333         header->extra_end = hunk->start;
334
335         if (!s->colored.len) {
336                 header->colored_extra_start = header->colored_extra_end = 0;
337                 return 0;
338         }
339
340         /* Now find the extra text in the colored diff */
341         line = s->colored.buf + hunk->colored_start;
342         eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
343         if (!eol)
344                 eol = s->colored.buf + s->colored.len;
345         p = memmem(line, eol - line, "@@ -", 4);
346         if (!p)
347                 return error(_("could not parse colored hunk header '%.*s'"),
348                              (int)(eol - line), line);
349         p = memmem(p + 4, eol - p - 4, " @@", 3);
350         if (!p)
351                 return error(_("could not parse colored hunk header '%.*s'"),
352                              (int)(eol - line), line);
353         hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
354         header->colored_extra_start = p + 3 - s->colored.buf;
355         header->colored_extra_end = hunk->colored_start;
356
357         return 0;
358 }
359
360 static int is_octal(const char *p, size_t len)
361 {
362         if (!len)
363                 return 0;
364
365         while (len--)
366                 if (*p < '0' || *(p++) > '7')
367                         return 0;
368         return 1;
369 }
370
371 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
372 {
373         struct argv_array args = ARGV_ARRAY_INIT;
374         const char *diff_algorithm = s->s.interactive_diff_algorithm;
375         struct strbuf *plain = &s->plain, *colored = NULL;
376         struct child_process cp = CHILD_PROCESS_INIT;
377         char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
378         size_t file_diff_alloc = 0, i, color_arg_index;
379         struct file_diff *file_diff = NULL;
380         struct hunk *hunk = NULL;
381         int res;
382
383         argv_array_pushv(&args, s->mode->diff_cmd);
384         if (diff_algorithm)
385                 argv_array_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
386         if (s->revision) {
387                 struct object_id oid;
388                 argv_array_push(&args,
389                                 /* could be on an unborn branch */
390                                 !strcmp("HEAD", s->revision) &&
391                                 get_oid("HEAD", &oid) ?
392                                 empty_tree_oid_hex() : s->revision);
393         }
394         color_arg_index = args.argc;
395         /* Use `--no-color` explicitly, just in case `diff.color = always`. */
396         argv_array_pushl(&args, "--no-color", "-p", "--", NULL);
397         for (i = 0; i < ps->nr; i++)
398                 argv_array_push(&args, ps->items[i].original);
399
400         setup_child_process(s, &cp, NULL);
401         cp.argv = args.argv;
402         res = capture_command(&cp, plain, 0);
403         if (res) {
404                 argv_array_clear(&args);
405                 return error(_("could not parse diff"));
406         }
407         if (!plain->len) {
408                 argv_array_clear(&args);
409                 return 0;
410         }
411         strbuf_complete_line(plain);
412
413         if (want_color_fd(1, -1)) {
414                 struct child_process colored_cp = CHILD_PROCESS_INIT;
415                 const char *diff_filter = s->s.interactive_diff_filter;
416
417                 setup_child_process(s, &colored_cp, NULL);
418                 xsnprintf((char *)args.argv[color_arg_index], 8, "--color");
419                 colored_cp.argv = args.argv;
420                 colored = &s->colored;
421                 res = capture_command(&colored_cp, colored, 0);
422                 argv_array_clear(&args);
423                 if (res)
424                         return error(_("could not parse colored diff"));
425
426                 if (diff_filter) {
427                         struct child_process filter_cp = CHILD_PROCESS_INIT;
428
429                         setup_child_process(s, &filter_cp,
430                                             diff_filter, NULL);
431                         filter_cp.git_cmd = 0;
432                         filter_cp.use_shell = 1;
433                         strbuf_reset(&s->buf);
434                         if (pipe_command(&filter_cp,
435                                          colored->buf, colored->len,
436                                          &s->buf, colored->len,
437                                          NULL, 0) < 0)
438                                 return error(_("failed to run '%s'"),
439                                              diff_filter);
440                         strbuf_swap(colored, &s->buf);
441                 }
442
443                 strbuf_complete_line(colored);
444                 colored_p = colored->buf;
445                 colored_pend = colored_p + colored->len;
446         }
447         argv_array_clear(&args);
448
449         /* parse files and hunks */
450         p = plain->buf;
451         pend = p + plain->len;
452         while (p != pend) {
453                 char *eol = memchr(p, '\n', pend - p);
454                 const char *deleted = NULL, *added = NULL, *mode_change = NULL;
455
456                 if (!eol)
457                         eol = pend;
458
459                 if (starts_with(p, "diff ")) {
460                         s->file_diff_nr++;
461                         ALLOC_GROW(s->file_diff, s->file_diff_nr,
462                                    file_diff_alloc);
463                         file_diff = s->file_diff + s->file_diff_nr - 1;
464                         memset(file_diff, 0, sizeof(*file_diff));
465                         hunk = &file_diff->head;
466                         hunk->start = p - plain->buf;
467                         if (colored_p)
468                                 hunk->colored_start = colored_p - colored->buf;
469                         marker = '\0';
470                 } else if (p == plain->buf)
471                         BUG("diff starts with unexpected line:\n"
472                             "%.*s\n", (int)(eol - p), p);
473                 else if (file_diff->deleted || file_diff->added)
474                         ; /* keep the rest of the file in a single "hunk" */
475                 else if (starts_with(p, "@@ ") ||
476                          (hunk == &file_diff->head &&
477                           (skip_prefix(p, "deleted file", &deleted) ||
478                            skip_prefix(p, "new file", &added)))) {
479                         if (marker == '-' || marker == '+')
480                                 /*
481                                  * Should not happen; previous hunk did not end
482                                  * in a context line? Handle it anyway.
483                                  */
484                                 hunk->splittable_into++;
485
486                         file_diff->hunk_nr++;
487                         ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
488                                    file_diff->hunk_alloc);
489                         hunk = file_diff->hunk + file_diff->hunk_nr - 1;
490                         memset(hunk, 0, sizeof(*hunk));
491
492                         hunk->start = p - plain->buf;
493                         if (colored)
494                                 hunk->colored_start = colored_p - colored->buf;
495
496                         if (deleted)
497                                 file_diff->deleted = 1;
498                         else if (added)
499                                 file_diff->added = 1;
500                         else if (parse_hunk_header(s, hunk) < 0)
501                                 return -1;
502
503                         /*
504                          * Start counting into how many hunks this one can be
505                          * split
506                          */
507                         marker = *p;
508                 } else if (hunk == &file_diff->head &&
509                            skip_prefix(p, "old mode ", &mode_change) &&
510                            is_octal(mode_change, eol - mode_change)) {
511                         if (file_diff->mode_change)
512                                 BUG("double mode change?\n\n%.*s",
513                                     (int)(eol - plain->buf), plain->buf);
514                         if (file_diff->hunk_nr++)
515                                 BUG("mode change in the middle?\n\n%.*s",
516                                     (int)(eol - plain->buf), plain->buf);
517
518                         /*
519                          * Do *not* change `hunk`: the mode change pseudo-hunk
520                          * is _part of_ the header "hunk".
521                          */
522                         file_diff->mode_change = 1;
523                         ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
524                                    file_diff->hunk_alloc);
525                         memset(file_diff->hunk, 0, sizeof(struct hunk));
526                         file_diff->hunk->start = p - plain->buf;
527                         if (colored_p)
528                                 file_diff->hunk->colored_start =
529                                         colored_p - colored->buf;
530                 } else if (hunk == &file_diff->head &&
531                            skip_prefix(p, "new mode ", &mode_change) &&
532                            is_octal(mode_change, eol - mode_change)) {
533
534                         /*
535                          * Extend the "mode change" pseudo-hunk to include also
536                          * the "new mode" line.
537                          */
538                         if (!file_diff->mode_change)
539                                 BUG("'new mode' without 'old mode'?\n\n%.*s",
540                                     (int)(eol - plain->buf), plain->buf);
541                         if (file_diff->hunk_nr != 1)
542                                 BUG("mode change in the middle?\n\n%.*s",
543                                     (int)(eol - plain->buf), plain->buf);
544                         if (p - plain->buf != file_diff->hunk->end)
545                                 BUG("'new mode' does not immediately follow "
546                                     "'old mode'?\n\n%.*s",
547                                     (int)(eol - plain->buf), plain->buf);
548                 } else if (hunk == &file_diff->head &&
549                            starts_with(p, "Binary files "))
550                         file_diff->binary = 1;
551
552                 if (!!file_diff->deleted + !!file_diff->added +
553                     !!file_diff->mode_change > 1)
554                         BUG("diff can only contain delete *or* add *or* a "
555                             "mode change?!?\n%.*s",
556                             (int)(eol - (plain->buf + file_diff->head.start)),
557                             plain->buf + file_diff->head.start);
558
559                 if ((marker == '-' || marker == '+') && *p == ' ')
560                         hunk->splittable_into++;
561                 if (marker && *p != '\\')
562                         marker = *p;
563
564                 p = eol == pend ? pend : eol + 1;
565                 hunk->end = p - plain->buf;
566
567                 if (colored) {
568                         char *colored_eol = memchr(colored_p, '\n',
569                                                    colored_pend - colored_p);
570                         if (colored_eol)
571                                 colored_p = colored_eol + 1;
572                         else if (p != pend)
573                                 /* colored shorter than non-colored? */
574                                 goto mismatched_output;
575                         else
576                                 colored_p = colored_pend;
577
578                         hunk->colored_end = colored_p - colored->buf;
579                 }
580
581                 if (mode_change) {
582                         if (file_diff->hunk_nr != 1)
583                                 BUG("mode change in hunk #%d???",
584                                     (int)file_diff->hunk_nr);
585                         /* Adjust the end of the "mode change" pseudo-hunk */
586                         file_diff->hunk->end = hunk->end;
587                         if (colored)
588                                 file_diff->hunk->colored_end = hunk->colored_end;
589                 }
590         }
591
592         if (marker == '-' || marker == '+')
593                 /*
594                  * Last hunk ended in non-context line (i.e. it appended lines
595                  * to the file, so there are no trailing context lines).
596                  */
597                 hunk->splittable_into++;
598
599         /* non-colored shorter than colored? */
600         if (colored_p != colored_pend) {
601 mismatched_output:
602                 error(_("mismatched output from interactive.diffFilter"));
603                 advise(_("Your filter must maintain a one-to-one correspondence\n"
604                          "between its input and output lines."));
605                 return -1;
606         }
607
608         return 0;
609 }
610
611 static size_t find_next_line(struct strbuf *sb, size_t offset)
612 {
613         char *eol;
614
615         if (offset >= sb->len)
616                 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
617                     (int)offset, (int)sb->len, sb->buf);
618
619         eol = memchr(sb->buf + offset, '\n', sb->len - offset);
620         if (!eol)
621                 return sb->len;
622         return eol - sb->buf + 1;
623 }
624
625 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
626                         ssize_t delta, int colored, struct strbuf *out)
627 {
628         struct hunk_header *header = &hunk->header;
629
630         if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
631                 /*
632                  * Generate the hunk header dynamically, except for special
633                  * hunks (such as the diff header).
634                  */
635                 const char *p;
636                 size_t len;
637                 unsigned long old_offset = header->old_offset;
638                 unsigned long new_offset = header->new_offset;
639
640                 if (!colored) {
641                         p = s->plain.buf + header->extra_start;
642                         len = header->extra_end - header->extra_start;
643                 } else {
644                         strbuf_addstr(out, s->s.fraginfo_color);
645                         p = s->colored.buf + header->colored_extra_start;
646                         len = header->colored_extra_end
647                                 - header->colored_extra_start;
648                 }
649
650                 if (s->mode->is_reverse)
651                         old_offset -= delta;
652                 else
653                         new_offset += delta;
654
655                 strbuf_addf(out, "@@ -%lu,%lu +%lu,%lu @@",
656                             old_offset, header->old_count,
657                             new_offset, header->new_count);
658                 if (len)
659                         strbuf_add(out, p, len);
660                 else if (colored)
661                         strbuf_addf(out, "%s\n", GIT_COLOR_RESET);
662                 else
663                         strbuf_addch(out, '\n');
664         }
665
666         if (colored)
667                 strbuf_add(out, s->colored.buf + hunk->colored_start,
668                            hunk->colored_end - hunk->colored_start);
669         else
670                 strbuf_add(out, s->plain.buf + hunk->start,
671                            hunk->end - hunk->start);
672 }
673
674 static void render_diff_header(struct add_p_state *s,
675                                struct file_diff *file_diff, int colored,
676                                struct strbuf *out)
677 {
678         /*
679          * If there was a mode change, the first hunk is a pseudo hunk that
680          * corresponds to the mode line in the header. If the user did not want
681          * to stage that "hunk", we actually have to cut it out from the header.
682          */
683         int skip_mode_change =
684                 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
685         struct hunk *head = &file_diff->head, *first = file_diff->hunk;
686
687         if (!skip_mode_change) {
688                 render_hunk(s, head, 0, colored, out);
689                 return;
690         }
691
692         if (colored) {
693                 const char *p = s->colored.buf;
694
695                 strbuf_add(out, p + head->colored_start,
696                             first->colored_start - head->colored_start);
697                 strbuf_add(out, p + first->colored_end,
698                             head->colored_end - first->colored_end);
699         } else {
700                 const char *p = s->plain.buf;
701
702                 strbuf_add(out, p + head->start, first->start - head->start);
703                 strbuf_add(out, p + first->end, head->end - first->end);
704         }
705 }
706
707 /* Coalesce hunks again that were split */
708 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
709                        size_t *hunk_index, int use_all, struct hunk *merged)
710 {
711         size_t i = *hunk_index, delta;
712         struct hunk *hunk = file_diff->hunk + i;
713         /* `header` corresponds to the merged hunk */
714         struct hunk_header *header = &merged->header, *next;
715
716         if (!use_all && hunk->use != USE_HUNK)
717                 return 0;
718
719         *merged = *hunk;
720         /* We simply skip the colored part (if any) when merging hunks */
721         merged->colored_start = merged->colored_end = 0;
722
723         for (; i + 1 < file_diff->hunk_nr; i++) {
724                 hunk++;
725                 next = &hunk->header;
726
727                 /*
728                  * Stop merging hunks when:
729                  *
730                  * - the hunk is not selected for use, or
731                  * - the hunk does not overlap with the already-merged hunk(s)
732                  */
733                 if ((!use_all && hunk->use != USE_HUNK) ||
734                     header->new_offset >= next->new_offset + merged->delta ||
735                     header->new_offset + header->new_count
736                     < next->new_offset + merged->delta)
737                         break;
738
739                 /*
740                  * If the hunks were not edited, and overlap, we can simply
741                  * extend the line range.
742                  */
743                 if (merged->start < hunk->start && merged->end > hunk->start) {
744                         merged->end = hunk->end;
745                         merged->colored_end = hunk->colored_end;
746                         delta = 0;
747                 } else {
748                         const char *plain = s->plain.buf;
749                         size_t  overlapping_line_count = header->new_offset
750                                 + header->new_count - merged->delta
751                                 - next->new_offset;
752                         size_t overlap_end = hunk->start;
753                         size_t overlap_start = overlap_end;
754                         size_t overlap_next, len, j;
755
756                         /*
757                          * One of the hunks was edited: the modified hunk was
758                          * appended to the strbuf `s->plain`.
759                          *
760                          * Let's ensure that at least the last context line of
761                          * the first hunk overlaps with the corresponding line
762                          * of the second hunk, and then merge.
763                          */
764                         for (j = 0; j < overlapping_line_count; j++) {
765                                 overlap_next = find_next_line(&s->plain,
766                                                               overlap_end);
767
768                                 if (overlap_next > hunk->end)
769                                         BUG("failed to find %d context lines "
770                                             "in:\n%.*s",
771                                             (int)overlapping_line_count,
772                                             (int)(hunk->end - hunk->start),
773                                             plain + hunk->start);
774
775                                 if (plain[overlap_end] != ' ')
776                                         return error(_("expected context line "
777                                                        "#%d in\n%.*s"),
778                                                      (int)(j + 1),
779                                                      (int)(hunk->end
780                                                            - hunk->start),
781                                                      plain + hunk->start);
782
783                                 overlap_start = overlap_end;
784                                 overlap_end = overlap_next;
785                         }
786                         len = overlap_end - overlap_start;
787
788                         if (len > merged->end - merged->start ||
789                             memcmp(plain + merged->end - len,
790                                    plain + overlap_start, len))
791                                 return error(_("hunks do not overlap:\n%.*s\n"
792                                                "\tdoes not end with:\n%.*s"),
793                                              (int)(merged->end - merged->start),
794                                              plain + merged->start,
795                                              (int)len, plain + overlap_start);
796
797                         /*
798                          * Since the start-end ranges are not adjacent, we
799                          * cannot simply take the union of the ranges. To
800                          * address that, we temporarily append the union of the
801                          * lines to the `plain` strbuf.
802                          */
803                         if (merged->end != s->plain.len) {
804                                 size_t start = s->plain.len;
805
806                                 strbuf_add(&s->plain, plain + merged->start,
807                                            merged->end - merged->start);
808                                 plain = s->plain.buf;
809                                 merged->start = start;
810                                 merged->end = s->plain.len;
811                         }
812
813                         strbuf_add(&s->plain,
814                                    plain + overlap_end,
815                                    hunk->end - overlap_end);
816                         merged->end = s->plain.len;
817                         merged->splittable_into += hunk->splittable_into;
818                         delta = merged->delta;
819                         merged->delta += hunk->delta;
820                 }
821
822                 header->old_count = next->old_offset + next->old_count
823                         - header->old_offset;
824                 header->new_count = next->new_offset + delta
825                         + next->new_count - header->new_offset;
826         }
827
828         if (i == *hunk_index)
829                 return 0;
830
831         *hunk_index = i;
832         return 1;
833 }
834
835 static void reassemble_patch(struct add_p_state *s,
836                              struct file_diff *file_diff, int use_all,
837                              struct strbuf *out)
838 {
839         struct hunk *hunk;
840         size_t save_len = s->plain.len, i;
841         ssize_t delta = 0;
842
843         render_diff_header(s, file_diff, 0, out);
844
845         for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
846                 struct hunk merged = { 0 };
847
848                 hunk = file_diff->hunk + i;
849                 if (!use_all && hunk->use != USE_HUNK)
850                         delta += hunk->header.old_count
851                                 - hunk->header.new_count;
852                 else {
853                         /* merge overlapping hunks into a temporary hunk */
854                         if (merge_hunks(s, file_diff, &i, use_all, &merged))
855                                 hunk = &merged;
856
857                         render_hunk(s, hunk, delta, 0, out);
858
859                         /*
860                          * In case `merge_hunks()` used `plain` as a scratch
861                          * pad (this happens when an edited hunk had to be
862                          * coalesced with another hunk).
863                          */
864                         strbuf_setlen(&s->plain, save_len);
865
866                         delta += hunk->delta;
867                 }
868         }
869 }
870
871 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
872                        size_t hunk_index)
873 {
874         int colored = !!s->colored.len, first = 1;
875         struct hunk *hunk = file_diff->hunk + hunk_index;
876         size_t splittable_into;
877         size_t end, colored_end, current, colored_current = 0, context_line_count;
878         struct hunk_header remaining, *header;
879         char marker, ch;
880
881         if (hunk_index >= file_diff->hunk_nr)
882                 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
883                     (int)hunk_index, (int)file_diff->hunk_nr);
884
885         if (hunk->splittable_into < 2)
886                 return 0;
887         splittable_into = hunk->splittable_into;
888
889         end = hunk->end;
890         colored_end = hunk->colored_end;
891
892         remaining = hunk->header;
893
894         file_diff->hunk_nr += splittable_into - 1;
895         ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
896         if (hunk_index + splittable_into < file_diff->hunk_nr)
897                 memmove(file_diff->hunk + hunk_index + splittable_into,
898                         file_diff->hunk + hunk_index + 1,
899                         (file_diff->hunk_nr - hunk_index - splittable_into)
900                         * sizeof(*hunk));
901         hunk = file_diff->hunk + hunk_index;
902         hunk->splittable_into = 1;
903         memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
904
905         header = &hunk->header;
906         header->old_count = header->new_count = 0;
907
908         current = hunk->start;
909         if (colored)
910                 colored_current = hunk->colored_start;
911         marker = '\0';
912         context_line_count = 0;
913
914         while (splittable_into > 1) {
915                 ch = s->plain.buf[current];
916
917                 if (!ch)
918                         BUG("buffer overrun while splitting hunks");
919
920                 /*
921                  * Is this the first context line after a chain of +/- lines?
922                  * Then record the start of the next split hunk.
923                  */
924                 if ((marker == '-' || marker == '+') && ch == ' ') {
925                         first = 0;
926                         hunk[1].start = current;
927                         if (colored)
928                                 hunk[1].colored_start = colored_current;
929                         context_line_count = 0;
930                 }
931
932                 /*
933                  * Was the previous line a +/- one? Alternatively, is this the
934                  * first line (and not a +/- one)?
935                  *
936                  * Then just increment the appropriate counter and continue
937                  * with the next line.
938                  */
939                 if (marker != ' ' || (ch != '-' && ch != '+')) {
940 next_hunk_line:
941                         /* Comment lines are attached to the previous line */
942                         if (ch == '\\')
943                                 ch = marker ? marker : ' ';
944
945                         /* current hunk not done yet */
946                         if (ch == ' ')
947                                 context_line_count++;
948                         else if (ch == '-')
949                                 header->old_count++;
950                         else if (ch == '+')
951                                 header->new_count++;
952                         else
953                                 BUG("unhandled diff marker: '%c'", ch);
954                         marker = ch;
955                         current = find_next_line(&s->plain, current);
956                         if (colored)
957                                 colored_current =
958                                         find_next_line(&s->colored,
959                                                        colored_current);
960                         continue;
961                 }
962
963                 /*
964                  * We got us the start of a new hunk!
965                  *
966                  * This is a context line, so it is shared with the previous
967                  * hunk, if any.
968                  */
969
970                 if (first) {
971                         if (header->old_count || header->new_count)
972                                 BUG("counts are off: %d/%d",
973                                     (int)header->old_count,
974                                     (int)header->new_count);
975
976                         header->old_count = context_line_count;
977                         header->new_count = context_line_count;
978                         context_line_count = 0;
979                         first = 0;
980                         goto next_hunk_line;
981                 }
982
983                 remaining.old_offset += header->old_count;
984                 remaining.old_count -= header->old_count;
985                 remaining.new_offset += header->new_count;
986                 remaining.new_count -= header->new_count;
987
988                 /* initialize next hunk header's offsets */
989                 hunk[1].header.old_offset =
990                         header->old_offset + header->old_count;
991                 hunk[1].header.new_offset =
992                         header->new_offset + header->new_count;
993
994                 /* add one split hunk */
995                 header->old_count += context_line_count;
996                 header->new_count += context_line_count;
997
998                 hunk->end = current;
999                 if (colored)
1000                         hunk->colored_end = colored_current;
1001
1002                 hunk++;
1003                 hunk->splittable_into = 1;
1004                 hunk->use = hunk[-1].use;
1005                 header = &hunk->header;
1006
1007                 header->old_count = header->new_count = context_line_count;
1008                 context_line_count = 0;
1009
1010                 splittable_into--;
1011                 marker = ch;
1012         }
1013
1014         /* last hunk simply gets the rest */
1015         if (header->old_offset != remaining.old_offset)
1016                 BUG("miscounted old_offset: %lu != %lu",
1017                     header->old_offset, remaining.old_offset);
1018         if (header->new_offset != remaining.new_offset)
1019                 BUG("miscounted new_offset: %lu != %lu",
1020                     header->new_offset, remaining.new_offset);
1021         header->old_count = remaining.old_count;
1022         header->new_count = remaining.new_count;
1023         hunk->end = end;
1024         if (colored)
1025                 hunk->colored_end = colored_end;
1026
1027         return 0;
1028 }
1029
1030 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1031 {
1032         const char *plain = s->plain.buf;
1033         size_t current, eol, next;
1034
1035         if (!s->colored.len)
1036                 return;
1037
1038         hunk->colored_start = s->colored.len;
1039         for (current = hunk->start; current < hunk->end; ) {
1040                 for (eol = current; eol < hunk->end; eol++)
1041                         if (plain[eol] == '\n')
1042                                 break;
1043                 next = eol + (eol < hunk->end);
1044                 if (eol > current && plain[eol - 1] == '\r')
1045                         eol--;
1046
1047                 strbuf_addstr(&s->colored,
1048                               plain[current] == '-' ?
1049                               s->s.file_old_color :
1050                               plain[current] == '+' ?
1051                               s->s.file_new_color :
1052                               s->s.context_color);
1053                 strbuf_add(&s->colored, plain + current, eol - current);
1054                 strbuf_addstr(&s->colored, GIT_COLOR_RESET);
1055                 if (next > eol)
1056                         strbuf_add(&s->colored, plain + eol, next - eol);
1057                 current = next;
1058         }
1059         hunk->colored_end = s->colored.len;
1060 }
1061
1062 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1063 {
1064         size_t i;
1065
1066         strbuf_reset(&s->buf);
1067         strbuf_commented_addf(&s->buf, _("Manual hunk edit mode -- see bottom for "
1068                                       "a quick guide.\n"));
1069         render_hunk(s, hunk, 0, 0, &s->buf);
1070         strbuf_commented_addf(&s->buf,
1071                               _("---\n"
1072                                 "To remove '%c' lines, make them ' ' lines "
1073                                 "(context).\n"
1074                                 "To remove '%c' lines, delete them.\n"
1075                                 "Lines starting with %c will be removed.\n"),
1076                               s->mode->is_reverse ? '+' : '-',
1077                               s->mode->is_reverse ? '-' : '+',
1078                               comment_line_char);
1079         strbuf_commented_addf(&s->buf, "%s", _(s->mode->edit_hunk_hint));
1080         /*
1081          * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1082          * messages.
1083          */
1084         strbuf_commented_addf(&s->buf,
1085                               _("If it does not apply cleanly, you will be "
1086                                 "given an opportunity to\n"
1087                                 "edit again.  If all lines of the hunk are "
1088                                 "removed, then the edit is\n"
1089                                 "aborted and the hunk is left unchanged.\n"));
1090
1091         if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1092                 return -1;
1093
1094         /* strip out commented lines */
1095         hunk->start = s->plain.len;
1096         for (i = 0; i < s->buf.len; ) {
1097                 size_t next = find_next_line(&s->buf, i);
1098
1099                 if (s->buf.buf[i] != comment_line_char)
1100                         strbuf_add(&s->plain, s->buf.buf + i, next - i);
1101                 i = next;
1102         }
1103
1104         hunk->end = s->plain.len;
1105         if (hunk->end == hunk->start)
1106                 /* The user aborted editing by deleting everything */
1107                 return 0;
1108
1109         recolor_hunk(s, hunk);
1110
1111         /*
1112          * If the hunk header is intact, parse it, otherwise simply use the
1113          * hunk header prior to editing (which will adjust `hunk->start` to
1114          * skip the hunk header).
1115          */
1116         if (s->plain.buf[hunk->start] == '@' &&
1117             parse_hunk_header(s, hunk) < 0)
1118                 return error(_("could not parse hunk header"));
1119
1120         return 1;
1121 }
1122
1123 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1124                                    size_t orig_old_count, size_t orig_new_count)
1125 {
1126         struct hunk_header *header = &hunk->header;
1127         size_t i;
1128
1129         header->old_count = header->new_count = 0;
1130         for (i = hunk->start; i < hunk->end; ) {
1131                 switch (s->plain.buf[i]) {
1132                 case '-':
1133                         header->old_count++;
1134                         break;
1135                 case '+':
1136                         header->new_count++;
1137                         break;
1138                 case ' ': case '\r': case '\n':
1139                         header->old_count++;
1140                         header->new_count++;
1141                         break;
1142                 }
1143
1144                 i = find_next_line(&s->plain, i);
1145         }
1146
1147         return orig_old_count - orig_new_count
1148                 - header->old_count + header->new_count;
1149 }
1150
1151 static int run_apply_check(struct add_p_state *s,
1152                            struct file_diff *file_diff)
1153 {
1154         struct child_process cp = CHILD_PROCESS_INIT;
1155
1156         strbuf_reset(&s->buf);
1157         reassemble_patch(s, file_diff, 1, &s->buf);
1158
1159         setup_child_process(s, &cp,
1160                             "apply", "--check", NULL);
1161         argv_array_pushv(&cp.args, s->mode->apply_check_args);
1162         if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1163                 return error(_("'git apply --cached' failed"));
1164
1165         return 0;
1166 }
1167
1168 static int read_single_character(struct add_p_state *s)
1169 {
1170         if (s->s.use_single_key) {
1171                 int res = read_key_without_echo(&s->answer);
1172                 printf("%s\n", res == EOF ? "" : s->answer.buf);
1173                 return res;
1174         }
1175
1176         if (git_read_line_interactively(&s->answer) == EOF)
1177                 return EOF;
1178         return 0;
1179 }
1180
1181 static int prompt_yesno(struct add_p_state *s, const char *prompt)
1182 {
1183         for (;;) {
1184                 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1185                 fflush(stdout);
1186                 if (read_single_character(s) == EOF)
1187                         return -1;
1188                 switch (tolower(s->answer.buf[0])) {
1189                 case 'n': return 0;
1190                 case 'y': return 1;
1191                 }
1192         }
1193 }
1194
1195 static int edit_hunk_loop(struct add_p_state *s,
1196                           struct file_diff *file_diff, struct hunk *hunk)
1197 {
1198         size_t plain_len = s->plain.len, colored_len = s->colored.len;
1199         struct hunk backup;
1200
1201         backup = *hunk;
1202
1203         for (;;) {
1204                 int res = edit_hunk_manually(s, hunk);
1205                 if (res == 0) {
1206                         /* abandonded */
1207                         *hunk = backup;
1208                         return -1;
1209                 }
1210
1211                 if (res > 0) {
1212                         hunk->delta +=
1213                                 recount_edited_hunk(s, hunk,
1214                                                     backup.header.old_count,
1215                                                     backup.header.new_count);
1216                         if (!run_apply_check(s, file_diff))
1217                                 return 0;
1218                 }
1219
1220                 /* Drop edits (they were appended to s->plain) */
1221                 strbuf_setlen(&s->plain, plain_len);
1222                 strbuf_setlen(&s->colored, colored_len);
1223                 *hunk = backup;
1224
1225                 /*
1226                  * TRANSLATORS: do not translate [y/n]
1227                  * The program will only accept that input at this point.
1228                  * Consider translating (saying "no" discards!) as
1229                  * (saying "n" for "no" discards!) if the translation
1230                  * of the word "no" does not start with n.
1231                  */
1232                 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1233                                         "Edit again (saying \"no\" discards!) "
1234                                         "[y/n]? "));
1235                 if (res < 1)
1236                         return -1;
1237         }
1238 }
1239
1240 static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1241                               int is_reverse)
1242 {
1243         const char *reverse = is_reverse ? "-R" : NULL;
1244         struct child_process check_index = CHILD_PROCESS_INIT;
1245         struct child_process check_worktree = CHILD_PROCESS_INIT;
1246         struct child_process apply_index = CHILD_PROCESS_INIT;
1247         struct child_process apply_worktree = CHILD_PROCESS_INIT;
1248         int applies_index, applies_worktree;
1249
1250         setup_child_process(s, &check_index,
1251                             "apply", "--cached", "--check", reverse, NULL);
1252         applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1253                                       NULL, 0, NULL, 0);
1254
1255         setup_child_process(s, &check_worktree,
1256                             "apply", "--check", reverse, NULL);
1257         applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1258                                          NULL, 0, NULL, 0);
1259
1260         if (applies_worktree && applies_index) {
1261                 setup_child_process(s, &apply_index,
1262                                     "apply", "--cached", reverse, NULL);
1263                 pipe_command(&apply_index, diff->buf, diff->len,
1264                              NULL, 0, NULL, 0);
1265
1266                 setup_child_process(s, &apply_worktree,
1267                                     "apply", reverse, NULL);
1268                 pipe_command(&apply_worktree, diff->buf, diff->len,
1269                              NULL, 0, NULL, 0);
1270
1271                 return 1;
1272         }
1273
1274         if (!applies_index) {
1275                 err(s, _("The selected hunks do not apply to the index!"));
1276                 if (prompt_yesno(s, _("Apply them to the worktree "
1277                                           "anyway? ")) > 0) {
1278                         setup_child_process(s, &apply_worktree,
1279                                             "apply", reverse, NULL);
1280                         return pipe_command(&apply_worktree, diff->buf,
1281                                             diff->len, NULL, 0, NULL, 0);
1282                 }
1283                 err(s, _("Nothing was applied.\n"));
1284         } else
1285                 /* As a last resort, show the diff to the user */
1286                 fwrite(diff->buf, diff->len, 1, stderr);
1287
1288         return 0;
1289 }
1290
1291 #define SUMMARY_HEADER_WIDTH 20
1292 #define SUMMARY_LINE_WIDTH 80
1293 static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1294                            struct strbuf *out)
1295 {
1296         struct hunk_header *header = &hunk->header;
1297         struct strbuf *plain = &s->plain;
1298         size_t len = out->len, i;
1299
1300         strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1301                     header->old_offset, header->old_count,
1302                     header->new_offset, header->new_count);
1303         if (out->len - len < SUMMARY_HEADER_WIDTH)
1304                 strbuf_addchars(out, ' ',
1305                                 SUMMARY_HEADER_WIDTH + len - out->len);
1306         for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1307                 if (plain->buf[i] != ' ')
1308                         break;
1309         if (i < hunk->end)
1310                 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1311         if (out->len - len > SUMMARY_LINE_WIDTH)
1312                 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1313         strbuf_complete_line(out);
1314 }
1315
1316 #define DISPLAY_HUNKS_LINES 20
1317 static size_t display_hunks(struct add_p_state *s,
1318                             struct file_diff *file_diff, size_t start_index)
1319 {
1320         size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1321
1322         if (end_index > file_diff->hunk_nr)
1323                 end_index = file_diff->hunk_nr;
1324
1325         while (start_index < end_index) {
1326                 struct hunk *hunk = file_diff->hunk + start_index++;
1327
1328                 strbuf_reset(&s->buf);
1329                 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1330                             : hunk->use == SKIP_HUNK ? '-' : ' ',
1331                             (int)start_index);
1332                 summarize_hunk(s, hunk, &s->buf);
1333                 fputs(s->buf.buf, stdout);
1334         }
1335
1336         return end_index;
1337 }
1338
1339 static const char help_patch_remainder[] =
1340 N_("j - leave this hunk undecided, see next undecided hunk\n"
1341    "J - leave this hunk undecided, see next hunk\n"
1342    "k - leave this hunk undecided, see previous undecided hunk\n"
1343    "K - leave this hunk undecided, see previous hunk\n"
1344    "g - select a hunk to go to\n"
1345    "/ - search for a hunk matching the given regex\n"
1346    "s - split the current hunk into smaller hunks\n"
1347    "e - manually edit the current hunk\n"
1348    "? - print help\n");
1349
1350 static int patch_update_file(struct add_p_state *s,
1351                              struct file_diff *file_diff)
1352 {
1353         size_t hunk_index = 0;
1354         ssize_t i, undecided_previous, undecided_next;
1355         struct hunk *hunk;
1356         char ch;
1357         struct child_process cp = CHILD_PROCESS_INIT;
1358         int colored = !!s->colored.len, quit = 0;
1359         enum prompt_mode_type prompt_mode_type;
1360
1361         if (!file_diff->hunk_nr)
1362                 return 0;
1363
1364         strbuf_reset(&s->buf);
1365         render_diff_header(s, file_diff, colored, &s->buf);
1366         fputs(s->buf.buf, stdout);
1367         for (;;) {
1368                 if (hunk_index >= file_diff->hunk_nr)
1369                         hunk_index = 0;
1370                 hunk = file_diff->hunk + hunk_index;
1371
1372                 undecided_previous = -1;
1373                 for (i = hunk_index - 1; i >= 0; i--)
1374                         if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1375                                 undecided_previous = i;
1376                                 break;
1377                         }
1378
1379                 undecided_next = -1;
1380                 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1381                         if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1382                                 undecided_next = i;
1383                                 break;
1384                         }
1385
1386                 /* Everything decided? */
1387                 if (undecided_previous < 0 && undecided_next < 0 &&
1388                     hunk->use != UNDECIDED_HUNK)
1389                         break;
1390
1391                 strbuf_reset(&s->buf);
1392                 render_hunk(s, hunk, 0, colored, &s->buf);
1393                 fputs(s->buf.buf, stdout);
1394
1395                 strbuf_reset(&s->buf);
1396                 if (undecided_previous >= 0)
1397                         strbuf_addstr(&s->buf, ",k");
1398                 if (hunk_index)
1399                         strbuf_addstr(&s->buf, ",K");
1400                 if (undecided_next >= 0)
1401                         strbuf_addstr(&s->buf, ",j");
1402                 if (hunk_index + 1 < file_diff->hunk_nr)
1403                         strbuf_addstr(&s->buf, ",J");
1404                 if (file_diff->hunk_nr > 1)
1405                         strbuf_addstr(&s->buf, ",g,/");
1406                 if (hunk->splittable_into > 1)
1407                         strbuf_addstr(&s->buf, ",s");
1408                 if (hunk_index + 1 > file_diff->mode_change &&
1409                     !file_diff->deleted)
1410                         strbuf_addstr(&s->buf, ",e");
1411
1412                 if (file_diff->deleted)
1413                         prompt_mode_type = PROMPT_DELETION;
1414                 else if (file_diff->added)
1415                         prompt_mode_type = PROMPT_ADDITION;
1416                 else if (file_diff->mode_change && !hunk_index)
1417                         prompt_mode_type = PROMPT_MODE_CHANGE;
1418                 else
1419                         prompt_mode_type = PROMPT_HUNK;
1420
1421                 color_fprintf(stdout, s->s.prompt_color,
1422                               "(%"PRIuMAX"/%"PRIuMAX") ",
1423                               (uintmax_t)hunk_index + 1,
1424                               (uintmax_t)file_diff->hunk_nr);
1425                 color_fprintf(stdout, s->s.prompt_color,
1426                               _(s->mode->prompt_mode[prompt_mode_type]),
1427                               s->buf.buf);
1428                 fflush(stdout);
1429                 if (read_single_character(s) == EOF)
1430                         break;
1431
1432                 if (!s->answer.len)
1433                         continue;
1434                 ch = tolower(s->answer.buf[0]);
1435                 if (ch == 'y') {
1436                         hunk->use = USE_HUNK;
1437 soft_increment:
1438                         hunk_index = undecided_next < 0 ?
1439                                 file_diff->hunk_nr : undecided_next;
1440                 } else if (ch == 'n') {
1441                         hunk->use = SKIP_HUNK;
1442                         goto soft_increment;
1443                 } else if (ch == 'a') {
1444                         for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1445                                 hunk = file_diff->hunk + hunk_index;
1446                                 if (hunk->use == UNDECIDED_HUNK)
1447                                         hunk->use = USE_HUNK;
1448                         }
1449                 } else if (ch == 'd' || ch == 'q') {
1450                         for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1451                                 hunk = file_diff->hunk + hunk_index;
1452                                 if (hunk->use == UNDECIDED_HUNK)
1453                                         hunk->use = SKIP_HUNK;
1454                         }
1455                         if (ch == 'q') {
1456                                 quit = 1;
1457                                 break;
1458                         }
1459                 } else if (s->answer.buf[0] == 'K') {
1460                         if (hunk_index)
1461                                 hunk_index--;
1462                         else
1463                                 err(s, _("No previous hunk"));
1464                 } else if (s->answer.buf[0] == 'J') {
1465                         if (hunk_index + 1 < file_diff->hunk_nr)
1466                                 hunk_index++;
1467                         else
1468                                 err(s, _("No next hunk"));
1469                 } else if (s->answer.buf[0] == 'k') {
1470                         if (undecided_previous >= 0)
1471                                 hunk_index = undecided_previous;
1472                         else
1473                                 err(s, _("No previous hunk"));
1474                 } else if (s->answer.buf[0] == 'j') {
1475                         if (undecided_next >= 0)
1476                                 hunk_index = undecided_next;
1477                         else
1478                                 err(s, _("No next hunk"));
1479                 } else if (s->answer.buf[0] == 'g') {
1480                         char *pend;
1481                         unsigned long response;
1482
1483                         if (file_diff->hunk_nr < 2) {
1484                                 err(s, _("No other hunks to goto"));
1485                                 continue;
1486                         }
1487                         strbuf_remove(&s->answer, 0, 1);
1488                         strbuf_trim(&s->answer);
1489                         i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1490                         if (i < file_diff->mode_change)
1491                                 i = file_diff->mode_change;
1492                         while (s->answer.len == 0) {
1493                                 i = display_hunks(s, file_diff, i);
1494                                 printf("%s", i < file_diff->hunk_nr ?
1495                                        _("go to which hunk (<ret> to see "
1496                                          "more)? ") : _("go to which hunk? "));
1497                                 fflush(stdout);
1498                                 if (strbuf_getline(&s->answer,
1499                                                    stdin) == EOF)
1500                                         break;
1501                                 strbuf_trim_trailing_newline(&s->answer);
1502                         }
1503
1504                         strbuf_trim(&s->answer);
1505                         response = strtoul(s->answer.buf, &pend, 10);
1506                         if (*pend || pend == s->answer.buf)
1507                                 err(s, _("Invalid number: '%s'"),
1508                                     s->answer.buf);
1509                         else if (0 < response && response <= file_diff->hunk_nr)
1510                                 hunk_index = response - 1;
1511                         else
1512                                 err(s, Q_("Sorry, only %d hunk available.",
1513                                           "Sorry, only %d hunks available.",
1514                                           file_diff->hunk_nr),
1515                                     (int)file_diff->hunk_nr);
1516                 } else if (s->answer.buf[0] == '/') {
1517                         regex_t regex;
1518                         int ret;
1519
1520                         if (file_diff->hunk_nr < 2) {
1521                                 err(s, _("No other hunks to search"));
1522                                 continue;
1523                         }
1524                         strbuf_remove(&s->answer, 0, 1);
1525                         strbuf_trim_trailing_newline(&s->answer);
1526                         if (s->answer.len == 0) {
1527                                 printf("%s", _("search for regex? "));
1528                                 fflush(stdout);
1529                                 if (strbuf_getline(&s->answer,
1530                                                    stdin) == EOF)
1531                                         break;
1532                                 strbuf_trim_trailing_newline(&s->answer);
1533                                 if (s->answer.len == 0)
1534                                         continue;
1535                         }
1536                         ret = regcomp(&regex, s->answer.buf,
1537                                       REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1538                         if (ret) {
1539                                 char errbuf[1024];
1540
1541                                 regerror(ret, &regex, errbuf, sizeof(errbuf));
1542                                 err(s, _("Malformed search regexp %s: %s"),
1543                                     s->answer.buf, errbuf);
1544                                 continue;
1545                         }
1546                         i = hunk_index;
1547                         for (;;) {
1548                                 /* render the hunk into a scratch buffer */
1549                                 render_hunk(s, file_diff->hunk + i, 0, 0,
1550                                             &s->buf);
1551                                 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1552                                     != REG_NOMATCH)
1553                                         break;
1554                                 i++;
1555                                 if (i == file_diff->hunk_nr)
1556                                         i = 0;
1557                                 if (i != hunk_index)
1558                                         continue;
1559                                 err(s, _("No hunk matches the given pattern"));
1560                                 break;
1561                         }
1562                         hunk_index = i;
1563                 } else if (s->answer.buf[0] == 's') {
1564                         size_t splittable_into = hunk->splittable_into;
1565                         if (splittable_into < 2)
1566                                 err(s, _("Sorry, cannot split this hunk"));
1567                         else if (!split_hunk(s, file_diff,
1568                                              hunk - file_diff->hunk))
1569                                 color_fprintf_ln(stdout, s->s.header_color,
1570                                                  _("Split into %d hunks."),
1571                                                  (int)splittable_into);
1572                 } else if (s->answer.buf[0] == 'e') {
1573                         if (hunk_index + 1 == file_diff->mode_change)
1574                                 err(s, _("Sorry, cannot edit this hunk"));
1575                         else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1576                                 hunk->use = USE_HUNK;
1577                                 goto soft_increment;
1578                         }
1579                 } else {
1580                         const char *p = _(help_patch_remainder), *eol = p;
1581
1582                         color_fprintf(stdout, s->s.help_color, "%s",
1583                                       _(s->mode->help_patch_text));
1584
1585                         /*
1586                          * Show only those lines of the remainder that are
1587                          * actually applicable with the current hunk.
1588                          */
1589                         for (; *p; p = eol + (*eol == '\n')) {
1590                                 eol = strchrnul(p, '\n');
1591
1592                                 /*
1593                                  * `s->buf` still contains the part of the
1594                                  * commands shown in the prompt that are not
1595                                  * always available.
1596                                  */
1597                                 if (*p != '?' && !strchr(s->buf.buf, *p))
1598                                         continue;
1599
1600                                 color_fprintf_ln(stdout, s->s.help_color,
1601                                                  "%.*s", (int)(eol - p), p);
1602                         }
1603                 }
1604         }
1605
1606         /* Any hunk to be used? */
1607         for (i = 0; i < file_diff->hunk_nr; i++)
1608                 if (file_diff->hunk[i].use == USE_HUNK)
1609                         break;
1610
1611         if (i < file_diff->hunk_nr) {
1612                 /* At least one hunk selected: apply */
1613                 strbuf_reset(&s->buf);
1614                 reassemble_patch(s, file_diff, 0, &s->buf);
1615
1616                 discard_index(s->s.r->index);
1617                 if (s->mode->apply_for_checkout)
1618                         apply_for_checkout(s, &s->buf,
1619                                            s->mode->is_reverse);
1620                 else {
1621                         setup_child_process(s, &cp, "apply", NULL);
1622                         argv_array_pushv(&cp.args, s->mode->apply_args);
1623                         if (pipe_command(&cp, s->buf.buf, s->buf.len,
1624                                          NULL, 0, NULL, 0))
1625                                 error(_("'git apply' failed"));
1626                 }
1627                 if (!repo_read_index(s->s.r))
1628                         repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
1629                                                      1, NULL, NULL, NULL);
1630         }
1631
1632         putchar('\n');
1633         return quit;
1634 }
1635
1636 int run_add_p(struct repository *r, enum add_p_mode mode,
1637               const char *revision, const struct pathspec *ps)
1638 {
1639         struct add_p_state s = {
1640                 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1641         };
1642         size_t i, binary_count = 0;
1643
1644         init_add_i_state(&s.s, r);
1645
1646         if (mode == ADD_P_STASH)
1647                 s.mode = &patch_mode_stash;
1648         else if (mode == ADD_P_RESET) {
1649                 if (!revision || !strcmp(revision, "HEAD"))
1650                         s.mode = &patch_mode_reset_head;
1651                 else
1652                         s.mode = &patch_mode_reset_nothead;
1653         } else if (mode == ADD_P_CHECKOUT) {
1654                 if (!revision)
1655                         s.mode = &patch_mode_checkout_index;
1656                 else if (!strcmp(revision, "HEAD"))
1657                         s.mode = &patch_mode_checkout_head;
1658                 else
1659                         s.mode = &patch_mode_checkout_nothead;
1660         } else if (mode == ADD_P_WORKTREE) {
1661                 if (!revision)
1662                         s.mode = &patch_mode_checkout_index;
1663                 else if (!strcmp(revision, "HEAD"))
1664                         s.mode = &patch_mode_worktree_head;
1665                 else
1666                         s.mode = &patch_mode_worktree_nothead;
1667         } else
1668                 s.mode = &patch_mode_add;
1669         s.revision = revision;
1670
1671         if (discard_index(r->index) < 0 || repo_read_index(r) < 0 ||
1672             (!s.mode->index_only &&
1673              repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1674                                           NULL, NULL, NULL) < 0) ||
1675             parse_diff(&s, ps) < 0) {
1676                 strbuf_release(&s.plain);
1677                 strbuf_release(&s.colored);
1678                 clear_add_i_state(&s.s);
1679                 return -1;
1680         }
1681
1682         for (i = 0; i < s.file_diff_nr; i++)
1683                 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1684                         binary_count++;
1685                 else if (patch_update_file(&s, s.file_diff + i))
1686                         break;
1687
1688         if (s.file_diff_nr == 0)
1689                 fprintf(stderr, _("No changes.\n"));
1690         else if (binary_count == s.file_diff_nr)
1691                 fprintf(stderr, _("Only binary files changed.\n"));
1692
1693         strbuf_release(&s.answer);
1694         strbuf_release(&s.buf);
1695         strbuf_release(&s.plain);
1696         strbuf_release(&s.colored);
1697         clear_add_i_state(&s.s);
1698         return 0;
1699 }