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