t2400: rewrite regex to avoid unintentional PCRE
[git.git] / add-patch.c
blob1e1ee2df59674ebf5340ae77b8e00a3de30f1947
1 #include "cache.h"
2 #include "add-interactive.h"
3 #include "alloc.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "strbuf.h"
7 #include "run-command.h"
8 #include "strvec.h"
9 #include "pathspec.h"
10 #include "color.h"
11 #include "diff.h"
12 #include "compat/terminal.h"
13 #include "prompt.h"
15 enum prompt_mode_type {
16 PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_ADDITION, PROMPT_HUNK,
17 PROMPT_MODE_MAX, /* must be last */
20 struct patch_mode {
22 * The magic constant 4 is chosen such that all patch modes
23 * provide enough space for three command-line arguments followed by a
24 * trailing `NULL`.
26 const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
27 unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
28 const char *prompt_mode[PROMPT_MODE_MAX];
29 const char *edit_hunk_hint, *help_patch_text;
32 static struct patch_mode patch_mode_add = {
33 .diff_cmd = { "diff-files", NULL },
34 .apply_args = { "--cached", NULL },
35 .apply_check_args = { "--cached", NULL },
36 .prompt_mode = {
37 N_("Stage mode change [y,n,q,a,d%s,?]? "),
38 N_("Stage deletion [y,n,q,a,d%s,?]? "),
39 N_("Stage addition [y,n,q,a,d%s,?]? "),
40 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
42 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
43 "will immediately be marked for staging."),
44 .help_patch_text =
45 N_("y - stage this hunk\n"
46 "n - do not stage this hunk\n"
47 "q - quit; do not stage this hunk or any of the remaining "
48 "ones\n"
49 "a - stage this hunk and all later hunks in the file\n"
50 "d - do not stage this hunk or any of the later hunks in "
51 "the file\n")
54 static struct patch_mode patch_mode_stash = {
55 .diff_cmd = { "diff-index", "HEAD", NULL },
56 .apply_args = { "--cached", NULL },
57 .apply_check_args = { "--cached", NULL },
58 .prompt_mode = {
59 N_("Stash mode change [y,n,q,a,d%s,?]? "),
60 N_("Stash deletion [y,n,q,a,d%s,?]? "),
61 N_("Stash addition [y,n,q,a,d%s,?]? "),
62 N_("Stash this hunk [y,n,q,a,d%s,?]? "),
64 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
65 "will immediately be marked for stashing."),
66 .help_patch_text =
67 N_("y - stash this hunk\n"
68 "n - do not stash this hunk\n"
69 "q - quit; do not stash this hunk or any of the remaining "
70 "ones\n"
71 "a - stash this hunk and all later hunks in the file\n"
72 "d - do not stash this hunk or any of the later hunks in "
73 "the file\n"),
76 static struct patch_mode patch_mode_reset_head = {
77 .diff_cmd = { "diff-index", "--cached", NULL },
78 .apply_args = { "-R", "--cached", NULL },
79 .apply_check_args = { "-R", "--cached", NULL },
80 .is_reverse = 1,
81 .index_only = 1,
82 .prompt_mode = {
83 N_("Unstage mode change [y,n,q,a,d%s,?]? "),
84 N_("Unstage deletion [y,n,q,a,d%s,?]? "),
85 N_("Unstage addition [y,n,q,a,d%s,?]? "),
86 N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
88 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
89 "will immediately be marked for unstaging."),
90 .help_patch_text =
91 N_("y - unstage this hunk\n"
92 "n - do not unstage this hunk\n"
93 "q - quit; do not unstage this hunk or any of the remaining "
94 "ones\n"
95 "a - unstage this hunk and all later hunks in the file\n"
96 "d - do not unstage this hunk or any of the later hunks in "
97 "the file\n"),
100 static struct patch_mode patch_mode_reset_nothead = {
101 .diff_cmd = { "diff-index", "-R", "--cached", NULL },
102 .apply_args = { "--cached", NULL },
103 .apply_check_args = { "--cached", NULL },
104 .index_only = 1,
105 .prompt_mode = {
106 N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
107 N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
108 N_("Apply addition to index [y,n,q,a,d%s,?]? "),
109 N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
111 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
112 "will immediately be marked for applying."),
113 .help_patch_text =
114 N_("y - apply this hunk to index\n"
115 "n - do not apply this hunk to index\n"
116 "q - quit; do not apply this hunk or any of the remaining "
117 "ones\n"
118 "a - apply this hunk and all later hunks in the file\n"
119 "d - do not apply this hunk or any of the later hunks in "
120 "the file\n"),
123 static struct patch_mode patch_mode_checkout_index = {
124 .diff_cmd = { "diff-files", NULL },
125 .apply_args = { "-R", NULL },
126 .apply_check_args = { "-R", NULL },
127 .is_reverse = 1,
128 .prompt_mode = {
129 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
130 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
131 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
132 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
134 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
135 "will immediately be marked for discarding."),
136 .help_patch_text =
137 N_("y - discard this hunk from worktree\n"
138 "n - do not discard this hunk from worktree\n"
139 "q - quit; do not discard this hunk or any of the remaining "
140 "ones\n"
141 "a - discard this hunk and all later hunks in the file\n"
142 "d - do not discard this hunk or any of the later hunks in "
143 "the file\n"),
146 static struct patch_mode patch_mode_checkout_head = {
147 .diff_cmd = { "diff-index", NULL },
148 .apply_for_checkout = 1,
149 .apply_check_args = { "-R", NULL },
150 .is_reverse = 1,
151 .prompt_mode = {
152 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
153 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
154 N_("Discard addition from index and worktree [y,n,q,a,d%s,?]? "),
155 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
157 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
158 "will immediately be marked for discarding."),
159 .help_patch_text =
160 N_("y - discard this hunk from index and worktree\n"
161 "n - do not discard this hunk from index and worktree\n"
162 "q - quit; do not discard this hunk or any of the remaining "
163 "ones\n"
164 "a - discard this hunk and all later hunks in the file\n"
165 "d - do not discard this hunk or any of the later hunks in "
166 "the file\n"),
169 static struct patch_mode patch_mode_checkout_nothead = {
170 .diff_cmd = { "diff-index", "-R", NULL },
171 .apply_for_checkout = 1,
172 .apply_check_args = { NULL },
173 .prompt_mode = {
174 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
175 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
176 N_("Apply addition to index and worktree [y,n,q,a,d%s,?]? "),
177 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
179 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
180 "will immediately be marked for applying."),
181 .help_patch_text =
182 N_("y - apply this hunk to index and worktree\n"
183 "n - do not apply this hunk to index and worktree\n"
184 "q - quit; do not apply this hunk or any of the remaining "
185 "ones\n"
186 "a - apply this hunk and all later hunks in the file\n"
187 "d - do not apply this hunk or any of the later hunks in "
188 "the file\n"),
191 static struct patch_mode patch_mode_worktree_head = {
192 .diff_cmd = { "diff-index", NULL },
193 .apply_args = { "-R", NULL },
194 .apply_check_args = { "-R", NULL },
195 .is_reverse = 1,
196 .prompt_mode = {
197 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
198 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
199 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
200 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
202 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
203 "will immediately be marked for discarding."),
204 .help_patch_text =
205 N_("y - discard this hunk from worktree\n"
206 "n - do not discard this hunk from worktree\n"
207 "q - quit; do not discard this hunk or any of the remaining "
208 "ones\n"
209 "a - discard this hunk and all later hunks in the file\n"
210 "d - do not discard this hunk or any of the later hunks in "
211 "the file\n"),
214 static struct patch_mode patch_mode_worktree_nothead = {
215 .diff_cmd = { "diff-index", "-R", NULL },
216 .apply_args = { NULL },
217 .apply_check_args = { NULL },
218 .prompt_mode = {
219 N_("Apply mode change to worktree [y,n,q,a,d%s,?]? "),
220 N_("Apply deletion to worktree [y,n,q,a,d%s,?]? "),
221 N_("Apply addition to worktree [y,n,q,a,d%s,?]? "),
222 N_("Apply this hunk to worktree [y,n,q,a,d%s,?]? "),
224 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
225 "will immediately be marked for applying."),
226 .help_patch_text =
227 N_("y - apply this hunk to worktree\n"
228 "n - do not apply this hunk to worktree\n"
229 "q - quit; do not apply this hunk or any of the remaining "
230 "ones\n"
231 "a - apply this hunk and all later hunks in the file\n"
232 "d - do not apply this hunk or any of the later hunks in "
233 "the file\n"),
236 struct hunk_header {
237 unsigned long old_offset, old_count, new_offset, new_count;
239 * Start/end offsets to the extra text after the second `@@` in the
240 * hunk header, e.g. the function signature. This is expected to
241 * include the newline.
243 size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
244 unsigned suppress_colored_line_range:1;
247 struct hunk {
248 size_t start, end, colored_start, colored_end, splittable_into;
249 ssize_t delta;
250 enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
251 struct hunk_header header;
254 struct add_p_state {
255 struct add_i_state s;
256 struct strbuf answer, buf;
258 /* parsed diff */
259 struct strbuf plain, colored;
260 struct file_diff {
261 struct hunk head;
262 struct hunk *hunk;
263 size_t hunk_nr, hunk_alloc;
264 unsigned deleted:1, added:1, mode_change:1,binary:1;
265 } *file_diff;
266 size_t file_diff_nr;
268 /* patch mode */
269 struct patch_mode *mode;
270 const char *revision;
273 static void add_p_state_clear(struct add_p_state *s)
275 size_t i;
277 strbuf_release(&s->answer);
278 strbuf_release(&s->buf);
279 strbuf_release(&s->plain);
280 strbuf_release(&s->colored);
281 for (i = 0; i < s->file_diff_nr; i++)
282 free(s->file_diff[i].hunk);
283 free(s->file_diff);
284 clear_add_i_state(&s->s);
287 __attribute__((format (printf, 2, 3)))
288 static void err(struct add_p_state *s, const char *fmt, ...)
290 va_list args;
292 va_start(args, fmt);
293 fputs(s->s.error_color, stderr);
294 vfprintf(stderr, fmt, args);
295 fputs(s->s.reset_color, stderr);
296 fputc('\n', stderr);
297 va_end(args);
300 static void setup_child_process(struct add_p_state *s,
301 struct child_process *cp, ...)
303 va_list ap;
304 const char *arg;
306 va_start(ap, cp);
307 while ((arg = va_arg(ap, const char *)))
308 strvec_push(&cp->args, arg);
309 va_end(ap);
311 cp->git_cmd = 1;
312 strvec_pushf(&cp->env,
313 INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
316 static int parse_range(const char **p,
317 unsigned long *offset, unsigned long *count)
319 char *pend;
321 *offset = strtoul(*p, &pend, 10);
322 if (pend == *p)
323 return -1;
324 if (*pend != ',') {
325 *count = 1;
326 *p = pend;
327 return 0;
329 *count = strtoul(pend + 1, (char **)p, 10);
330 return *p == pend + 1 ? -1 : 0;
333 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
335 struct hunk_header *header = &hunk->header;
336 const char *line = s->plain.buf + hunk->start, *p = line;
337 char *eol = memchr(p, '\n', s->plain.len - hunk->start);
339 if (!eol)
340 eol = s->plain.buf + s->plain.len;
342 if (!skip_prefix(p, "@@ -", &p) ||
343 parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
344 !skip_prefix(p, " +", &p) ||
345 parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
346 !skip_prefix(p, " @@", &p))
347 return error(_("could not parse hunk header '%.*s'"),
348 (int)(eol - line), line);
350 hunk->start = eol - s->plain.buf + (*eol == '\n');
351 header->extra_start = p - s->plain.buf;
352 header->extra_end = hunk->start;
354 if (!s->colored.len) {
355 header->colored_extra_start = header->colored_extra_end = 0;
356 return 0;
359 /* Now find the extra text in the colored diff */
360 line = s->colored.buf + hunk->colored_start;
361 eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
362 if (!eol)
363 eol = s->colored.buf + s->colored.len;
364 p = memmem(line, eol - line, "@@ -", 4);
365 if (p && (p = memmem(p + 4, eol - p - 4, " @@", 3))) {
366 header->colored_extra_start = p + 3 - s->colored.buf;
367 } else {
368 /* could not parse colored hunk header, leave as-is */
369 header->colored_extra_start = hunk->colored_start;
370 header->suppress_colored_line_range = 1;
372 hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
373 header->colored_extra_end = hunk->colored_start;
375 return 0;
378 static int is_octal(const char *p, size_t len)
380 if (!len)
381 return 0;
383 while (len--)
384 if (*p < '0' || *(p++) > '7')
385 return 0;
386 return 1;
389 static void complete_file(char marker, struct hunk *hunk)
391 if (marker == '-' || marker == '+')
393 * Last hunk ended in non-context line (i.e. it
394 * appended lines to the file, so there are no
395 * trailing context lines).
397 hunk->splittable_into++;
400 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
402 struct strvec args = STRVEC_INIT;
403 const char *diff_algorithm = s->s.interactive_diff_algorithm;
404 struct strbuf *plain = &s->plain, *colored = NULL;
405 struct child_process cp = CHILD_PROCESS_INIT;
406 char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
407 size_t file_diff_alloc = 0, i, color_arg_index;
408 struct file_diff *file_diff = NULL;
409 struct hunk *hunk = NULL;
410 int res;
412 strvec_pushv(&args, s->mode->diff_cmd);
413 if (diff_algorithm)
414 strvec_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
415 if (s->revision) {
416 struct object_id oid;
417 strvec_push(&args,
418 /* could be on an unborn branch */
419 !strcmp("HEAD", s->revision) &&
420 repo_get_oid(the_repository, "HEAD", &oid) ?
421 empty_tree_oid_hex() : s->revision);
423 color_arg_index = args.nr;
424 /* Use `--no-color` explicitly, just in case `diff.color = always`. */
425 strvec_pushl(&args, "--no-color", "--ignore-submodules=dirty", "-p",
426 "--", NULL);
427 for (i = 0; i < ps->nr; i++)
428 strvec_push(&args, ps->items[i].original);
430 setup_child_process(s, &cp, NULL);
431 strvec_pushv(&cp.args, args.v);
432 res = capture_command(&cp, plain, 0);
433 if (res) {
434 strvec_clear(&args);
435 return error(_("could not parse diff"));
437 if (!plain->len) {
438 strvec_clear(&args);
439 return 0;
441 strbuf_complete_line(plain);
443 if (want_color_fd(1, -1)) {
444 struct child_process colored_cp = CHILD_PROCESS_INIT;
445 const char *diff_filter = s->s.interactive_diff_filter;
447 setup_child_process(s, &colored_cp, NULL);
448 xsnprintf((char *)args.v[color_arg_index], 8, "--color");
449 strvec_pushv(&colored_cp.args, args.v);
450 colored = &s->colored;
451 res = capture_command(&colored_cp, colored, 0);
452 strvec_clear(&args);
453 if (res)
454 return error(_("could not parse colored diff"));
456 if (diff_filter) {
457 struct child_process filter_cp = CHILD_PROCESS_INIT;
459 setup_child_process(s, &filter_cp,
460 diff_filter, NULL);
461 filter_cp.git_cmd = 0;
462 filter_cp.use_shell = 1;
463 strbuf_reset(&s->buf);
464 if (pipe_command(&filter_cp,
465 colored->buf, colored->len,
466 &s->buf, colored->len,
467 NULL, 0) < 0)
468 return error(_("failed to run '%s'"),
469 diff_filter);
470 strbuf_swap(colored, &s->buf);
473 strbuf_complete_line(colored);
474 colored_p = colored->buf;
475 colored_pend = colored_p + colored->len;
477 strvec_clear(&args);
479 /* parse files and hunks */
480 p = plain->buf;
481 pend = p + plain->len;
482 while (p != pend) {
483 char *eol = memchr(p, '\n', pend - p);
484 const char *deleted = NULL, *mode_change = NULL;
486 if (!eol)
487 eol = pend;
489 if (starts_with(p, "diff ") ||
490 starts_with(p, "* Unmerged path ")) {
491 complete_file(marker, hunk);
492 ALLOC_GROW_BY(s->file_diff, s->file_diff_nr, 1,
493 file_diff_alloc);
494 file_diff = s->file_diff + s->file_diff_nr - 1;
495 hunk = &file_diff->head;
496 hunk->start = p - plain->buf;
497 if (colored_p)
498 hunk->colored_start = colored_p - colored->buf;
499 marker = '\0';
500 } else if (p == plain->buf)
501 BUG("diff starts with unexpected line:\n"
502 "%.*s\n", (int)(eol - p), p);
503 else if (file_diff->deleted)
504 ; /* keep the rest of the file in a single "hunk" */
505 else if (starts_with(p, "@@ ") ||
506 (hunk == &file_diff->head &&
507 (skip_prefix(p, "deleted file", &deleted)))) {
508 if (marker == '-' || marker == '+')
510 * Should not happen; previous hunk did not end
511 * in a context line? Handle it anyway.
513 hunk->splittable_into++;
515 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
516 file_diff->hunk_alloc);
517 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
519 hunk->start = p - plain->buf;
520 if (colored)
521 hunk->colored_start = colored_p - colored->buf;
523 if (deleted)
524 file_diff->deleted = 1;
525 else if (parse_hunk_header(s, hunk) < 0)
526 return -1;
529 * Start counting into how many hunks this one can be
530 * split
532 marker = *p;
533 } else if (hunk == &file_diff->head &&
534 starts_with(p, "new file")) {
535 file_diff->added = 1;
536 } else if (hunk == &file_diff->head &&
537 skip_prefix(p, "old mode ", &mode_change) &&
538 is_octal(mode_change, eol - mode_change)) {
539 if (file_diff->mode_change)
540 BUG("double mode change?\n\n%.*s",
541 (int)(eol - plain->buf), plain->buf);
542 if (file_diff->hunk_nr)
543 BUG("mode change in the middle?\n\n%.*s",
544 (int)(eol - plain->buf), plain->buf);
547 * Do *not* change `hunk`: the mode change pseudo-hunk
548 * is _part of_ the header "hunk".
550 file_diff->mode_change = 1;
551 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
552 file_diff->hunk_alloc);
553 file_diff->hunk->start = p - plain->buf;
554 if (colored_p)
555 file_diff->hunk->colored_start =
556 colored_p - colored->buf;
557 } else if (hunk == &file_diff->head &&
558 skip_prefix(p, "new mode ", &mode_change) &&
559 is_octal(mode_change, eol - mode_change)) {
562 * Extend the "mode change" pseudo-hunk to include also
563 * the "new mode" line.
565 if (!file_diff->mode_change)
566 BUG("'new mode' without 'old mode'?\n\n%.*s",
567 (int)(eol - plain->buf), plain->buf);
568 if (file_diff->hunk_nr != 1)
569 BUG("mode change in the middle?\n\n%.*s",
570 (int)(eol - plain->buf), plain->buf);
571 if (p - plain->buf != file_diff->hunk->end)
572 BUG("'new mode' does not immediately follow "
573 "'old mode'?\n\n%.*s",
574 (int)(eol - plain->buf), plain->buf);
575 } else if (hunk == &file_diff->head &&
576 starts_with(p, "Binary files "))
577 file_diff->binary = 1;
579 if (!!file_diff->deleted + !!file_diff->added +
580 !!file_diff->mode_change > 1)
581 BUG("diff can only contain delete *or* add *or* a "
582 "mode change?!?\n%.*s",
583 (int)(eol - (plain->buf + file_diff->head.start)),
584 plain->buf + file_diff->head.start);
586 if ((marker == '-' || marker == '+') && *p == ' ')
587 hunk->splittable_into++;
588 if (marker && *p != '\\')
589 marker = *p;
591 p = eol == pend ? pend : eol + 1;
592 hunk->end = p - plain->buf;
594 if (colored) {
595 char *colored_eol = memchr(colored_p, '\n',
596 colored_pend - colored_p);
597 if (colored_eol)
598 colored_p = colored_eol + 1;
599 else if (p != pend)
600 /* non-colored has more lines? */
601 goto mismatched_output;
602 else if (colored_p == colored_pend)
603 /* last line has no matching colored one? */
604 goto mismatched_output;
605 else
606 colored_p = colored_pend;
608 hunk->colored_end = colored_p - colored->buf;
611 if (mode_change) {
612 if (file_diff->hunk_nr != 1)
613 BUG("mode change in hunk #%d???",
614 (int)file_diff->hunk_nr);
615 /* Adjust the end of the "mode change" pseudo-hunk */
616 file_diff->hunk->end = hunk->end;
617 if (colored)
618 file_diff->hunk->colored_end = hunk->colored_end;
621 complete_file(marker, hunk);
623 /* non-colored shorter than colored? */
624 if (colored_p != colored_pend) {
625 mismatched_output:
626 error(_("mismatched output from interactive.diffFilter"));
627 advise(_("Your filter must maintain a one-to-one correspondence\n"
628 "between its input and output lines."));
629 return -1;
632 return 0;
635 static size_t find_next_line(struct strbuf *sb, size_t offset)
637 char *eol;
639 if (offset >= sb->len)
640 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
641 (int)offset, (int)sb->len, sb->buf);
643 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
644 if (!eol)
645 return sb->len;
646 return eol - sb->buf + 1;
649 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
650 ssize_t delta, int colored, struct strbuf *out)
652 struct hunk_header *header = &hunk->header;
654 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
656 * Generate the hunk header dynamically, except for special
657 * hunks (such as the diff header).
659 const char *p;
660 size_t len;
661 unsigned long old_offset = header->old_offset;
662 unsigned long new_offset = header->new_offset;
664 if (!colored) {
665 p = s->plain.buf + header->extra_start;
666 len = header->extra_end - header->extra_start;
667 } else if (header->suppress_colored_line_range) {
668 strbuf_add(out,
669 s->colored.buf + header->colored_extra_start,
670 header->colored_extra_end -
671 header->colored_extra_start);
673 strbuf_add(out, s->colored.buf + hunk->colored_start,
674 hunk->colored_end - hunk->colored_start);
675 return;
676 } else {
677 strbuf_addstr(out, s->s.fraginfo_color);
678 p = s->colored.buf + header->colored_extra_start;
679 len = header->colored_extra_end
680 - header->colored_extra_start;
683 if (s->mode->is_reverse)
684 old_offset -= delta;
685 else
686 new_offset += delta;
688 strbuf_addf(out, "@@ -%lu", old_offset);
689 if (header->old_count != 1)
690 strbuf_addf(out, ",%lu", header->old_count);
691 strbuf_addf(out, " +%lu", new_offset);
692 if (header->new_count != 1)
693 strbuf_addf(out, ",%lu", header->new_count);
694 strbuf_addstr(out, " @@");
696 if (len)
697 strbuf_add(out, p, len);
698 else if (colored)
699 strbuf_addf(out, "%s\n", s->s.reset_color);
700 else
701 strbuf_addch(out, '\n');
704 if (colored)
705 strbuf_add(out, s->colored.buf + hunk->colored_start,
706 hunk->colored_end - hunk->colored_start);
707 else
708 strbuf_add(out, s->plain.buf + hunk->start,
709 hunk->end - hunk->start);
712 static void render_diff_header(struct add_p_state *s,
713 struct file_diff *file_diff, int colored,
714 struct strbuf *out)
717 * If there was a mode change, the first hunk is a pseudo hunk that
718 * corresponds to the mode line in the header. If the user did not want
719 * to stage that "hunk", we actually have to cut it out from the header.
721 int skip_mode_change =
722 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
723 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
725 if (!skip_mode_change) {
726 render_hunk(s, head, 0, colored, out);
727 return;
730 if (colored) {
731 const char *p = s->colored.buf;
733 strbuf_add(out, p + head->colored_start,
734 first->colored_start - head->colored_start);
735 strbuf_add(out, p + first->colored_end,
736 head->colored_end - first->colored_end);
737 } else {
738 const char *p = s->plain.buf;
740 strbuf_add(out, p + head->start, first->start - head->start);
741 strbuf_add(out, p + first->end, head->end - first->end);
745 /* Coalesce hunks again that were split */
746 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
747 size_t *hunk_index, int use_all, struct hunk *merged)
749 size_t i = *hunk_index, delta;
750 struct hunk *hunk = file_diff->hunk + i;
751 /* `header` corresponds to the merged hunk */
752 struct hunk_header *header = &merged->header, *next;
754 if (!use_all && hunk->use != USE_HUNK)
755 return 0;
757 *merged = *hunk;
758 /* We simply skip the colored part (if any) when merging hunks */
759 merged->colored_start = merged->colored_end = 0;
761 for (; i + 1 < file_diff->hunk_nr; i++) {
762 hunk++;
763 next = &hunk->header;
766 * Stop merging hunks when:
768 * - the hunk is not selected for use, or
769 * - the hunk does not overlap with the already-merged hunk(s)
771 if ((!use_all && hunk->use != USE_HUNK) ||
772 header->new_offset >= next->new_offset + merged->delta ||
773 header->new_offset + header->new_count
774 < next->new_offset + merged->delta)
775 break;
778 * If the hunks were not edited, and overlap, we can simply
779 * extend the line range.
781 if (merged->start < hunk->start && merged->end > hunk->start) {
782 merged->end = hunk->end;
783 merged->colored_end = hunk->colored_end;
784 delta = 0;
785 } else {
786 const char *plain = s->plain.buf;
787 size_t overlapping_line_count = header->new_offset
788 + header->new_count - merged->delta
789 - next->new_offset;
790 size_t overlap_end = hunk->start;
791 size_t overlap_start = overlap_end;
792 size_t overlap_next, len, j;
795 * One of the hunks was edited: the modified hunk was
796 * appended to the strbuf `s->plain`.
798 * Let's ensure that at least the last context line of
799 * the first hunk overlaps with the corresponding line
800 * of the second hunk, and then merge.
802 for (j = 0; j < overlapping_line_count; j++) {
803 overlap_next = find_next_line(&s->plain,
804 overlap_end);
806 if (overlap_next > hunk->end)
807 BUG("failed to find %d context lines "
808 "in:\n%.*s",
809 (int)overlapping_line_count,
810 (int)(hunk->end - hunk->start),
811 plain + hunk->start);
813 if (plain[overlap_end] != ' ')
814 return error(_("expected context line "
815 "#%d in\n%.*s"),
816 (int)(j + 1),
817 (int)(hunk->end
818 - hunk->start),
819 plain + hunk->start);
821 overlap_start = overlap_end;
822 overlap_end = overlap_next;
824 len = overlap_end - overlap_start;
826 if (len > merged->end - merged->start ||
827 memcmp(plain + merged->end - len,
828 plain + overlap_start, len))
829 return error(_("hunks do not overlap:\n%.*s\n"
830 "\tdoes not end with:\n%.*s"),
831 (int)(merged->end - merged->start),
832 plain + merged->start,
833 (int)len, plain + overlap_start);
836 * Since the start-end ranges are not adjacent, we
837 * cannot simply take the union of the ranges. To
838 * address that, we temporarily append the union of the
839 * lines to the `plain` strbuf.
841 if (merged->end != s->plain.len) {
842 size_t start = s->plain.len;
844 strbuf_add(&s->plain, plain + merged->start,
845 merged->end - merged->start);
846 plain = s->plain.buf;
847 merged->start = start;
848 merged->end = s->plain.len;
851 strbuf_add(&s->plain,
852 plain + overlap_end,
853 hunk->end - overlap_end);
854 merged->end = s->plain.len;
855 merged->splittable_into += hunk->splittable_into;
856 delta = merged->delta;
857 merged->delta += hunk->delta;
860 header->old_count = next->old_offset + next->old_count
861 - header->old_offset;
862 header->new_count = next->new_offset + delta
863 + next->new_count - header->new_offset;
866 if (i == *hunk_index)
867 return 0;
869 *hunk_index = i;
870 return 1;
873 static void reassemble_patch(struct add_p_state *s,
874 struct file_diff *file_diff, int use_all,
875 struct strbuf *out)
877 struct hunk *hunk;
878 size_t save_len = s->plain.len, i;
879 ssize_t delta = 0;
881 render_diff_header(s, file_diff, 0, out);
883 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
884 struct hunk merged = { 0 };
886 hunk = file_diff->hunk + i;
887 if (!use_all && hunk->use != USE_HUNK)
888 delta += hunk->header.old_count
889 - hunk->header.new_count;
890 else {
891 /* merge overlapping hunks into a temporary hunk */
892 if (merge_hunks(s, file_diff, &i, use_all, &merged))
893 hunk = &merged;
895 render_hunk(s, hunk, delta, 0, out);
898 * In case `merge_hunks()` used `plain` as a scratch
899 * pad (this happens when an edited hunk had to be
900 * coalesced with another hunk).
902 strbuf_setlen(&s->plain, save_len);
904 delta += hunk->delta;
909 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
910 size_t hunk_index)
912 int colored = !!s->colored.len, first = 1;
913 struct hunk *hunk = file_diff->hunk + hunk_index;
914 size_t splittable_into;
915 size_t end, colored_end, current, colored_current = 0, context_line_count;
916 struct hunk_header remaining, *header;
917 char marker, ch;
919 if (hunk_index >= file_diff->hunk_nr)
920 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
921 (int)hunk_index, (int)file_diff->hunk_nr);
923 if (hunk->splittable_into < 2)
924 return 0;
925 splittable_into = hunk->splittable_into;
927 end = hunk->end;
928 colored_end = hunk->colored_end;
930 remaining = hunk->header;
932 file_diff->hunk_nr += splittable_into - 1;
933 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
934 if (hunk_index + splittable_into < file_diff->hunk_nr)
935 memmove(file_diff->hunk + hunk_index + splittable_into,
936 file_diff->hunk + hunk_index + 1,
937 (file_diff->hunk_nr - hunk_index - splittable_into)
938 * sizeof(*hunk));
939 hunk = file_diff->hunk + hunk_index;
940 hunk->splittable_into = 1;
941 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
943 header = &hunk->header;
944 header->old_count = header->new_count = 0;
946 current = hunk->start;
947 if (colored)
948 colored_current = hunk->colored_start;
949 marker = '\0';
950 context_line_count = 0;
952 while (splittable_into > 1) {
953 ch = s->plain.buf[current];
955 if (!ch)
956 BUG("buffer overrun while splitting hunks");
959 * Is this the first context line after a chain of +/- lines?
960 * Then record the start of the next split hunk.
962 if ((marker == '-' || marker == '+') && ch == ' ') {
963 first = 0;
964 hunk[1].start = current;
965 if (colored)
966 hunk[1].colored_start = colored_current;
967 context_line_count = 0;
971 * Was the previous line a +/- one? Alternatively, is this the
972 * first line (and not a +/- one)?
974 * Then just increment the appropriate counter and continue
975 * with the next line.
977 if (marker != ' ' || (ch != '-' && ch != '+')) {
978 next_hunk_line:
979 /* Comment lines are attached to the previous line */
980 if (ch == '\\')
981 ch = marker ? marker : ' ';
983 /* current hunk not done yet */
984 if (ch == ' ')
985 context_line_count++;
986 else if (ch == '-')
987 header->old_count++;
988 else if (ch == '+')
989 header->new_count++;
990 else
991 BUG("unhandled diff marker: '%c'", ch);
992 marker = ch;
993 current = find_next_line(&s->plain, current);
994 if (colored)
995 colored_current =
996 find_next_line(&s->colored,
997 colored_current);
998 continue;
1002 * We got us the start of a new hunk!
1004 * This is a context line, so it is shared with the previous
1005 * hunk, if any.
1008 if (first) {
1009 if (header->old_count || header->new_count)
1010 BUG("counts are off: %d/%d",
1011 (int)header->old_count,
1012 (int)header->new_count);
1014 header->old_count = context_line_count;
1015 header->new_count = context_line_count;
1016 context_line_count = 0;
1017 first = 0;
1018 goto next_hunk_line;
1021 remaining.old_offset += header->old_count;
1022 remaining.old_count -= header->old_count;
1023 remaining.new_offset += header->new_count;
1024 remaining.new_count -= header->new_count;
1026 /* initialize next hunk header's offsets */
1027 hunk[1].header.old_offset =
1028 header->old_offset + header->old_count;
1029 hunk[1].header.new_offset =
1030 header->new_offset + header->new_count;
1032 /* add one split hunk */
1033 header->old_count += context_line_count;
1034 header->new_count += context_line_count;
1036 hunk->end = current;
1037 if (colored)
1038 hunk->colored_end = colored_current;
1040 hunk++;
1041 hunk->splittable_into = 1;
1042 hunk->use = hunk[-1].use;
1043 header = &hunk->header;
1045 header->old_count = header->new_count = context_line_count;
1046 context_line_count = 0;
1048 splittable_into--;
1049 marker = ch;
1052 /* last hunk simply gets the rest */
1053 if (header->old_offset != remaining.old_offset)
1054 BUG("miscounted old_offset: %lu != %lu",
1055 header->old_offset, remaining.old_offset);
1056 if (header->new_offset != remaining.new_offset)
1057 BUG("miscounted new_offset: %lu != %lu",
1058 header->new_offset, remaining.new_offset);
1059 header->old_count = remaining.old_count;
1060 header->new_count = remaining.new_count;
1061 hunk->end = end;
1062 if (colored)
1063 hunk->colored_end = colored_end;
1065 return 0;
1068 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1070 const char *plain = s->plain.buf;
1071 size_t current, eol, next;
1073 if (!s->colored.len)
1074 return;
1076 hunk->colored_start = s->colored.len;
1077 for (current = hunk->start; current < hunk->end; ) {
1078 for (eol = current; eol < hunk->end; eol++)
1079 if (plain[eol] == '\n')
1080 break;
1081 next = eol + (eol < hunk->end);
1082 if (eol > current && plain[eol - 1] == '\r')
1083 eol--;
1085 strbuf_addstr(&s->colored,
1086 plain[current] == '-' ?
1087 s->s.file_old_color :
1088 plain[current] == '+' ?
1089 s->s.file_new_color :
1090 s->s.context_color);
1091 strbuf_add(&s->colored, plain + current, eol - current);
1092 strbuf_addstr(&s->colored, s->s.reset_color);
1093 if (next > eol)
1094 strbuf_add(&s->colored, plain + eol, next - eol);
1095 current = next;
1097 hunk->colored_end = s->colored.len;
1100 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1102 size_t i;
1104 strbuf_reset(&s->buf);
1105 strbuf_commented_addf(&s->buf, _("Manual hunk edit mode -- see bottom for "
1106 "a quick guide.\n"));
1107 render_hunk(s, hunk, 0, 0, &s->buf);
1108 strbuf_commented_addf(&s->buf,
1109 _("---\n"
1110 "To remove '%c' lines, make them ' ' lines "
1111 "(context).\n"
1112 "To remove '%c' lines, delete them.\n"
1113 "Lines starting with %c will be removed.\n"),
1114 s->mode->is_reverse ? '+' : '-',
1115 s->mode->is_reverse ? '-' : '+',
1116 comment_line_char);
1117 strbuf_commented_addf(&s->buf, "%s", _(s->mode->edit_hunk_hint));
1119 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1120 * messages.
1122 strbuf_commented_addf(&s->buf,
1123 _("If it does not apply cleanly, you will be "
1124 "given an opportunity to\n"
1125 "edit again. If all lines of the hunk are "
1126 "removed, then the edit is\n"
1127 "aborted and the hunk is left unchanged.\n"));
1129 if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1130 return -1;
1132 /* strip out commented lines */
1133 hunk->start = s->plain.len;
1134 for (i = 0; i < s->buf.len; ) {
1135 size_t next = find_next_line(&s->buf, i);
1137 if (s->buf.buf[i] != comment_line_char)
1138 strbuf_add(&s->plain, s->buf.buf + i, next - i);
1139 i = next;
1142 hunk->end = s->plain.len;
1143 if (hunk->end == hunk->start)
1144 /* The user aborted editing by deleting everything */
1145 return 0;
1147 recolor_hunk(s, hunk);
1150 * If the hunk header is intact, parse it, otherwise simply use the
1151 * hunk header prior to editing (which will adjust `hunk->start` to
1152 * skip the hunk header).
1154 if (s->plain.buf[hunk->start] == '@' &&
1155 parse_hunk_header(s, hunk) < 0)
1156 return error(_("could not parse hunk header"));
1158 return 1;
1161 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1162 size_t orig_old_count, size_t orig_new_count)
1164 struct hunk_header *header = &hunk->header;
1165 size_t i;
1167 header->old_count = header->new_count = 0;
1168 for (i = hunk->start; i < hunk->end; ) {
1169 switch (s->plain.buf[i]) {
1170 case '-':
1171 header->old_count++;
1172 break;
1173 case '+':
1174 header->new_count++;
1175 break;
1176 case ' ': case '\r': case '\n':
1177 header->old_count++;
1178 header->new_count++;
1179 break;
1182 i = find_next_line(&s->plain, i);
1185 return orig_old_count - orig_new_count
1186 - header->old_count + header->new_count;
1189 static int run_apply_check(struct add_p_state *s,
1190 struct file_diff *file_diff)
1192 struct child_process cp = CHILD_PROCESS_INIT;
1194 strbuf_reset(&s->buf);
1195 reassemble_patch(s, file_diff, 1, &s->buf);
1197 setup_child_process(s, &cp,
1198 "apply", "--check", NULL);
1199 strvec_pushv(&cp.args, s->mode->apply_check_args);
1200 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1201 return error(_("'git apply --cached' failed"));
1203 return 0;
1206 static int read_single_character(struct add_p_state *s)
1208 if (s->s.use_single_key) {
1209 int res = read_key_without_echo(&s->answer);
1210 printf("%s\n", res == EOF ? "" : s->answer.buf);
1211 return res;
1214 if (git_read_line_interactively(&s->answer) == EOF)
1215 return EOF;
1216 return 0;
1219 static int prompt_yesno(struct add_p_state *s, const char *prompt)
1221 for (;;) {
1222 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1223 fflush(stdout);
1224 if (read_single_character(s) == EOF)
1225 return -1;
1226 switch (tolower(s->answer.buf[0])) {
1227 case 'n': return 0;
1228 case 'y': return 1;
1233 static int edit_hunk_loop(struct add_p_state *s,
1234 struct file_diff *file_diff, struct hunk *hunk)
1236 size_t plain_len = s->plain.len, colored_len = s->colored.len;
1237 struct hunk backup;
1239 backup = *hunk;
1241 for (;;) {
1242 int res = edit_hunk_manually(s, hunk);
1243 if (res == 0) {
1244 /* abandoned */
1245 *hunk = backup;
1246 return -1;
1249 if (res > 0) {
1250 hunk->delta +=
1251 recount_edited_hunk(s, hunk,
1252 backup.header.old_count,
1253 backup.header.new_count);
1254 if (!run_apply_check(s, file_diff))
1255 return 0;
1258 /* Drop edits (they were appended to s->plain) */
1259 strbuf_setlen(&s->plain, plain_len);
1260 strbuf_setlen(&s->colored, colored_len);
1261 *hunk = backup;
1264 * TRANSLATORS: do not translate [y/n]
1265 * The program will only accept that input at this point.
1266 * Consider translating (saying "no" discards!) as
1267 * (saying "n" for "no" discards!) if the translation
1268 * of the word "no" does not start with n.
1270 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1271 "Edit again (saying \"no\" discards!) "
1272 "[y/n]? "));
1273 if (res < 1)
1274 return -1;
1278 static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1279 int is_reverse)
1281 const char *reverse = is_reverse ? "-R" : NULL;
1282 struct child_process check_index = CHILD_PROCESS_INIT;
1283 struct child_process check_worktree = CHILD_PROCESS_INIT;
1284 struct child_process apply_index = CHILD_PROCESS_INIT;
1285 struct child_process apply_worktree = CHILD_PROCESS_INIT;
1286 int applies_index, applies_worktree;
1288 setup_child_process(s, &check_index,
1289 "apply", "--cached", "--check", reverse, NULL);
1290 applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1291 NULL, 0, NULL, 0);
1293 setup_child_process(s, &check_worktree,
1294 "apply", "--check", reverse, NULL);
1295 applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1296 NULL, 0, NULL, 0);
1298 if (applies_worktree && applies_index) {
1299 setup_child_process(s, &apply_index,
1300 "apply", "--cached", reverse, NULL);
1301 pipe_command(&apply_index, diff->buf, diff->len,
1302 NULL, 0, NULL, 0);
1304 setup_child_process(s, &apply_worktree,
1305 "apply", reverse, NULL);
1306 pipe_command(&apply_worktree, diff->buf, diff->len,
1307 NULL, 0, NULL, 0);
1309 return 1;
1312 if (!applies_index) {
1313 err(s, _("The selected hunks do not apply to the index!"));
1314 if (prompt_yesno(s, _("Apply them to the worktree "
1315 "anyway? ")) > 0) {
1316 setup_child_process(s, &apply_worktree,
1317 "apply", reverse, NULL);
1318 return pipe_command(&apply_worktree, diff->buf,
1319 diff->len, NULL, 0, NULL, 0);
1321 err(s, _("Nothing was applied.\n"));
1322 } else
1323 /* As a last resort, show the diff to the user */
1324 fwrite(diff->buf, diff->len, 1, stderr);
1326 return 0;
1329 #define SUMMARY_HEADER_WIDTH 20
1330 #define SUMMARY_LINE_WIDTH 80
1331 static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1332 struct strbuf *out)
1334 struct hunk_header *header = &hunk->header;
1335 struct strbuf *plain = &s->plain;
1336 size_t len = out->len, i;
1338 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1339 header->old_offset, header->old_count,
1340 header->new_offset, header->new_count);
1341 if (out->len - len < SUMMARY_HEADER_WIDTH)
1342 strbuf_addchars(out, ' ',
1343 SUMMARY_HEADER_WIDTH + len - out->len);
1344 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1345 if (plain->buf[i] != ' ')
1346 break;
1347 if (i < hunk->end)
1348 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1349 if (out->len - len > SUMMARY_LINE_WIDTH)
1350 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1351 strbuf_complete_line(out);
1354 #define DISPLAY_HUNKS_LINES 20
1355 static size_t display_hunks(struct add_p_state *s,
1356 struct file_diff *file_diff, size_t start_index)
1358 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1360 if (end_index > file_diff->hunk_nr)
1361 end_index = file_diff->hunk_nr;
1363 while (start_index < end_index) {
1364 struct hunk *hunk = file_diff->hunk + start_index++;
1366 strbuf_reset(&s->buf);
1367 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1368 : hunk->use == SKIP_HUNK ? '-' : ' ',
1369 (int)start_index);
1370 summarize_hunk(s, hunk, &s->buf);
1371 fputs(s->buf.buf, stdout);
1374 return end_index;
1377 static const char help_patch_remainder[] =
1378 N_("j - leave this hunk undecided, see next undecided hunk\n"
1379 "J - leave this hunk undecided, see next hunk\n"
1380 "k - leave this hunk undecided, see previous undecided hunk\n"
1381 "K - leave this hunk undecided, see previous hunk\n"
1382 "g - select a hunk to go to\n"
1383 "/ - search for a hunk matching the given regex\n"
1384 "s - split the current hunk into smaller hunks\n"
1385 "e - manually edit the current hunk\n"
1386 "? - print help\n");
1388 static int patch_update_file(struct add_p_state *s,
1389 struct file_diff *file_diff)
1391 size_t hunk_index = 0;
1392 ssize_t i, undecided_previous, undecided_next;
1393 struct hunk *hunk;
1394 char ch;
1395 struct child_process cp = CHILD_PROCESS_INIT;
1396 int colored = !!s->colored.len, quit = 0;
1397 enum prompt_mode_type prompt_mode_type;
1398 enum {
1399 ALLOW_GOTO_PREVIOUS_HUNK = 1 << 0,
1400 ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK = 1 << 1,
1401 ALLOW_GOTO_NEXT_HUNK = 1 << 2,
1402 ALLOW_GOTO_NEXT_UNDECIDED_HUNK = 1 << 3,
1403 ALLOW_SEARCH_AND_GOTO = 1 << 4,
1404 ALLOW_SPLIT = 1 << 5,
1405 ALLOW_EDIT = 1 << 6
1406 } permitted = 0;
1408 /* Empty added files have no hunks */
1409 if (!file_diff->hunk_nr && !file_diff->added)
1410 return 0;
1412 strbuf_reset(&s->buf);
1413 render_diff_header(s, file_diff, colored, &s->buf);
1414 fputs(s->buf.buf, stdout);
1415 for (;;) {
1416 if (hunk_index >= file_diff->hunk_nr)
1417 hunk_index = 0;
1418 hunk = file_diff->hunk_nr
1419 ? file_diff->hunk + hunk_index
1420 : &file_diff->head;
1421 undecided_previous = -1;
1422 undecided_next = -1;
1424 if (file_diff->hunk_nr) {
1425 for (i = hunk_index - 1; i >= 0; i--)
1426 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1427 undecided_previous = i;
1428 break;
1431 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1432 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1433 undecided_next = i;
1434 break;
1438 /* Everything decided? */
1439 if (undecided_previous < 0 && undecided_next < 0 &&
1440 hunk->use != UNDECIDED_HUNK)
1441 break;
1443 strbuf_reset(&s->buf);
1444 if (file_diff->hunk_nr) {
1445 render_hunk(s, hunk, 0, colored, &s->buf);
1446 fputs(s->buf.buf, stdout);
1448 strbuf_reset(&s->buf);
1449 if (undecided_previous >= 0) {
1450 permitted |= ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK;
1451 strbuf_addstr(&s->buf, ",k");
1453 if (hunk_index) {
1454 permitted |= ALLOW_GOTO_PREVIOUS_HUNK;
1455 strbuf_addstr(&s->buf, ",K");
1457 if (undecided_next >= 0) {
1458 permitted |= ALLOW_GOTO_NEXT_UNDECIDED_HUNK;
1459 strbuf_addstr(&s->buf, ",j");
1461 if (hunk_index + 1 < file_diff->hunk_nr) {
1462 permitted |= ALLOW_GOTO_NEXT_HUNK;
1463 strbuf_addstr(&s->buf, ",J");
1465 if (file_diff->hunk_nr > 1) {
1466 permitted |= ALLOW_SEARCH_AND_GOTO;
1467 strbuf_addstr(&s->buf, ",g,/");
1469 if (hunk->splittable_into > 1) {
1470 permitted |= ALLOW_SPLIT;
1471 strbuf_addstr(&s->buf, ",s");
1473 if (hunk_index + 1 > file_diff->mode_change &&
1474 !file_diff->deleted) {
1475 permitted |= ALLOW_EDIT;
1476 strbuf_addstr(&s->buf, ",e");
1479 if (file_diff->deleted)
1480 prompt_mode_type = PROMPT_DELETION;
1481 else if (file_diff->added)
1482 prompt_mode_type = PROMPT_ADDITION;
1483 else if (file_diff->mode_change && !hunk_index)
1484 prompt_mode_type = PROMPT_MODE_CHANGE;
1485 else
1486 prompt_mode_type = PROMPT_HUNK;
1488 printf("%s(%"PRIuMAX"/%"PRIuMAX") ", s->s.prompt_color,
1489 (uintmax_t)hunk_index + 1,
1490 (uintmax_t)(file_diff->hunk_nr
1491 ? file_diff->hunk_nr
1492 : 1));
1493 printf(_(s->mode->prompt_mode[prompt_mode_type]),
1494 s->buf.buf);
1495 if (*s->s.reset_color)
1496 fputs(s->s.reset_color, stdout);
1497 fflush(stdout);
1498 if (read_single_character(s) == EOF)
1499 break;
1501 if (!s->answer.len)
1502 continue;
1503 ch = tolower(s->answer.buf[0]);
1504 if (ch == 'y') {
1505 hunk->use = USE_HUNK;
1506 soft_increment:
1507 hunk_index = undecided_next < 0 ?
1508 file_diff->hunk_nr : undecided_next;
1509 } else if (ch == 'n') {
1510 hunk->use = SKIP_HUNK;
1511 goto soft_increment;
1512 } else if (ch == 'a') {
1513 if (file_diff->hunk_nr) {
1514 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1515 hunk = file_diff->hunk + hunk_index;
1516 if (hunk->use == UNDECIDED_HUNK)
1517 hunk->use = USE_HUNK;
1519 } else if (hunk->use == UNDECIDED_HUNK) {
1520 hunk->use = USE_HUNK;
1522 } else if (ch == 'd' || ch == 'q') {
1523 if (file_diff->hunk_nr) {
1524 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1525 hunk = file_diff->hunk + hunk_index;
1526 if (hunk->use == UNDECIDED_HUNK)
1527 hunk->use = SKIP_HUNK;
1529 } else if (hunk->use == UNDECIDED_HUNK) {
1530 hunk->use = SKIP_HUNK;
1532 if (ch == 'q') {
1533 quit = 1;
1534 break;
1536 } else if (s->answer.buf[0] == 'K') {
1537 if (permitted & ALLOW_GOTO_PREVIOUS_HUNK)
1538 hunk_index--;
1539 else
1540 err(s, _("No previous hunk"));
1541 } else if (s->answer.buf[0] == 'J') {
1542 if (permitted & ALLOW_GOTO_NEXT_HUNK)
1543 hunk_index++;
1544 else
1545 err(s, _("No next hunk"));
1546 } else if (s->answer.buf[0] == 'k') {
1547 if (permitted & ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK)
1548 hunk_index = undecided_previous;
1549 else
1550 err(s, _("No previous hunk"));
1551 } else if (s->answer.buf[0] == 'j') {
1552 if (permitted & ALLOW_GOTO_NEXT_UNDECIDED_HUNK)
1553 hunk_index = undecided_next;
1554 else
1555 err(s, _("No next hunk"));
1556 } else if (s->answer.buf[0] == 'g') {
1557 char *pend;
1558 unsigned long response;
1560 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1561 err(s, _("No other hunks to goto"));
1562 continue;
1564 strbuf_remove(&s->answer, 0, 1);
1565 strbuf_trim(&s->answer);
1566 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1567 if (i < (int)file_diff->mode_change)
1568 i = file_diff->mode_change;
1569 while (s->answer.len == 0) {
1570 i = display_hunks(s, file_diff, i);
1571 printf("%s", i < file_diff->hunk_nr ?
1572 _("go to which hunk (<ret> to see "
1573 "more)? ") : _("go to which hunk? "));
1574 fflush(stdout);
1575 if (strbuf_getline(&s->answer,
1576 stdin) == EOF)
1577 break;
1578 strbuf_trim_trailing_newline(&s->answer);
1581 strbuf_trim(&s->answer);
1582 response = strtoul(s->answer.buf, &pend, 10);
1583 if (*pend || pend == s->answer.buf)
1584 err(s, _("Invalid number: '%s'"),
1585 s->answer.buf);
1586 else if (0 < response && response <= file_diff->hunk_nr)
1587 hunk_index = response - 1;
1588 else
1589 err(s, Q_("Sorry, only %d hunk available.",
1590 "Sorry, only %d hunks available.",
1591 file_diff->hunk_nr),
1592 (int)file_diff->hunk_nr);
1593 } else if (s->answer.buf[0] == '/') {
1594 regex_t regex;
1595 int ret;
1597 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1598 err(s, _("No other hunks to search"));
1599 continue;
1601 strbuf_remove(&s->answer, 0, 1);
1602 strbuf_trim_trailing_newline(&s->answer);
1603 if (s->answer.len == 0) {
1604 printf("%s", _("search for regex? "));
1605 fflush(stdout);
1606 if (strbuf_getline(&s->answer,
1607 stdin) == EOF)
1608 break;
1609 strbuf_trim_trailing_newline(&s->answer);
1610 if (s->answer.len == 0)
1611 continue;
1613 ret = regcomp(&regex, s->answer.buf,
1614 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1615 if (ret) {
1616 char errbuf[1024];
1618 regerror(ret, &regex, errbuf, sizeof(errbuf));
1619 err(s, _("Malformed search regexp %s: %s"),
1620 s->answer.buf, errbuf);
1621 continue;
1623 i = hunk_index;
1624 for (;;) {
1625 /* render the hunk into a scratch buffer */
1626 render_hunk(s, file_diff->hunk + i, 0, 0,
1627 &s->buf);
1628 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1629 != REG_NOMATCH)
1630 break;
1631 i++;
1632 if (i == file_diff->hunk_nr)
1633 i = 0;
1634 if (i != hunk_index)
1635 continue;
1636 err(s, _("No hunk matches the given pattern"));
1637 break;
1639 hunk_index = i;
1640 } else if (s->answer.buf[0] == 's') {
1641 size_t splittable_into = hunk->splittable_into;
1642 if (!(permitted & ALLOW_SPLIT))
1643 err(s, _("Sorry, cannot split this hunk"));
1644 else if (!split_hunk(s, file_diff,
1645 hunk - file_diff->hunk))
1646 color_fprintf_ln(stdout, s->s.header_color,
1647 _("Split into %d hunks."),
1648 (int)splittable_into);
1649 } else if (s->answer.buf[0] == 'e') {
1650 if (!(permitted & ALLOW_EDIT))
1651 err(s, _("Sorry, cannot edit this hunk"));
1652 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1653 hunk->use = USE_HUNK;
1654 goto soft_increment;
1656 } else {
1657 const char *p = _(help_patch_remainder), *eol = p;
1659 color_fprintf(stdout, s->s.help_color, "%s",
1660 _(s->mode->help_patch_text));
1663 * Show only those lines of the remainder that are
1664 * actually applicable with the current hunk.
1666 for (; *p; p = eol + (*eol == '\n')) {
1667 eol = strchrnul(p, '\n');
1670 * `s->buf` still contains the part of the
1671 * commands shown in the prompt that are not
1672 * always available.
1674 if (*p != '?' && !strchr(s->buf.buf, *p))
1675 continue;
1677 color_fprintf_ln(stdout, s->s.help_color,
1678 "%.*s", (int)(eol - p), p);
1683 /* Any hunk to be used? */
1684 for (i = 0; i < file_diff->hunk_nr; i++)
1685 if (file_diff->hunk[i].use == USE_HUNK)
1686 break;
1688 if (i < file_diff->hunk_nr ||
1689 (!file_diff->hunk_nr && file_diff->head.use == USE_HUNK)) {
1690 /* At least one hunk selected: apply */
1691 strbuf_reset(&s->buf);
1692 reassemble_patch(s, file_diff, 0, &s->buf);
1694 discard_index(s->s.r->index);
1695 if (s->mode->apply_for_checkout)
1696 apply_for_checkout(s, &s->buf,
1697 s->mode->is_reverse);
1698 else {
1699 setup_child_process(s, &cp, "apply", NULL);
1700 strvec_pushv(&cp.args, s->mode->apply_args);
1701 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1702 NULL, 0, NULL, 0))
1703 error(_("'git apply' failed"));
1705 if (repo_read_index(s->s.r) >= 0)
1706 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
1707 1, NULL, NULL, NULL);
1710 putchar('\n');
1711 return quit;
1714 int run_add_p(struct repository *r, enum add_p_mode mode,
1715 const char *revision, const struct pathspec *ps)
1717 struct add_p_state s = {
1718 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1720 size_t i, binary_count = 0;
1722 init_add_i_state(&s.s, r);
1724 if (mode == ADD_P_STASH)
1725 s.mode = &patch_mode_stash;
1726 else if (mode == ADD_P_RESET) {
1728 * NEEDSWORK: Instead of comparing to the literal "HEAD",
1729 * compare the commit objects instead so that other ways of
1730 * saying the same thing (such as "@") are also handled
1731 * appropriately.
1733 * This applies to the cases below too.
1735 if (!revision || !strcmp(revision, "HEAD"))
1736 s.mode = &patch_mode_reset_head;
1737 else
1738 s.mode = &patch_mode_reset_nothead;
1739 } else if (mode == ADD_P_CHECKOUT) {
1740 if (!revision)
1741 s.mode = &patch_mode_checkout_index;
1742 else if (!strcmp(revision, "HEAD"))
1743 s.mode = &patch_mode_checkout_head;
1744 else
1745 s.mode = &patch_mode_checkout_nothead;
1746 } else if (mode == ADD_P_WORKTREE) {
1747 if (!revision)
1748 s.mode = &patch_mode_checkout_index;
1749 else if (!strcmp(revision, "HEAD"))
1750 s.mode = &patch_mode_worktree_head;
1751 else
1752 s.mode = &patch_mode_worktree_nothead;
1753 } else
1754 s.mode = &patch_mode_add;
1755 s.revision = revision;
1757 discard_index(r->index);
1758 if (repo_read_index(r) < 0 ||
1759 (!s.mode->index_only &&
1760 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1761 NULL, NULL, NULL) < 0) ||
1762 parse_diff(&s, ps) < 0) {
1763 add_p_state_clear(&s);
1764 return -1;
1767 for (i = 0; i < s.file_diff_nr; i++)
1768 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1769 binary_count++;
1770 else if (patch_update_file(&s, s.file_diff + i))
1771 break;
1773 if (s.file_diff_nr == 0)
1774 fprintf(stderr, _("No changes.\n"));
1775 else if (binary_count == s.file_diff_nr)
1776 fprintf(stderr, _("Only binary files changed.\n"));
1778 add_p_state_clear(&s);
1779 return 0;