Imported Upstream version 2.26.0
[platform/upstream/git.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
11 enum prompt_mode_type {
12         PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_HUNK,
13         PROMPT_MODE_MAX, /* must be last */
14 };
15
16 struct patch_mode {
17         /*
18          * The magic constant 4 is chosen such that all patch modes
19          * provide enough space for three command-line arguments followed by a
20          * trailing `NULL`.
21          */
22         const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
23         unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
24         const char *prompt_mode[PROMPT_MODE_MAX];
25         const char *edit_hunk_hint, *help_patch_text;
26 };
27
28 static struct patch_mode patch_mode_add = {
29         .diff_cmd = { "diff-files", NULL },
30         .apply_args = { "--cached", NULL },
31         .apply_check_args = { "--cached", NULL },
32         .prompt_mode = {
33                 N_("Stage mode change [y,n,q,a,d%s,?]? "),
34                 N_("Stage deletion [y,n,q,a,d%s,?]? "),
35                 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
36         },
37         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
38                              "will immediately be marked for staging."),
39         .help_patch_text =
40                 N_("y - stage this hunk\n"
41                    "n - do not stage this hunk\n"
42                    "q - quit; do not stage this hunk or any of the remaining "
43                         "ones\n"
44                    "a - stage this hunk and all later hunks in the file\n"
45                    "d - do not stage this hunk or any of the later hunks in "
46                         "the file\n")
47 };
48
49 static struct patch_mode patch_mode_stash = {
50         .diff_cmd = { "diff-index", "HEAD", NULL },
51         .apply_args = { "--cached", NULL },
52         .apply_check_args = { "--cached", NULL },
53         .prompt_mode = {
54                 N_("Stash mode change [y,n,q,a,d%s,?]? "),
55                 N_("Stash deletion [y,n,q,a,d%s,?]? "),
56                 N_("Stash this hunk [y,n,q,a,d%s,?]? "),
57         },
58         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
59                              "will immediately be marked for stashing."),
60         .help_patch_text =
61                 N_("y - stash this hunk\n"
62                    "n - do not stash this hunk\n"
63                    "q - quit; do not stash this hunk or any of the remaining "
64                         "ones\n"
65                    "a - stash this hunk and all later hunks in the file\n"
66                    "d - do not stash this hunk or any of the later hunks in "
67                         "the file\n"),
68 };
69
70 static struct patch_mode patch_mode_reset_head = {
71         .diff_cmd = { "diff-index", "--cached", NULL },
72         .apply_args = { "-R", "--cached", NULL },
73         .apply_check_args = { "-R", "--cached", NULL },
74         .is_reverse = 1,
75         .index_only = 1,
76         .prompt_mode = {
77                 N_("Unstage mode change [y,n,q,a,d%s,?]? "),
78                 N_("Unstage deletion [y,n,q,a,d%s,?]? "),
79                 N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
80         },
81         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
82                              "will immediately be marked for unstaging."),
83         .help_patch_text =
84                 N_("y - unstage this hunk\n"
85                    "n - do not unstage this hunk\n"
86                    "q - quit; do not unstage this hunk or any of the remaining "
87                         "ones\n"
88                    "a - unstage this hunk and all later hunks in the file\n"
89                    "d - do not unstage this hunk or any of the later hunks in "
90                         "the file\n"),
91 };
92
93 static struct patch_mode patch_mode_reset_nothead = {
94         .diff_cmd = { "diff-index", "-R", "--cached", NULL },
95         .apply_args = { "--cached", NULL },
96         .apply_check_args = { "--cached", NULL },
97         .index_only = 1,
98         .prompt_mode = {
99                 N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
100                 N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
101                 N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
102         },
103         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
104                              "will immediately be marked for applying."),
105         .help_patch_text =
106                 N_("y - apply this hunk to index\n"
107                    "n - do not apply this hunk to index\n"
108                    "q - quit; do not apply this hunk or any of the remaining "
109                         "ones\n"
110                    "a - apply this hunk and all later hunks in the file\n"
111                    "d - do not apply this hunk or any of the later hunks in "
112                         "the file\n"),
113 };
114
115 static struct patch_mode patch_mode_checkout_index = {
116         .diff_cmd = { "diff-files", NULL },
117         .apply_args = { "-R", NULL },
118         .apply_check_args = { "-R", NULL },
119         .is_reverse = 1,
120         .prompt_mode = {
121                 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
122                 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
123                 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
124         },
125         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
126                              "will immediately be marked for discarding."),
127         .help_patch_text =
128                 N_("y - discard this hunk from worktree\n"
129                    "n - do not discard this hunk from worktree\n"
130                    "q - quit; do not discard this hunk or any of the remaining "
131                         "ones\n"
132                    "a - discard this hunk and all later hunks in the file\n"
133                    "d - do not discard this hunk or any of the later hunks in "
134                         "the file\n"),
135 };
136
137 static struct patch_mode patch_mode_checkout_head = {
138         .diff_cmd = { "diff-index", NULL },
139         .apply_for_checkout = 1,
140         .apply_check_args = { "-R", NULL },
141         .is_reverse = 1,
142         .prompt_mode = {
143                 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
144                 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
145                 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
146         },
147         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
148                              "will immediately be marked for discarding."),
149         .help_patch_text =
150                 N_("y - discard this hunk from index and worktree\n"
151                    "n - do not discard this hunk from index and worktree\n"
152                    "q - quit; do not discard this hunk or any of the remaining "
153                         "ones\n"
154                    "a - discard this hunk and all later hunks in the file\n"
155                    "d - do not discard this hunk or any of the later hunks in "
156                         "the file\n"),
157 };
158
159 static struct patch_mode patch_mode_checkout_nothead = {
160         .diff_cmd = { "diff-index", "-R", NULL },
161         .apply_for_checkout = 1,
162         .apply_check_args = { NULL },
163         .prompt_mode = {
164                 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
165                 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
166                 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
167         },
168         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
169                              "will immediately be marked for applying."),
170         .help_patch_text =
171                 N_("y - apply this hunk to index and worktree\n"
172                    "n - do not apply this hunk to index and worktree\n"
173                    "q - quit; do not apply this hunk or any of the remaining "
174                         "ones\n"
175                    "a - apply this hunk and all later hunks in the file\n"
176                    "d - do not apply this hunk or any of the later hunks in "
177                         "the file\n"),
178 };
179
180 static struct patch_mode patch_mode_worktree_head = {
181         .diff_cmd = { "diff-index", NULL },
182         .apply_args = { "-R", NULL },
183         .apply_check_args = { "-R", NULL },
184         .is_reverse = 1,
185         .prompt_mode = {
186                 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
187                 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
188                 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
189         },
190         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
191                              "will immediately be marked for discarding."),
192         .help_patch_text =
193                 N_("y - discard this hunk from worktree\n"
194                    "n - do not discard this hunk from worktree\n"
195                    "q - quit; do not discard this hunk or any of the remaining "
196                         "ones\n"
197                    "a - discard this hunk and all later hunks in the file\n"
198                    "d - do not discard this hunk or any of the later hunks in "
199                         "the file\n"),
200 };
201
202 static struct patch_mode patch_mode_worktree_nothead = {
203         .diff_cmd = { "diff-index", "-R", NULL },
204         .apply_args = { NULL },
205         .apply_check_args = { NULL },
206         .prompt_mode = {
207                 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
208                 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
209                 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
210         },
211         .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
212                              "will immediately be marked for applying."),
213         .help_patch_text =
214                 N_("y - apply this hunk to worktree\n"
215                    "n - do not apply this hunk to worktree\n"
216                    "q - quit; do not apply this hunk or any of the remaining "
217                         "ones\n"
218                    "a - apply this hunk and all later hunks in the file\n"
219                    "d - do not apply this hunk or any of the later hunks in "
220                         "the file\n"),
221 };
222
223 struct hunk_header {
224         unsigned long old_offset, old_count, new_offset, new_count;
225         /*
226          * Start/end offsets to the extra text after the second `@@` in the
227          * hunk header, e.g. the function signature. This is expected to
228          * include the newline.
229          */
230         size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
231 };
232
233 struct hunk {
234         size_t start, end, colored_start, colored_end, splittable_into;
235         ssize_t delta;
236         enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
237         struct hunk_header header;
238 };
239
240 struct add_p_state {
241         struct add_i_state s;
242         struct strbuf answer, buf;
243
244         /* parsed diff */
245         struct strbuf plain, colored;
246         struct file_diff {
247                 struct hunk head;
248                 struct hunk *hunk;
249                 size_t hunk_nr, hunk_alloc;
250                 unsigned deleted:1, mode_change:1,binary:1;
251         } *file_diff;
252         size_t file_diff_nr;
253
254         /* patch mode */
255         struct patch_mode *mode;
256         const char *revision;
257 };
258
259 static void err(struct add_p_state *s, const char *fmt, ...)
260 {
261         va_list args;
262
263         va_start(args, fmt);
264         fputs(s->s.error_color, stderr);
265         vfprintf(stderr, fmt, args);
266         fputs(s->s.reset_color, stderr);
267         fputc('\n', stderr);
268         va_end(args);
269 }
270
271 static void setup_child_process(struct add_p_state *s,
272                                 struct child_process *cp, ...)
273 {
274         va_list ap;
275         const char *arg;
276
277         va_start(ap, cp);
278         while ((arg = va_arg(ap, const char *)))
279                 argv_array_push(&cp->args, arg);
280         va_end(ap);
281
282         cp->git_cmd = 1;
283         argv_array_pushf(&cp->env_array,
284                          INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
285 }
286
287 static int parse_range(const char **p,
288                        unsigned long *offset, unsigned long *count)
289 {
290         char *pend;
291
292         *offset = strtoul(*p, &pend, 10);
293         if (pend == *p)
294                 return -1;
295         if (*pend != ',') {
296                 *count = 1;
297                 *p = pend;
298                 return 0;
299         }
300         *count = strtoul(pend + 1, (char **)p, 10);
301         return *p == pend + 1 ? -1 : 0;
302 }
303
304 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
305 {
306         struct hunk_header *header = &hunk->header;
307         const char *line = s->plain.buf + hunk->start, *p = line;
308         char *eol = memchr(p, '\n', s->plain.len - hunk->start);
309
310         if (!eol)
311                 eol = s->plain.buf + s->plain.len;
312
313         if (!skip_prefix(p, "@@ -", &p) ||
314             parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
315             !skip_prefix(p, " +", &p) ||
316             parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
317             !skip_prefix(p, " @@", &p))
318                 return error(_("could not parse hunk header '%.*s'"),
319                              (int)(eol - line), line);
320
321         hunk->start = eol - s->plain.buf + (*eol == '\n');
322         header->extra_start = p - s->plain.buf;
323         header->extra_end = hunk->start;
324
325         if (!s->colored.len) {
326                 header->colored_extra_start = header->colored_extra_end = 0;
327                 return 0;
328         }
329
330         /* Now find the extra text in the colored diff */
331         line = s->colored.buf + hunk->colored_start;
332         eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
333         if (!eol)
334                 eol = s->colored.buf + s->colored.len;
335         p = memmem(line, eol - line, "@@ -", 4);
336         if (!p)
337                 return error(_("could not parse colored hunk header '%.*s'"),
338                              (int)(eol - line), line);
339         p = memmem(p + 4, eol - p - 4, " @@", 3);
340         if (!p)
341                 return error(_("could not parse colored hunk header '%.*s'"),
342                              (int)(eol - line), line);
343         hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
344         header->colored_extra_start = p + 3 - s->colored.buf;
345         header->colored_extra_end = hunk->colored_start;
346
347         return 0;
348 }
349
350 static int is_octal(const char *p, size_t len)
351 {
352         if (!len)
353                 return 0;
354
355         while (len--)
356                 if (*p < '0' || *(p++) > '7')
357                         return 0;
358         return 1;
359 }
360
361 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
362 {
363         struct argv_array args = ARGV_ARRAY_INIT;
364         const char *diff_algorithm = s->s.interactive_diff_algorithm;
365         struct strbuf *plain = &s->plain, *colored = NULL;
366         struct child_process cp = CHILD_PROCESS_INIT;
367         char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
368         size_t file_diff_alloc = 0, i, color_arg_index;
369         struct file_diff *file_diff = NULL;
370         struct hunk *hunk = NULL;
371         int res;
372
373         argv_array_pushv(&args, s->mode->diff_cmd);
374         if (diff_algorithm)
375                 argv_array_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
376         if (s->revision) {
377                 struct object_id oid;
378                 argv_array_push(&args,
379                                 /* could be on an unborn branch */
380                                 !strcmp("HEAD", s->revision) &&
381                                 get_oid("HEAD", &oid) ?
382                                 empty_tree_oid_hex() : s->revision);
383         }
384         color_arg_index = args.argc;
385         /* Use `--no-color` explicitly, just in case `diff.color = always`. */
386         argv_array_pushl(&args, "--no-color", "-p", "--", NULL);
387         for (i = 0; i < ps->nr; i++)
388                 argv_array_push(&args, ps->items[i].original);
389
390         setup_child_process(s, &cp, NULL);
391         cp.argv = args.argv;
392         res = capture_command(&cp, plain, 0);
393         if (res) {
394                 argv_array_clear(&args);
395                 return error(_("could not parse diff"));
396         }
397         if (!plain->len) {
398                 argv_array_clear(&args);
399                 return 0;
400         }
401         strbuf_complete_line(plain);
402
403         if (want_color_fd(1, -1)) {
404                 struct child_process colored_cp = CHILD_PROCESS_INIT;
405                 const char *diff_filter = s->s.interactive_diff_filter;
406
407                 setup_child_process(s, &colored_cp, NULL);
408                 xsnprintf((char *)args.argv[color_arg_index], 8, "--color");
409                 colored_cp.argv = args.argv;
410                 colored = &s->colored;
411                 res = capture_command(&colored_cp, colored, 0);
412                 argv_array_clear(&args);
413                 if (res)
414                         return error(_("could not parse colored diff"));
415
416                 if (diff_filter) {
417                         struct child_process filter_cp = CHILD_PROCESS_INIT;
418
419                         setup_child_process(s, &filter_cp,
420                                             diff_filter, NULL);
421                         filter_cp.git_cmd = 0;
422                         filter_cp.use_shell = 1;
423                         strbuf_reset(&s->buf);
424                         if (pipe_command(&filter_cp,
425                                          colored->buf, colored->len,
426                                          &s->buf, colored->len,
427                                          NULL, 0) < 0)
428                                 return error(_("failed to run '%s'"),
429                                              diff_filter);
430                         strbuf_swap(colored, &s->buf);
431                 }
432
433                 strbuf_complete_line(colored);
434                 colored_p = colored->buf;
435                 colored_pend = colored_p + colored->len;
436         }
437         argv_array_clear(&args);
438
439         /* parse files and hunks */
440         p = plain->buf;
441         pend = p + plain->len;
442         while (p != pend) {
443                 char *eol = memchr(p, '\n', pend - p);
444                 const char *deleted = NULL, *mode_change = NULL;
445
446                 if (!eol)
447                         eol = pend;
448
449                 if (starts_with(p, "diff ")) {
450                         s->file_diff_nr++;
451                         ALLOC_GROW(s->file_diff, s->file_diff_nr,
452                                    file_diff_alloc);
453                         file_diff = s->file_diff + s->file_diff_nr - 1;
454                         memset(file_diff, 0, sizeof(*file_diff));
455                         hunk = &file_diff->head;
456                         hunk->start = p - plain->buf;
457                         if (colored_p)
458                                 hunk->colored_start = colored_p - colored->buf;
459                         marker = '\0';
460                 } else if (p == plain->buf)
461                         BUG("diff starts with unexpected line:\n"
462                             "%.*s\n", (int)(eol - p), p);
463                 else if (file_diff->deleted)
464                         ; /* keep the rest of the file in a single "hunk" */
465                 else if (starts_with(p, "@@ ") ||
466                          (hunk == &file_diff->head &&
467                           skip_prefix(p, "deleted file", &deleted))) {
468                         if (marker == '-' || marker == '+')
469                                 /*
470                                  * Should not happen; previous hunk did not end
471                                  * in a context line? Handle it anyway.
472                                  */
473                                 hunk->splittable_into++;
474
475                         file_diff->hunk_nr++;
476                         ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
477                                    file_diff->hunk_alloc);
478                         hunk = file_diff->hunk + file_diff->hunk_nr - 1;
479                         memset(hunk, 0, sizeof(*hunk));
480
481                         hunk->start = p - plain->buf;
482                         if (colored)
483                                 hunk->colored_start = colored_p - colored->buf;
484
485                         if (deleted)
486                                 file_diff->deleted = 1;
487                         else if (parse_hunk_header(s, hunk) < 0)
488                                 return -1;
489
490                         /*
491                          * Start counting into how many hunks this one can be
492                          * split
493                          */
494                         marker = *p;
495                 } else if (hunk == &file_diff->head &&
496                            skip_prefix(p, "old mode ", &mode_change) &&
497                            is_octal(mode_change, eol - mode_change)) {
498                         if (file_diff->mode_change)
499                                 BUG("double mode change?\n\n%.*s",
500                                     (int)(eol - plain->buf), plain->buf);
501                         if (file_diff->hunk_nr++)
502                                 BUG("mode change in the middle?\n\n%.*s",
503                                     (int)(eol - plain->buf), plain->buf);
504
505                         /*
506                          * Do *not* change `hunk`: the mode change pseudo-hunk
507                          * is _part of_ the header "hunk".
508                          */
509                         file_diff->mode_change = 1;
510                         ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
511                                    file_diff->hunk_alloc);
512                         memset(file_diff->hunk, 0, sizeof(struct hunk));
513                         file_diff->hunk->start = p - plain->buf;
514                         if (colored_p)
515                                 file_diff->hunk->colored_start =
516                                         colored_p - colored->buf;
517                 } else if (hunk == &file_diff->head &&
518                            skip_prefix(p, "new mode ", &mode_change) &&
519                            is_octal(mode_change, eol - mode_change)) {
520
521                         /*
522                          * Extend the "mode change" pseudo-hunk to include also
523                          * the "new mode" line.
524                          */
525                         if (!file_diff->mode_change)
526                                 BUG("'new mode' without 'old mode'?\n\n%.*s",
527                                     (int)(eol - plain->buf), plain->buf);
528                         if (file_diff->hunk_nr != 1)
529                                 BUG("mode change in the middle?\n\n%.*s",
530                                     (int)(eol - plain->buf), plain->buf);
531                         if (p - plain->buf != file_diff->hunk->end)
532                                 BUG("'new mode' does not immediately follow "
533                                     "'old mode'?\n\n%.*s",
534                                     (int)(eol - plain->buf), plain->buf);
535                 } else if (hunk == &file_diff->head &&
536                            starts_with(p, "Binary files "))
537                         file_diff->binary = 1;
538
539                 if (file_diff->deleted && file_diff->mode_change)
540                         BUG("diff contains delete *and* a mode change?!?\n%.*s",
541                             (int)(eol - (plain->buf + file_diff->head.start)),
542                             plain->buf + file_diff->head.start);
543
544                 if ((marker == '-' || marker == '+') && *p == ' ')
545                         hunk->splittable_into++;
546                 if (marker && *p != '\\')
547                         marker = *p;
548
549                 p = eol == pend ? pend : eol + 1;
550                 hunk->end = p - plain->buf;
551
552                 if (colored) {
553                         char *colored_eol = memchr(colored_p, '\n',
554                                                    colored_pend - colored_p);
555                         if (colored_eol)
556                                 colored_p = colored_eol + 1;
557                         else if (p != pend)
558                                 /* colored shorter than non-colored? */
559                                 goto mismatched_output;
560                         else
561                                 colored_p = colored_pend;
562
563                         hunk->colored_end = colored_p - colored->buf;
564                 }
565
566                 if (mode_change) {
567                         if (file_diff->hunk_nr != 1)
568                                 BUG("mode change in hunk #%d???",
569                                     (int)file_diff->hunk_nr);
570                         /* Adjust the end of the "mode change" pseudo-hunk */
571                         file_diff->hunk->end = hunk->end;
572                         if (colored)
573                                 file_diff->hunk->colored_end = hunk->colored_end;
574                 }
575         }
576
577         if (marker == '-' || marker == '+')
578                 /*
579                  * Last hunk ended in non-context line (i.e. it appended lines
580                  * to the file, so there are no trailing context lines).
581                  */
582                 hunk->splittable_into++;
583
584         /* non-colored shorter than colored? */
585         if (colored_p != colored_pend) {
586 mismatched_output:
587                 error(_("mismatched output from interactive.diffFilter"));
588                 advise(_("Your filter must maintain a one-to-one correspondence\n"
589                          "between its input and output lines."));
590                 return -1;
591         }
592
593         return 0;
594 }
595
596 static size_t find_next_line(struct strbuf *sb, size_t offset)
597 {
598         char *eol;
599
600         if (offset >= sb->len)
601                 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
602                     (int)offset, (int)sb->len, sb->buf);
603
604         eol = memchr(sb->buf + offset, '\n', sb->len - offset);
605         if (!eol)
606                 return sb->len;
607         return eol - sb->buf + 1;
608 }
609
610 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
611                         ssize_t delta, int colored, struct strbuf *out)
612 {
613         struct hunk_header *header = &hunk->header;
614
615         if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
616                 /*
617                  * Generate the hunk header dynamically, except for special
618                  * hunks (such as the diff header).
619                  */
620                 const char *p;
621                 size_t len;
622                 unsigned long old_offset = header->old_offset;
623                 unsigned long new_offset = header->new_offset;
624
625                 if (!colored) {
626                         p = s->plain.buf + header->extra_start;
627                         len = header->extra_end - header->extra_start;
628                 } else {
629                         strbuf_addstr(out, s->s.fraginfo_color);
630                         p = s->colored.buf + header->colored_extra_start;
631                         len = header->colored_extra_end
632                                 - header->colored_extra_start;
633                 }
634
635                 if (s->mode->is_reverse)
636                         old_offset -= delta;
637                 else
638                         new_offset += delta;
639
640                 strbuf_addf(out, "@@ -%lu,%lu +%lu,%lu @@",
641                             old_offset, header->old_count,
642                             new_offset, header->new_count);
643                 if (len)
644                         strbuf_add(out, p, len);
645                 else if (colored)
646                         strbuf_addf(out, "%s\n", GIT_COLOR_RESET);
647                 else
648                         strbuf_addch(out, '\n');
649         }
650
651         if (colored)
652                 strbuf_add(out, s->colored.buf + hunk->colored_start,
653                            hunk->colored_end - hunk->colored_start);
654         else
655                 strbuf_add(out, s->plain.buf + hunk->start,
656                            hunk->end - hunk->start);
657 }
658
659 static void render_diff_header(struct add_p_state *s,
660                                struct file_diff *file_diff, int colored,
661                                struct strbuf *out)
662 {
663         /*
664          * If there was a mode change, the first hunk is a pseudo hunk that
665          * corresponds to the mode line in the header. If the user did not want
666          * to stage that "hunk", we actually have to cut it out from the header.
667          */
668         int skip_mode_change =
669                 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
670         struct hunk *head = &file_diff->head, *first = file_diff->hunk;
671
672         if (!skip_mode_change) {
673                 render_hunk(s, head, 0, colored, out);
674                 return;
675         }
676
677         if (colored) {
678                 const char *p = s->colored.buf;
679
680                 strbuf_add(out, p + head->colored_start,
681                             first->colored_start - head->colored_start);
682                 strbuf_add(out, p + first->colored_end,
683                             head->colored_end - first->colored_end);
684         } else {
685                 const char *p = s->plain.buf;
686
687                 strbuf_add(out, p + head->start, first->start - head->start);
688                 strbuf_add(out, p + first->end, head->end - first->end);
689         }
690 }
691
692 /* Coalesce hunks again that were split */
693 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
694                        size_t *hunk_index, int use_all, struct hunk *merged)
695 {
696         size_t i = *hunk_index, delta;
697         struct hunk *hunk = file_diff->hunk + i;
698         /* `header` corresponds to the merged hunk */
699         struct hunk_header *header = &merged->header, *next;
700
701         if (!use_all && hunk->use != USE_HUNK)
702                 return 0;
703
704         *merged = *hunk;
705         /* We simply skip the colored part (if any) when merging hunks */
706         merged->colored_start = merged->colored_end = 0;
707
708         for (; i + 1 < file_diff->hunk_nr; i++) {
709                 hunk++;
710                 next = &hunk->header;
711
712                 /*
713                  * Stop merging hunks when:
714                  *
715                  * - the hunk is not selected for use, or
716                  * - the hunk does not overlap with the already-merged hunk(s)
717                  */
718                 if ((!use_all && hunk->use != USE_HUNK) ||
719                     header->new_offset >= next->new_offset + merged->delta ||
720                     header->new_offset + header->new_count
721                     < next->new_offset + merged->delta)
722                         break;
723
724                 /*
725                  * If the hunks were not edited, and overlap, we can simply
726                  * extend the line range.
727                  */
728                 if (merged->start < hunk->start && merged->end > hunk->start) {
729                         merged->end = hunk->end;
730                         merged->colored_end = hunk->colored_end;
731                         delta = 0;
732                 } else {
733                         const char *plain = s->plain.buf;
734                         size_t  overlapping_line_count = header->new_offset
735                                 + header->new_count - merged->delta
736                                 - next->new_offset;
737                         size_t overlap_end = hunk->start;
738                         size_t overlap_start = overlap_end;
739                         size_t overlap_next, len, j;
740
741                         /*
742                          * One of the hunks was edited: the modified hunk was
743                          * appended to the strbuf `s->plain`.
744                          *
745                          * Let's ensure that at least the last context line of
746                          * the first hunk overlaps with the corresponding line
747                          * of the second hunk, and then merge.
748                          */
749                         for (j = 0; j < overlapping_line_count; j++) {
750                                 overlap_next = find_next_line(&s->plain,
751                                                               overlap_end);
752
753                                 if (overlap_next > hunk->end)
754                                         BUG("failed to find %d context lines "
755                                             "in:\n%.*s",
756                                             (int)overlapping_line_count,
757                                             (int)(hunk->end - hunk->start),
758                                             plain + hunk->start);
759
760                                 if (plain[overlap_end] != ' ')
761                                         return error(_("expected context line "
762                                                        "#%d in\n%.*s"),
763                                                      (int)(j + 1),
764                                                      (int)(hunk->end
765                                                            - hunk->start),
766                                                      plain + hunk->start);
767
768                                 overlap_start = overlap_end;
769                                 overlap_end = overlap_next;
770                         }
771                         len = overlap_end - overlap_start;
772
773                         if (len > merged->end - merged->start ||
774                             memcmp(plain + merged->end - len,
775                                    plain + overlap_start, len))
776                                 return error(_("hunks do not overlap:\n%.*s\n"
777                                                "\tdoes not end with:\n%.*s"),
778                                              (int)(merged->end - merged->start),
779                                              plain + merged->start,
780                                              (int)len, plain + overlap_start);
781
782                         /*
783                          * Since the start-end ranges are not adjacent, we
784                          * cannot simply take the union of the ranges. To
785                          * address that, we temporarily append the union of the
786                          * lines to the `plain` strbuf.
787                          */
788                         if (merged->end != s->plain.len) {
789                                 size_t start = s->plain.len;
790
791                                 strbuf_add(&s->plain, plain + merged->start,
792                                            merged->end - merged->start);
793                                 plain = s->plain.buf;
794                                 merged->start = start;
795                                 merged->end = s->plain.len;
796                         }
797
798                         strbuf_add(&s->plain,
799                                    plain + overlap_end,
800                                    hunk->end - overlap_end);
801                         merged->end = s->plain.len;
802                         merged->splittable_into += hunk->splittable_into;
803                         delta = merged->delta;
804                         merged->delta += hunk->delta;
805                 }
806
807                 header->old_count = next->old_offset + next->old_count
808                         - header->old_offset;
809                 header->new_count = next->new_offset + delta
810                         + next->new_count - header->new_offset;
811         }
812
813         if (i == *hunk_index)
814                 return 0;
815
816         *hunk_index = i;
817         return 1;
818 }
819
820 static void reassemble_patch(struct add_p_state *s,
821                              struct file_diff *file_diff, int use_all,
822                              struct strbuf *out)
823 {
824         struct hunk *hunk;
825         size_t save_len = s->plain.len, i;
826         ssize_t delta = 0;
827
828         render_diff_header(s, file_diff, 0, out);
829
830         for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
831                 struct hunk merged = { 0 };
832
833                 hunk = file_diff->hunk + i;
834                 if (!use_all && hunk->use != USE_HUNK)
835                         delta += hunk->header.old_count
836                                 - hunk->header.new_count;
837                 else {
838                         /* merge overlapping hunks into a temporary hunk */
839                         if (merge_hunks(s, file_diff, &i, use_all, &merged))
840                                 hunk = &merged;
841
842                         render_hunk(s, hunk, delta, 0, out);
843
844                         /*
845                          * In case `merge_hunks()` used `plain` as a scratch
846                          * pad (this happens when an edited hunk had to be
847                          * coalesced with another hunk).
848                          */
849                         strbuf_setlen(&s->plain, save_len);
850
851                         delta += hunk->delta;
852                 }
853         }
854 }
855
856 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
857                        size_t hunk_index)
858 {
859         int colored = !!s->colored.len, first = 1;
860         struct hunk *hunk = file_diff->hunk + hunk_index;
861         size_t splittable_into;
862         size_t end, colored_end, current, colored_current = 0, context_line_count;
863         struct hunk_header remaining, *header;
864         char marker, ch;
865
866         if (hunk_index >= file_diff->hunk_nr)
867                 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
868                     (int)hunk_index, (int)file_diff->hunk_nr);
869
870         if (hunk->splittable_into < 2)
871                 return 0;
872         splittable_into = hunk->splittable_into;
873
874         end = hunk->end;
875         colored_end = hunk->colored_end;
876
877         remaining = hunk->header;
878
879         file_diff->hunk_nr += splittable_into - 1;
880         ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
881         if (hunk_index + splittable_into < file_diff->hunk_nr)
882                 memmove(file_diff->hunk + hunk_index + splittable_into,
883                         file_diff->hunk + hunk_index + 1,
884                         (file_diff->hunk_nr - hunk_index - splittable_into)
885                         * sizeof(*hunk));
886         hunk = file_diff->hunk + hunk_index;
887         hunk->splittable_into = 1;
888         memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
889
890         header = &hunk->header;
891         header->old_count = header->new_count = 0;
892
893         current = hunk->start;
894         if (colored)
895                 colored_current = hunk->colored_start;
896         marker = '\0';
897         context_line_count = 0;
898
899         while (splittable_into > 1) {
900                 ch = s->plain.buf[current];
901
902                 if (!ch)
903                         BUG("buffer overrun while splitting hunks");
904
905                 /*
906                  * Is this the first context line after a chain of +/- lines?
907                  * Then record the start of the next split hunk.
908                  */
909                 if ((marker == '-' || marker == '+') && ch == ' ') {
910                         first = 0;
911                         hunk[1].start = current;
912                         if (colored)
913                                 hunk[1].colored_start = colored_current;
914                         context_line_count = 0;
915                 }
916
917                 /*
918                  * Was the previous line a +/- one? Alternatively, is this the
919                  * first line (and not a +/- one)?
920                  *
921                  * Then just increment the appropriate counter and continue
922                  * with the next line.
923                  */
924                 if (marker != ' ' || (ch != '-' && ch != '+')) {
925 next_hunk_line:
926                         /* Comment lines are attached to the previous line */
927                         if (ch == '\\')
928                                 ch = marker ? marker : ' ';
929
930                         /* current hunk not done yet */
931                         if (ch == ' ')
932                                 context_line_count++;
933                         else if (ch == '-')
934                                 header->old_count++;
935                         else if (ch == '+')
936                                 header->new_count++;
937                         else
938                                 BUG("unhandled diff marker: '%c'", ch);
939                         marker = ch;
940                         current = find_next_line(&s->plain, current);
941                         if (colored)
942                                 colored_current =
943                                         find_next_line(&s->colored,
944                                                        colored_current);
945                         continue;
946                 }
947
948                 /*
949                  * We got us the start of a new hunk!
950                  *
951                  * This is a context line, so it is shared with the previous
952                  * hunk, if any.
953                  */
954
955                 if (first) {
956                         if (header->old_count || header->new_count)
957                                 BUG("counts are off: %d/%d",
958                                     (int)header->old_count,
959                                     (int)header->new_count);
960
961                         header->old_count = context_line_count;
962                         header->new_count = context_line_count;
963                         context_line_count = 0;
964                         first = 0;
965                         goto next_hunk_line;
966                 }
967
968                 remaining.old_offset += header->old_count;
969                 remaining.old_count -= header->old_count;
970                 remaining.new_offset += header->new_count;
971                 remaining.new_count -= header->new_count;
972
973                 /* initialize next hunk header's offsets */
974                 hunk[1].header.old_offset =
975                         header->old_offset + header->old_count;
976                 hunk[1].header.new_offset =
977                         header->new_offset + header->new_count;
978
979                 /* add one split hunk */
980                 header->old_count += context_line_count;
981                 header->new_count += context_line_count;
982
983                 hunk->end = current;
984                 if (colored)
985                         hunk->colored_end = colored_current;
986
987                 hunk++;
988                 hunk->splittable_into = 1;
989                 hunk->use = hunk[-1].use;
990                 header = &hunk->header;
991
992                 header->old_count = header->new_count = context_line_count;
993                 context_line_count = 0;
994
995                 splittable_into--;
996                 marker = ch;
997         }
998
999         /* last hunk simply gets the rest */
1000         if (header->old_offset != remaining.old_offset)
1001                 BUG("miscounted old_offset: %lu != %lu",
1002                     header->old_offset, remaining.old_offset);
1003         if (header->new_offset != remaining.new_offset)
1004                 BUG("miscounted new_offset: %lu != %lu",
1005                     header->new_offset, remaining.new_offset);
1006         header->old_count = remaining.old_count;
1007         header->new_count = remaining.new_count;
1008         hunk->end = end;
1009         if (colored)
1010                 hunk->colored_end = colored_end;
1011
1012         return 0;
1013 }
1014
1015 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1016 {
1017         const char *plain = s->plain.buf;
1018         size_t current, eol, next;
1019
1020         if (!s->colored.len)
1021                 return;
1022
1023         hunk->colored_start = s->colored.len;
1024         for (current = hunk->start; current < hunk->end; ) {
1025                 for (eol = current; eol < hunk->end; eol++)
1026                         if (plain[eol] == '\n')
1027                                 break;
1028                 next = eol + (eol < hunk->end);
1029                 if (eol > current && plain[eol - 1] == '\r')
1030                         eol--;
1031
1032                 strbuf_addstr(&s->colored,
1033                               plain[current] == '-' ?
1034                               s->s.file_old_color :
1035                               plain[current] == '+' ?
1036                               s->s.file_new_color :
1037                               s->s.context_color);
1038                 strbuf_add(&s->colored, plain + current, eol - current);
1039                 strbuf_addstr(&s->colored, GIT_COLOR_RESET);
1040                 if (next > eol)
1041                         strbuf_add(&s->colored, plain + eol, next - eol);
1042                 current = next;
1043         }
1044         hunk->colored_end = s->colored.len;
1045 }
1046
1047 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1048 {
1049         size_t i;
1050
1051         strbuf_reset(&s->buf);
1052         strbuf_commented_addf(&s->buf, _("Manual hunk edit mode -- see bottom for "
1053                                       "a quick guide.\n"));
1054         render_hunk(s, hunk, 0, 0, &s->buf);
1055         strbuf_commented_addf(&s->buf,
1056                               _("---\n"
1057                                 "To remove '%c' lines, make them ' ' lines "
1058                                 "(context).\n"
1059                                 "To remove '%c' lines, delete them.\n"
1060                                 "Lines starting with %c will be removed.\n"),
1061                               s->mode->is_reverse ? '+' : '-',
1062                               s->mode->is_reverse ? '-' : '+',
1063                               comment_line_char);
1064         strbuf_commented_addf(&s->buf, "%s", _(s->mode->edit_hunk_hint));
1065         /*
1066          * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1067          * messages.
1068          */
1069         strbuf_commented_addf(&s->buf,
1070                               _("If it does not apply cleanly, you will be "
1071                                 "given an opportunity to\n"
1072                                 "edit again.  If all lines of the hunk are "
1073                                 "removed, then the edit is\n"
1074                                 "aborted and the hunk is left unchanged.\n"));
1075
1076         if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1077                 return -1;
1078
1079         /* strip out commented lines */
1080         hunk->start = s->plain.len;
1081         for (i = 0; i < s->buf.len; ) {
1082                 size_t next = find_next_line(&s->buf, i);
1083
1084                 if (s->buf.buf[i] != comment_line_char)
1085                         strbuf_add(&s->plain, s->buf.buf + i, next - i);
1086                 i = next;
1087         }
1088
1089         hunk->end = s->plain.len;
1090         if (hunk->end == hunk->start)
1091                 /* The user aborted editing by deleting everything */
1092                 return 0;
1093
1094         recolor_hunk(s, hunk);
1095
1096         /*
1097          * If the hunk header is intact, parse it, otherwise simply use the
1098          * hunk header prior to editing (which will adjust `hunk->start` to
1099          * skip the hunk header).
1100          */
1101         if (s->plain.buf[hunk->start] == '@' &&
1102             parse_hunk_header(s, hunk) < 0)
1103                 return error(_("could not parse hunk header"));
1104
1105         return 1;
1106 }
1107
1108 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1109                                    size_t orig_old_count, size_t orig_new_count)
1110 {
1111         struct hunk_header *header = &hunk->header;
1112         size_t i;
1113
1114         header->old_count = header->new_count = 0;
1115         for (i = hunk->start; i < hunk->end; ) {
1116                 switch (s->plain.buf[i]) {
1117                 case '-':
1118                         header->old_count++;
1119                         break;
1120                 case '+':
1121                         header->new_count++;
1122                         break;
1123                 case ' ': case '\r': case '\n':
1124                         header->old_count++;
1125                         header->new_count++;
1126                         break;
1127                 }
1128
1129                 i = find_next_line(&s->plain, i);
1130         }
1131
1132         return orig_old_count - orig_new_count
1133                 - header->old_count + header->new_count;
1134 }
1135
1136 static int run_apply_check(struct add_p_state *s,
1137                            struct file_diff *file_diff)
1138 {
1139         struct child_process cp = CHILD_PROCESS_INIT;
1140
1141         strbuf_reset(&s->buf);
1142         reassemble_patch(s, file_diff, 1, &s->buf);
1143
1144         setup_child_process(s, &cp,
1145                             "apply", "--check", NULL);
1146         argv_array_pushv(&cp.args, s->mode->apply_check_args);
1147         if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1148                 return error(_("'git apply --cached' failed"));
1149
1150         return 0;
1151 }
1152
1153 static int read_single_character(struct add_p_state *s)
1154 {
1155         if (s->s.use_single_key) {
1156                 int res = read_key_without_echo(&s->answer);
1157                 printf("%s\n", res == EOF ? "" : s->answer.buf);
1158                 return res;
1159         }
1160
1161         if (strbuf_getline(&s->answer, stdin) == EOF)
1162                 return EOF;
1163         strbuf_trim_trailing_newline(&s->answer);
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 }