delta-islands: fix segfault when freeing island marks
[git.git] / add-patch.c
bloba86a92e16461384cbe8ac880fa6515e0f74e243c
1 #include "cache.h"
2 #include "add-interactive.h"
3 #include "strbuf.h"
4 #include "run-command.h"
5 #include "strvec.h"
6 #include "pathspec.h"
7 #include "color.h"
8 #include "diff.h"
9 #include "compat/terminal.h"
10 #include "prompt.h"
12 enum prompt_mode_type {
13 PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_ADDITION, PROMPT_HUNK,
14 PROMPT_MODE_MAX, /* must be last */
17 struct patch_mode {
19 * The magic constant 4 is chosen such that all patch modes
20 * provide enough space for three command-line arguments followed by a
21 * trailing `NULL`.
23 const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
24 unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
25 const char *prompt_mode[PROMPT_MODE_MAX];
26 const char *edit_hunk_hint, *help_patch_text;
29 static struct patch_mode patch_mode_add = {
30 .diff_cmd = { "diff-files", NULL },
31 .apply_args = { "--cached", NULL },
32 .apply_check_args = { "--cached", NULL },
33 .prompt_mode = {
34 N_("Stage mode change [y,n,q,a,d%s,?]? "),
35 N_("Stage deletion [y,n,q,a,d%s,?]? "),
36 N_("Stage addition [y,n,q,a,d%s,?]? "),
37 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
39 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
40 "will immediately be marked for staging."),
41 .help_patch_text =
42 N_("y - stage this hunk\n"
43 "n - do not stage this hunk\n"
44 "q - quit; do not stage this hunk or any of the remaining "
45 "ones\n"
46 "a - stage this hunk and all later hunks in the file\n"
47 "d - do not stage this hunk or any of the later hunks in "
48 "the file\n")
51 static struct patch_mode patch_mode_stash = {
52 .diff_cmd = { "diff-index", "HEAD", NULL },
53 .apply_args = { "--cached", NULL },
54 .apply_check_args = { "--cached", NULL },
55 .prompt_mode = {
56 N_("Stash mode change [y,n,q,a,d%s,?]? "),
57 N_("Stash deletion [y,n,q,a,d%s,?]? "),
58 N_("Stash addition [y,n,q,a,d%s,?]? "),
59 N_("Stash this hunk [y,n,q,a,d%s,?]? "),
61 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
62 "will immediately be marked for stashing."),
63 .help_patch_text =
64 N_("y - stash this hunk\n"
65 "n - do not stash this hunk\n"
66 "q - quit; do not stash this hunk or any of the remaining "
67 "ones\n"
68 "a - stash this hunk and all later hunks in the file\n"
69 "d - do not stash this hunk or any of the later hunks in "
70 "the file\n"),
73 static struct patch_mode patch_mode_reset_head = {
74 .diff_cmd = { "diff-index", "--cached", NULL },
75 .apply_args = { "-R", "--cached", NULL },
76 .apply_check_args = { "-R", "--cached", NULL },
77 .is_reverse = 1,
78 .index_only = 1,
79 .prompt_mode = {
80 N_("Unstage mode change [y,n,q,a,d%s,?]? "),
81 N_("Unstage deletion [y,n,q,a,d%s,?]? "),
82 N_("Unstage addition [y,n,q,a,d%s,?]? "),
83 N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
85 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
86 "will immediately be marked for unstaging."),
87 .help_patch_text =
88 N_("y - unstage this hunk\n"
89 "n - do not unstage this hunk\n"
90 "q - quit; do not unstage this hunk or any of the remaining "
91 "ones\n"
92 "a - unstage this hunk and all later hunks in the file\n"
93 "d - do not unstage this hunk or any of the later hunks in "
94 "the file\n"),
97 static struct patch_mode patch_mode_reset_nothead = {
98 .diff_cmd = { "diff-index", "-R", "--cached", NULL },
99 .apply_args = { "--cached", NULL },
100 .apply_check_args = { "--cached", NULL },
101 .index_only = 1,
102 .prompt_mode = {
103 N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
104 N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
105 N_("Apply addition to index [y,n,q,a,d%s,?]? "),
106 N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
108 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
109 "will immediately be marked for applying."),
110 .help_patch_text =
111 N_("y - apply this hunk to index\n"
112 "n - do not apply this hunk to index\n"
113 "q - quit; do not apply this hunk or any of the remaining "
114 "ones\n"
115 "a - apply this hunk and all later hunks in the file\n"
116 "d - do not apply this hunk or any of the later hunks in "
117 "the file\n"),
120 static struct patch_mode patch_mode_checkout_index = {
121 .diff_cmd = { "diff-files", NULL },
122 .apply_args = { "-R", NULL },
123 .apply_check_args = { "-R", NULL },
124 .is_reverse = 1,
125 .prompt_mode = {
126 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
127 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
128 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
129 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
131 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
132 "will immediately be marked for discarding."),
133 .help_patch_text =
134 N_("y - discard this hunk from worktree\n"
135 "n - do not discard this hunk from worktree\n"
136 "q - quit; do not discard this hunk or any of the remaining "
137 "ones\n"
138 "a - discard this hunk and all later hunks in the file\n"
139 "d - do not discard this hunk or any of the later hunks in "
140 "the file\n"),
143 static struct patch_mode patch_mode_checkout_head = {
144 .diff_cmd = { "diff-index", NULL },
145 .apply_for_checkout = 1,
146 .apply_check_args = { "-R", NULL },
147 .is_reverse = 1,
148 .prompt_mode = {
149 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
150 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
151 N_("Discard addition from index and worktree [y,n,q,a,d%s,?]? "),
152 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
154 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
155 "will immediately be marked for discarding."),
156 .help_patch_text =
157 N_("y - discard this hunk from index and worktree\n"
158 "n - do not discard this hunk from index and worktree\n"
159 "q - quit; do not discard this hunk or any of the remaining "
160 "ones\n"
161 "a - discard this hunk and all later hunks in the file\n"
162 "d - do not discard this hunk or any of the later hunks in "
163 "the file\n"),
166 static struct patch_mode patch_mode_checkout_nothead = {
167 .diff_cmd = { "diff-index", "-R", NULL },
168 .apply_for_checkout = 1,
169 .apply_check_args = { NULL },
170 .prompt_mode = {
171 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
172 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
173 N_("Apply addition to index and worktree [y,n,q,a,d%s,?]? "),
174 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
176 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
177 "will immediately be marked for applying."),
178 .help_patch_text =
179 N_("y - apply this hunk to index and worktree\n"
180 "n - do not apply this hunk to index and worktree\n"
181 "q - quit; do not apply this hunk or any of the remaining "
182 "ones\n"
183 "a - apply this hunk and all later hunks in the file\n"
184 "d - do not apply this hunk or any of the later hunks in "
185 "the file\n"),
188 static struct patch_mode patch_mode_worktree_head = {
189 .diff_cmd = { "diff-index", NULL },
190 .apply_args = { "-R", NULL },
191 .apply_check_args = { "-R", NULL },
192 .is_reverse = 1,
193 .prompt_mode = {
194 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
195 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
196 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
197 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
199 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
200 "will immediately be marked for discarding."),
201 .help_patch_text =
202 N_("y - discard this hunk from worktree\n"
203 "n - do not discard this hunk from worktree\n"
204 "q - quit; do not discard this hunk or any of the remaining "
205 "ones\n"
206 "a - discard this hunk and all later hunks in the file\n"
207 "d - do not discard this hunk or any of the later hunks in "
208 "the file\n"),
211 static struct patch_mode patch_mode_worktree_nothead = {
212 .diff_cmd = { "diff-index", "-R", NULL },
213 .apply_args = { NULL },
214 .apply_check_args = { NULL },
215 .prompt_mode = {
216 N_("Apply mode change to worktree [y,n,q,a,d%s,?]? "),
217 N_("Apply deletion to worktree [y,n,q,a,d%s,?]? "),
218 N_("Apply addition to worktree [y,n,q,a,d%s,?]? "),
219 N_("Apply this hunk to worktree [y,n,q,a,d%s,?]? "),
221 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
222 "will immediately be marked for applying."),
223 .help_patch_text =
224 N_("y - apply this hunk to worktree\n"
225 "n - do not apply this hunk to worktree\n"
226 "q - quit; do not apply this hunk or any of the remaining "
227 "ones\n"
228 "a - apply this hunk and all later hunks in the file\n"
229 "d - do not apply this hunk or any of the later hunks in "
230 "the file\n"),
233 struct hunk_header {
234 unsigned long old_offset, old_count, new_offset, new_count;
236 * Start/end offsets to the extra text after the second `@@` in the
237 * hunk header, e.g. the function signature. This is expected to
238 * include the newline.
240 size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
241 unsigned suppress_colored_line_range:1;
244 struct hunk {
245 size_t start, end, colored_start, colored_end, splittable_into;
246 ssize_t delta;
247 enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
248 struct hunk_header header;
251 struct add_p_state {
252 struct add_i_state s;
253 struct strbuf answer, buf;
255 /* parsed diff */
256 struct strbuf plain, colored;
257 struct file_diff {
258 struct hunk head;
259 struct hunk *hunk;
260 size_t hunk_nr, hunk_alloc;
261 unsigned deleted:1, added:1, mode_change:1,binary:1;
262 } *file_diff;
263 size_t file_diff_nr;
265 /* patch mode */
266 struct patch_mode *mode;
267 const char *revision;
270 static void add_p_state_clear(struct add_p_state *s)
272 size_t i;
274 strbuf_release(&s->answer);
275 strbuf_release(&s->buf);
276 strbuf_release(&s->plain);
277 strbuf_release(&s->colored);
278 for (i = 0; i < s->file_diff_nr; i++)
279 free(s->file_diff[i].hunk);
280 free(s->file_diff);
281 clear_add_i_state(&s->s);
284 __attribute__((format (printf, 2, 3)))
285 static void err(struct add_p_state *s, const char *fmt, ...)
287 va_list args;
289 va_start(args, fmt);
290 fputs(s->s.error_color, stderr);
291 vfprintf(stderr, fmt, args);
292 fputs(s->s.reset_color, stderr);
293 fputc('\n', stderr);
294 va_end(args);
297 static void setup_child_process(struct add_p_state *s,
298 struct child_process *cp, ...)
300 va_list ap;
301 const char *arg;
303 va_start(ap, cp);
304 while ((arg = va_arg(ap, const char *)))
305 strvec_push(&cp->args, arg);
306 va_end(ap);
308 cp->git_cmd = 1;
309 strvec_pushf(&cp->env,
310 INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
313 static int parse_range(const char **p,
314 unsigned long *offset, unsigned long *count)
316 char *pend;
318 *offset = strtoul(*p, &pend, 10);
319 if (pend == *p)
320 return -1;
321 if (*pend != ',') {
322 *count = 1;
323 *p = pend;
324 return 0;
326 *count = strtoul(pend + 1, (char **)p, 10);
327 return *p == pend + 1 ? -1 : 0;
330 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
332 struct hunk_header *header = &hunk->header;
333 const char *line = s->plain.buf + hunk->start, *p = line;
334 char *eol = memchr(p, '\n', s->plain.len - hunk->start);
336 if (!eol)
337 eol = s->plain.buf + s->plain.len;
339 if (!skip_prefix(p, "@@ -", &p) ||
340 parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
341 !skip_prefix(p, " +", &p) ||
342 parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
343 !skip_prefix(p, " @@", &p))
344 return error(_("could not parse hunk header '%.*s'"),
345 (int)(eol - line), line);
347 hunk->start = eol - s->plain.buf + (*eol == '\n');
348 header->extra_start = p - s->plain.buf;
349 header->extra_end = hunk->start;
351 if (!s->colored.len) {
352 header->colored_extra_start = header->colored_extra_end = 0;
353 return 0;
356 /* Now find the extra text in the colored diff */
357 line = s->colored.buf + hunk->colored_start;
358 eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
359 if (!eol)
360 eol = s->colored.buf + s->colored.len;
361 p = memmem(line, eol - line, "@@ -", 4);
362 if (p && (p = memmem(p + 4, eol - p - 4, " @@", 3))) {
363 header->colored_extra_start = p + 3 - s->colored.buf;
364 } else {
365 /* could not parse colored hunk header, leave as-is */
366 header->colored_extra_start = hunk->colored_start;
367 header->suppress_colored_line_range = 1;
369 hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
370 header->colored_extra_end = hunk->colored_start;
372 return 0;
375 static int is_octal(const char *p, size_t len)
377 if (!len)
378 return 0;
380 while (len--)
381 if (*p < '0' || *(p++) > '7')
382 return 0;
383 return 1;
386 static void complete_file(char marker, struct hunk *hunk)
388 if (marker == '-' || marker == '+')
390 * Last hunk ended in non-context line (i.e. it
391 * appended lines to the file, so there are no
392 * trailing context lines).
394 hunk->splittable_into++;
397 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
399 struct strvec args = STRVEC_INIT;
400 const char *diff_algorithm = s->s.interactive_diff_algorithm;
401 struct strbuf *plain = &s->plain, *colored = NULL;
402 struct child_process cp = CHILD_PROCESS_INIT;
403 char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
404 size_t file_diff_alloc = 0, i, color_arg_index;
405 struct file_diff *file_diff = NULL;
406 struct hunk *hunk = NULL;
407 int res;
409 strvec_pushv(&args, s->mode->diff_cmd);
410 if (diff_algorithm)
411 strvec_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
412 if (s->revision) {
413 struct object_id oid;
414 strvec_push(&args,
415 /* could be on an unborn branch */
416 !strcmp("HEAD", s->revision) &&
417 get_oid("HEAD", &oid) ?
418 empty_tree_oid_hex() : s->revision);
420 color_arg_index = args.nr;
421 /* Use `--no-color` explicitly, just in case `diff.color = always`. */
422 strvec_pushl(&args, "--no-color", "--ignore-submodules=dirty", "-p",
423 "--", NULL);
424 for (i = 0; i < ps->nr; i++)
425 strvec_push(&args, ps->items[i].original);
427 setup_child_process(s, &cp, NULL);
428 strvec_pushv(&cp.args, args.v);
429 res = capture_command(&cp, plain, 0);
430 if (res) {
431 strvec_clear(&args);
432 return error(_("could not parse diff"));
434 if (!plain->len) {
435 strvec_clear(&args);
436 return 0;
438 strbuf_complete_line(plain);
440 if (want_color_fd(1, -1)) {
441 struct child_process colored_cp = CHILD_PROCESS_INIT;
442 const char *diff_filter = s->s.interactive_diff_filter;
444 setup_child_process(s, &colored_cp, NULL);
445 xsnprintf((char *)args.v[color_arg_index], 8, "--color");
446 strvec_pushv(&colored_cp.args, args.v);
447 colored = &s->colored;
448 res = capture_command(&colored_cp, colored, 0);
449 strvec_clear(&args);
450 if (res)
451 return error(_("could not parse colored diff"));
453 if (diff_filter) {
454 struct child_process filter_cp = CHILD_PROCESS_INIT;
456 setup_child_process(s, &filter_cp,
457 diff_filter, NULL);
458 filter_cp.git_cmd = 0;
459 filter_cp.use_shell = 1;
460 strbuf_reset(&s->buf);
461 if (pipe_command(&filter_cp,
462 colored->buf, colored->len,
463 &s->buf, colored->len,
464 NULL, 0) < 0)
465 return error(_("failed to run '%s'"),
466 diff_filter);
467 strbuf_swap(colored, &s->buf);
470 strbuf_complete_line(colored);
471 colored_p = colored->buf;
472 colored_pend = colored_p + colored->len;
474 strvec_clear(&args);
476 /* parse files and hunks */
477 p = plain->buf;
478 pend = p + plain->len;
479 while (p != pend) {
480 char *eol = memchr(p, '\n', pend - p);
481 const char *deleted = NULL, *mode_change = NULL;
483 if (!eol)
484 eol = pend;
486 if (starts_with(p, "diff ")) {
487 complete_file(marker, hunk);
488 ALLOC_GROW_BY(s->file_diff, s->file_diff_nr, 1,
489 file_diff_alloc);
490 file_diff = s->file_diff + s->file_diff_nr - 1;
491 hunk = &file_diff->head;
492 hunk->start = p - plain->buf;
493 if (colored_p)
494 hunk->colored_start = colored_p - colored->buf;
495 marker = '\0';
496 } else if (p == plain->buf)
497 BUG("diff starts with unexpected line:\n"
498 "%.*s\n", (int)(eol - p), p);
499 else if (file_diff->deleted)
500 ; /* keep the rest of the file in a single "hunk" */
501 else if (starts_with(p, "@@ ") ||
502 (hunk == &file_diff->head &&
503 (skip_prefix(p, "deleted file", &deleted)))) {
504 if (marker == '-' || marker == '+')
506 * Should not happen; previous hunk did not end
507 * in a context line? Handle it anyway.
509 hunk->splittable_into++;
511 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
512 file_diff->hunk_alloc);
513 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
515 hunk->start = p - plain->buf;
516 if (colored)
517 hunk->colored_start = colored_p - colored->buf;
519 if (deleted)
520 file_diff->deleted = 1;
521 else if (parse_hunk_header(s, hunk) < 0)
522 return -1;
525 * Start counting into how many hunks this one can be
526 * split
528 marker = *p;
529 } else if (hunk == &file_diff->head &&
530 starts_with(p, "new file")) {
531 file_diff->added = 1;
532 } else if (hunk == &file_diff->head &&
533 skip_prefix(p, "old mode ", &mode_change) &&
534 is_octal(mode_change, eol - mode_change)) {
535 if (file_diff->mode_change)
536 BUG("double mode change?\n\n%.*s",
537 (int)(eol - plain->buf), plain->buf);
538 if (file_diff->hunk_nr)
539 BUG("mode change in the middle?\n\n%.*s",
540 (int)(eol - plain->buf), plain->buf);
543 * Do *not* change `hunk`: the mode change pseudo-hunk
544 * is _part of_ the header "hunk".
546 file_diff->mode_change = 1;
547 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
548 file_diff->hunk_alloc);
549 file_diff->hunk->start = p - plain->buf;
550 if (colored_p)
551 file_diff->hunk->colored_start =
552 colored_p - colored->buf;
553 } else if (hunk == &file_diff->head &&
554 skip_prefix(p, "new mode ", &mode_change) &&
555 is_octal(mode_change, eol - mode_change)) {
558 * Extend the "mode change" pseudo-hunk to include also
559 * the "new mode" line.
561 if (!file_diff->mode_change)
562 BUG("'new mode' without 'old mode'?\n\n%.*s",
563 (int)(eol - plain->buf), plain->buf);
564 if (file_diff->hunk_nr != 1)
565 BUG("mode change in the middle?\n\n%.*s",
566 (int)(eol - plain->buf), plain->buf);
567 if (p - plain->buf != file_diff->hunk->end)
568 BUG("'new mode' does not immediately follow "
569 "'old mode'?\n\n%.*s",
570 (int)(eol - plain->buf), plain->buf);
571 } else if (hunk == &file_diff->head &&
572 starts_with(p, "Binary files "))
573 file_diff->binary = 1;
575 if (!!file_diff->deleted + !!file_diff->added +
576 !!file_diff->mode_change > 1)
577 BUG("diff can only contain delete *or* add *or* a "
578 "mode change?!?\n%.*s",
579 (int)(eol - (plain->buf + file_diff->head.start)),
580 plain->buf + file_diff->head.start);
582 if ((marker == '-' || marker == '+') && *p == ' ')
583 hunk->splittable_into++;
584 if (marker && *p != '\\')
585 marker = *p;
587 p = eol == pend ? pend : eol + 1;
588 hunk->end = p - plain->buf;
590 if (colored) {
591 char *colored_eol = memchr(colored_p, '\n',
592 colored_pend - colored_p);
593 if (colored_eol)
594 colored_p = colored_eol + 1;
595 else if (p != pend)
596 /* non-colored has more lines? */
597 goto mismatched_output;
598 else if (colored_p == colored_pend)
599 /* last line has no matching colored one? */
600 goto mismatched_output;
601 else
602 colored_p = colored_pend;
604 hunk->colored_end = colored_p - colored->buf;
607 if (mode_change) {
608 if (file_diff->hunk_nr != 1)
609 BUG("mode change in hunk #%d???",
610 (int)file_diff->hunk_nr);
611 /* Adjust the end of the "mode change" pseudo-hunk */
612 file_diff->hunk->end = hunk->end;
613 if (colored)
614 file_diff->hunk->colored_end = hunk->colored_end;
617 complete_file(marker, hunk);
619 /* non-colored shorter than colored? */
620 if (colored_p != colored_pend) {
621 mismatched_output:
622 error(_("mismatched output from interactive.diffFilter"));
623 advise(_("Your filter must maintain a one-to-one correspondence\n"
624 "between its input and output lines."));
625 return -1;
628 return 0;
631 static size_t find_next_line(struct strbuf *sb, size_t offset)
633 char *eol;
635 if (offset >= sb->len)
636 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
637 (int)offset, (int)sb->len, sb->buf);
639 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
640 if (!eol)
641 return sb->len;
642 return eol - sb->buf + 1;
645 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
646 ssize_t delta, int colored, struct strbuf *out)
648 struct hunk_header *header = &hunk->header;
650 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
652 * Generate the hunk header dynamically, except for special
653 * hunks (such as the diff header).
655 const char *p;
656 size_t len;
657 unsigned long old_offset = header->old_offset;
658 unsigned long new_offset = header->new_offset;
660 if (!colored) {
661 p = s->plain.buf + header->extra_start;
662 len = header->extra_end - header->extra_start;
663 } else if (header->suppress_colored_line_range) {
664 strbuf_add(out,
665 s->colored.buf + header->colored_extra_start,
666 header->colored_extra_end -
667 header->colored_extra_start);
669 strbuf_add(out, s->colored.buf + hunk->colored_start,
670 hunk->colored_end - hunk->colored_start);
671 return;
672 } else {
673 strbuf_addstr(out, s->s.fraginfo_color);
674 p = s->colored.buf + header->colored_extra_start;
675 len = header->colored_extra_end
676 - header->colored_extra_start;
679 if (s->mode->is_reverse)
680 old_offset -= delta;
681 else
682 new_offset += delta;
684 strbuf_addf(out, "@@ -%lu", old_offset);
685 if (header->old_count != 1)
686 strbuf_addf(out, ",%lu", header->old_count);
687 strbuf_addf(out, " +%lu", new_offset);
688 if (header->new_count != 1)
689 strbuf_addf(out, ",%lu", header->new_count);
690 strbuf_addstr(out, " @@");
692 if (len)
693 strbuf_add(out, p, len);
694 else if (colored)
695 strbuf_addf(out, "%s\n", s->s.reset_color);
696 else
697 strbuf_addch(out, '\n');
700 if (colored)
701 strbuf_add(out, s->colored.buf + hunk->colored_start,
702 hunk->colored_end - hunk->colored_start);
703 else
704 strbuf_add(out, s->plain.buf + hunk->start,
705 hunk->end - hunk->start);
708 static void render_diff_header(struct add_p_state *s,
709 struct file_diff *file_diff, int colored,
710 struct strbuf *out)
713 * If there was a mode change, the first hunk is a pseudo hunk that
714 * corresponds to the mode line in the header. If the user did not want
715 * to stage that "hunk", we actually have to cut it out from the header.
717 int skip_mode_change =
718 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
719 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
721 if (!skip_mode_change) {
722 render_hunk(s, head, 0, colored, out);
723 return;
726 if (colored) {
727 const char *p = s->colored.buf;
729 strbuf_add(out, p + head->colored_start,
730 first->colored_start - head->colored_start);
731 strbuf_add(out, p + first->colored_end,
732 head->colored_end - first->colored_end);
733 } else {
734 const char *p = s->plain.buf;
736 strbuf_add(out, p + head->start, first->start - head->start);
737 strbuf_add(out, p + first->end, head->end - first->end);
741 /* Coalesce hunks again that were split */
742 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
743 size_t *hunk_index, int use_all, struct hunk *merged)
745 size_t i = *hunk_index, delta;
746 struct hunk *hunk = file_diff->hunk + i;
747 /* `header` corresponds to the merged hunk */
748 struct hunk_header *header = &merged->header, *next;
750 if (!use_all && hunk->use != USE_HUNK)
751 return 0;
753 *merged = *hunk;
754 /* We simply skip the colored part (if any) when merging hunks */
755 merged->colored_start = merged->colored_end = 0;
757 for (; i + 1 < file_diff->hunk_nr; i++) {
758 hunk++;
759 next = &hunk->header;
762 * Stop merging hunks when:
764 * - the hunk is not selected for use, or
765 * - the hunk does not overlap with the already-merged hunk(s)
767 if ((!use_all && hunk->use != USE_HUNK) ||
768 header->new_offset >= next->new_offset + merged->delta ||
769 header->new_offset + header->new_count
770 < next->new_offset + merged->delta)
771 break;
774 * If the hunks were not edited, and overlap, we can simply
775 * extend the line range.
777 if (merged->start < hunk->start && merged->end > hunk->start) {
778 merged->end = hunk->end;
779 merged->colored_end = hunk->colored_end;
780 delta = 0;
781 } else {
782 const char *plain = s->plain.buf;
783 size_t overlapping_line_count = header->new_offset
784 + header->new_count - merged->delta
785 - next->new_offset;
786 size_t overlap_end = hunk->start;
787 size_t overlap_start = overlap_end;
788 size_t overlap_next, len, j;
791 * One of the hunks was edited: the modified hunk was
792 * appended to the strbuf `s->plain`.
794 * Let's ensure that at least the last context line of
795 * the first hunk overlaps with the corresponding line
796 * of the second hunk, and then merge.
798 for (j = 0; j < overlapping_line_count; j++) {
799 overlap_next = find_next_line(&s->plain,
800 overlap_end);
802 if (overlap_next > hunk->end)
803 BUG("failed to find %d context lines "
804 "in:\n%.*s",
805 (int)overlapping_line_count,
806 (int)(hunk->end - hunk->start),
807 plain + hunk->start);
809 if (plain[overlap_end] != ' ')
810 return error(_("expected context line "
811 "#%d in\n%.*s"),
812 (int)(j + 1),
813 (int)(hunk->end
814 - hunk->start),
815 plain + hunk->start);
817 overlap_start = overlap_end;
818 overlap_end = overlap_next;
820 len = overlap_end - overlap_start;
822 if (len > merged->end - merged->start ||
823 memcmp(plain + merged->end - len,
824 plain + overlap_start, len))
825 return error(_("hunks do not overlap:\n%.*s\n"
826 "\tdoes not end with:\n%.*s"),
827 (int)(merged->end - merged->start),
828 plain + merged->start,
829 (int)len, plain + overlap_start);
832 * Since the start-end ranges are not adjacent, we
833 * cannot simply take the union of the ranges. To
834 * address that, we temporarily append the union of the
835 * lines to the `plain` strbuf.
837 if (merged->end != s->plain.len) {
838 size_t start = s->plain.len;
840 strbuf_add(&s->plain, plain + merged->start,
841 merged->end - merged->start);
842 plain = s->plain.buf;
843 merged->start = start;
844 merged->end = s->plain.len;
847 strbuf_add(&s->plain,
848 plain + overlap_end,
849 hunk->end - overlap_end);
850 merged->end = s->plain.len;
851 merged->splittable_into += hunk->splittable_into;
852 delta = merged->delta;
853 merged->delta += hunk->delta;
856 header->old_count = next->old_offset + next->old_count
857 - header->old_offset;
858 header->new_count = next->new_offset + delta
859 + next->new_count - header->new_offset;
862 if (i == *hunk_index)
863 return 0;
865 *hunk_index = i;
866 return 1;
869 static void reassemble_patch(struct add_p_state *s,
870 struct file_diff *file_diff, int use_all,
871 struct strbuf *out)
873 struct hunk *hunk;
874 size_t save_len = s->plain.len, i;
875 ssize_t delta = 0;
877 render_diff_header(s, file_diff, 0, out);
879 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
880 struct hunk merged = { 0 };
882 hunk = file_diff->hunk + i;
883 if (!use_all && hunk->use != USE_HUNK)
884 delta += hunk->header.old_count
885 - hunk->header.new_count;
886 else {
887 /* merge overlapping hunks into a temporary hunk */
888 if (merge_hunks(s, file_diff, &i, use_all, &merged))
889 hunk = &merged;
891 render_hunk(s, hunk, delta, 0, out);
894 * In case `merge_hunks()` used `plain` as a scratch
895 * pad (this happens when an edited hunk had to be
896 * coalesced with another hunk).
898 strbuf_setlen(&s->plain, save_len);
900 delta += hunk->delta;
905 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
906 size_t hunk_index)
908 int colored = !!s->colored.len, first = 1;
909 struct hunk *hunk = file_diff->hunk + hunk_index;
910 size_t splittable_into;
911 size_t end, colored_end, current, colored_current = 0, context_line_count;
912 struct hunk_header remaining, *header;
913 char marker, ch;
915 if (hunk_index >= file_diff->hunk_nr)
916 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
917 (int)hunk_index, (int)file_diff->hunk_nr);
919 if (hunk->splittable_into < 2)
920 return 0;
921 splittable_into = hunk->splittable_into;
923 end = hunk->end;
924 colored_end = hunk->colored_end;
926 remaining = hunk->header;
928 file_diff->hunk_nr += splittable_into - 1;
929 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
930 if (hunk_index + splittable_into < file_diff->hunk_nr)
931 memmove(file_diff->hunk + hunk_index + splittable_into,
932 file_diff->hunk + hunk_index + 1,
933 (file_diff->hunk_nr - hunk_index - splittable_into)
934 * sizeof(*hunk));
935 hunk = file_diff->hunk + hunk_index;
936 hunk->splittable_into = 1;
937 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
939 header = &hunk->header;
940 header->old_count = header->new_count = 0;
942 current = hunk->start;
943 if (colored)
944 colored_current = hunk->colored_start;
945 marker = '\0';
946 context_line_count = 0;
948 while (splittable_into > 1) {
949 ch = s->plain.buf[current];
951 if (!ch)
952 BUG("buffer overrun while splitting hunks");
955 * Is this the first context line after a chain of +/- lines?
956 * Then record the start of the next split hunk.
958 if ((marker == '-' || marker == '+') && ch == ' ') {
959 first = 0;
960 hunk[1].start = current;
961 if (colored)
962 hunk[1].colored_start = colored_current;
963 context_line_count = 0;
967 * Was the previous line a +/- one? Alternatively, is this the
968 * first line (and not a +/- one)?
970 * Then just increment the appropriate counter and continue
971 * with the next line.
973 if (marker != ' ' || (ch != '-' && ch != '+')) {
974 next_hunk_line:
975 /* Comment lines are attached to the previous line */
976 if (ch == '\\')
977 ch = marker ? marker : ' ';
979 /* current hunk not done yet */
980 if (ch == ' ')
981 context_line_count++;
982 else if (ch == '-')
983 header->old_count++;
984 else if (ch == '+')
985 header->new_count++;
986 else
987 BUG("unhandled diff marker: '%c'", ch);
988 marker = ch;
989 current = find_next_line(&s->plain, current);
990 if (colored)
991 colored_current =
992 find_next_line(&s->colored,
993 colored_current);
994 continue;
998 * We got us the start of a new hunk!
1000 * This is a context line, so it is shared with the previous
1001 * hunk, if any.
1004 if (first) {
1005 if (header->old_count || header->new_count)
1006 BUG("counts are off: %d/%d",
1007 (int)header->old_count,
1008 (int)header->new_count);
1010 header->old_count = context_line_count;
1011 header->new_count = context_line_count;
1012 context_line_count = 0;
1013 first = 0;
1014 goto next_hunk_line;
1017 remaining.old_offset += header->old_count;
1018 remaining.old_count -= header->old_count;
1019 remaining.new_offset += header->new_count;
1020 remaining.new_count -= header->new_count;
1022 /* initialize next hunk header's offsets */
1023 hunk[1].header.old_offset =
1024 header->old_offset + header->old_count;
1025 hunk[1].header.new_offset =
1026 header->new_offset + header->new_count;
1028 /* add one split hunk */
1029 header->old_count += context_line_count;
1030 header->new_count += context_line_count;
1032 hunk->end = current;
1033 if (colored)
1034 hunk->colored_end = colored_current;
1036 hunk++;
1037 hunk->splittable_into = 1;
1038 hunk->use = hunk[-1].use;
1039 header = &hunk->header;
1041 header->old_count = header->new_count = context_line_count;
1042 context_line_count = 0;
1044 splittable_into--;
1045 marker = ch;
1048 /* last hunk simply gets the rest */
1049 if (header->old_offset != remaining.old_offset)
1050 BUG("miscounted old_offset: %lu != %lu",
1051 header->old_offset, remaining.old_offset);
1052 if (header->new_offset != remaining.new_offset)
1053 BUG("miscounted new_offset: %lu != %lu",
1054 header->new_offset, remaining.new_offset);
1055 header->old_count = remaining.old_count;
1056 header->new_count = remaining.new_count;
1057 hunk->end = end;
1058 if (colored)
1059 hunk->colored_end = colored_end;
1061 return 0;
1064 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1066 const char *plain = s->plain.buf;
1067 size_t current, eol, next;
1069 if (!s->colored.len)
1070 return;
1072 hunk->colored_start = s->colored.len;
1073 for (current = hunk->start; current < hunk->end; ) {
1074 for (eol = current; eol < hunk->end; eol++)
1075 if (plain[eol] == '\n')
1076 break;
1077 next = eol + (eol < hunk->end);
1078 if (eol > current && plain[eol - 1] == '\r')
1079 eol--;
1081 strbuf_addstr(&s->colored,
1082 plain[current] == '-' ?
1083 s->s.file_old_color :
1084 plain[current] == '+' ?
1085 s->s.file_new_color :
1086 s->s.context_color);
1087 strbuf_add(&s->colored, plain + current, eol - current);
1088 strbuf_addstr(&s->colored, s->s.reset_color);
1089 if (next > eol)
1090 strbuf_add(&s->colored, plain + eol, next - eol);
1091 current = next;
1093 hunk->colored_end = s->colored.len;
1096 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1098 size_t i;
1100 strbuf_reset(&s->buf);
1101 strbuf_commented_addf(&s->buf, _("Manual hunk edit mode -- see bottom for "
1102 "a quick guide.\n"));
1103 render_hunk(s, hunk, 0, 0, &s->buf);
1104 strbuf_commented_addf(&s->buf,
1105 _("---\n"
1106 "To remove '%c' lines, make them ' ' lines "
1107 "(context).\n"
1108 "To remove '%c' lines, delete them.\n"
1109 "Lines starting with %c will be removed.\n"),
1110 s->mode->is_reverse ? '+' : '-',
1111 s->mode->is_reverse ? '-' : '+',
1112 comment_line_char);
1113 strbuf_commented_addf(&s->buf, "%s", _(s->mode->edit_hunk_hint));
1115 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1116 * messages.
1118 strbuf_commented_addf(&s->buf,
1119 _("If it does not apply cleanly, you will be "
1120 "given an opportunity to\n"
1121 "edit again. If all lines of the hunk are "
1122 "removed, then the edit is\n"
1123 "aborted and the hunk is left unchanged.\n"));
1125 if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1126 return -1;
1128 /* strip out commented lines */
1129 hunk->start = s->plain.len;
1130 for (i = 0; i < s->buf.len; ) {
1131 size_t next = find_next_line(&s->buf, i);
1133 if (s->buf.buf[i] != comment_line_char)
1134 strbuf_add(&s->plain, s->buf.buf + i, next - i);
1135 i = next;
1138 hunk->end = s->plain.len;
1139 if (hunk->end == hunk->start)
1140 /* The user aborted editing by deleting everything */
1141 return 0;
1143 recolor_hunk(s, hunk);
1146 * If the hunk header is intact, parse it, otherwise simply use the
1147 * hunk header prior to editing (which will adjust `hunk->start` to
1148 * skip the hunk header).
1150 if (s->plain.buf[hunk->start] == '@' &&
1151 parse_hunk_header(s, hunk) < 0)
1152 return error(_("could not parse hunk header"));
1154 return 1;
1157 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1158 size_t orig_old_count, size_t orig_new_count)
1160 struct hunk_header *header = &hunk->header;
1161 size_t i;
1163 header->old_count = header->new_count = 0;
1164 for (i = hunk->start; i < hunk->end; ) {
1165 switch (s->plain.buf[i]) {
1166 case '-':
1167 header->old_count++;
1168 break;
1169 case '+':
1170 header->new_count++;
1171 break;
1172 case ' ': case '\r': case '\n':
1173 header->old_count++;
1174 header->new_count++;
1175 break;
1178 i = find_next_line(&s->plain, i);
1181 return orig_old_count - orig_new_count
1182 - header->old_count + header->new_count;
1185 static int run_apply_check(struct add_p_state *s,
1186 struct file_diff *file_diff)
1188 struct child_process cp = CHILD_PROCESS_INIT;
1190 strbuf_reset(&s->buf);
1191 reassemble_patch(s, file_diff, 1, &s->buf);
1193 setup_child_process(s, &cp,
1194 "apply", "--check", NULL);
1195 strvec_pushv(&cp.args, s->mode->apply_check_args);
1196 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1197 return error(_("'git apply --cached' failed"));
1199 return 0;
1202 static int read_single_character(struct add_p_state *s)
1204 if (s->s.use_single_key) {
1205 int res = read_key_without_echo(&s->answer);
1206 printf("%s\n", res == EOF ? "" : s->answer.buf);
1207 return res;
1210 if (git_read_line_interactively(&s->answer) == EOF)
1211 return EOF;
1212 return 0;
1215 static int prompt_yesno(struct add_p_state *s, const char *prompt)
1217 for (;;) {
1218 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1219 fflush(stdout);
1220 if (read_single_character(s) == EOF)
1221 return -1;
1222 switch (tolower(s->answer.buf[0])) {
1223 case 'n': return 0;
1224 case 'y': return 1;
1229 static int edit_hunk_loop(struct add_p_state *s,
1230 struct file_diff *file_diff, struct hunk *hunk)
1232 size_t plain_len = s->plain.len, colored_len = s->colored.len;
1233 struct hunk backup;
1235 backup = *hunk;
1237 for (;;) {
1238 int res = edit_hunk_manually(s, hunk);
1239 if (res == 0) {
1240 /* abandoned */
1241 *hunk = backup;
1242 return -1;
1245 if (res > 0) {
1246 hunk->delta +=
1247 recount_edited_hunk(s, hunk,
1248 backup.header.old_count,
1249 backup.header.new_count);
1250 if (!run_apply_check(s, file_diff))
1251 return 0;
1254 /* Drop edits (they were appended to s->plain) */
1255 strbuf_setlen(&s->plain, plain_len);
1256 strbuf_setlen(&s->colored, colored_len);
1257 *hunk = backup;
1260 * TRANSLATORS: do not translate [y/n]
1261 * The program will only accept that input at this point.
1262 * Consider translating (saying "no" discards!) as
1263 * (saying "n" for "no" discards!) if the translation
1264 * of the word "no" does not start with n.
1266 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1267 "Edit again (saying \"no\" discards!) "
1268 "[y/n]? "));
1269 if (res < 1)
1270 return -1;
1274 static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1275 int is_reverse)
1277 const char *reverse = is_reverse ? "-R" : NULL;
1278 struct child_process check_index = CHILD_PROCESS_INIT;
1279 struct child_process check_worktree = CHILD_PROCESS_INIT;
1280 struct child_process apply_index = CHILD_PROCESS_INIT;
1281 struct child_process apply_worktree = CHILD_PROCESS_INIT;
1282 int applies_index, applies_worktree;
1284 setup_child_process(s, &check_index,
1285 "apply", "--cached", "--check", reverse, NULL);
1286 applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1287 NULL, 0, NULL, 0);
1289 setup_child_process(s, &check_worktree,
1290 "apply", "--check", reverse, NULL);
1291 applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1292 NULL, 0, NULL, 0);
1294 if (applies_worktree && applies_index) {
1295 setup_child_process(s, &apply_index,
1296 "apply", "--cached", reverse, NULL);
1297 pipe_command(&apply_index, diff->buf, diff->len,
1298 NULL, 0, NULL, 0);
1300 setup_child_process(s, &apply_worktree,
1301 "apply", reverse, NULL);
1302 pipe_command(&apply_worktree, diff->buf, diff->len,
1303 NULL, 0, NULL, 0);
1305 return 1;
1308 if (!applies_index) {
1309 err(s, _("The selected hunks do not apply to the index!"));
1310 if (prompt_yesno(s, _("Apply them to the worktree "
1311 "anyway? ")) > 0) {
1312 setup_child_process(s, &apply_worktree,
1313 "apply", reverse, NULL);
1314 return pipe_command(&apply_worktree, diff->buf,
1315 diff->len, NULL, 0, NULL, 0);
1317 err(s, _("Nothing was applied.\n"));
1318 } else
1319 /* As a last resort, show the diff to the user */
1320 fwrite(diff->buf, diff->len, 1, stderr);
1322 return 0;
1325 #define SUMMARY_HEADER_WIDTH 20
1326 #define SUMMARY_LINE_WIDTH 80
1327 static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1328 struct strbuf *out)
1330 struct hunk_header *header = &hunk->header;
1331 struct strbuf *plain = &s->plain;
1332 size_t len = out->len, i;
1334 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1335 header->old_offset, header->old_count,
1336 header->new_offset, header->new_count);
1337 if (out->len - len < SUMMARY_HEADER_WIDTH)
1338 strbuf_addchars(out, ' ',
1339 SUMMARY_HEADER_WIDTH + len - out->len);
1340 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1341 if (plain->buf[i] != ' ')
1342 break;
1343 if (i < hunk->end)
1344 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1345 if (out->len - len > SUMMARY_LINE_WIDTH)
1346 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1347 strbuf_complete_line(out);
1350 #define DISPLAY_HUNKS_LINES 20
1351 static size_t display_hunks(struct add_p_state *s,
1352 struct file_diff *file_diff, size_t start_index)
1354 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1356 if (end_index > file_diff->hunk_nr)
1357 end_index = file_diff->hunk_nr;
1359 while (start_index < end_index) {
1360 struct hunk *hunk = file_diff->hunk + start_index++;
1362 strbuf_reset(&s->buf);
1363 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1364 : hunk->use == SKIP_HUNK ? '-' : ' ',
1365 (int)start_index);
1366 summarize_hunk(s, hunk, &s->buf);
1367 fputs(s->buf.buf, stdout);
1370 return end_index;
1373 static const char help_patch_remainder[] =
1374 N_("j - leave this hunk undecided, see next undecided hunk\n"
1375 "J - leave this hunk undecided, see next hunk\n"
1376 "k - leave this hunk undecided, see previous undecided hunk\n"
1377 "K - leave this hunk undecided, see previous hunk\n"
1378 "g - select a hunk to go to\n"
1379 "/ - search for a hunk matching the given regex\n"
1380 "s - split the current hunk into smaller hunks\n"
1381 "e - manually edit the current hunk\n"
1382 "? - print help\n");
1384 static int patch_update_file(struct add_p_state *s,
1385 struct file_diff *file_diff)
1387 size_t hunk_index = 0;
1388 ssize_t i, undecided_previous, undecided_next;
1389 struct hunk *hunk;
1390 char ch;
1391 struct child_process cp = CHILD_PROCESS_INIT;
1392 int colored = !!s->colored.len, quit = 0;
1393 enum prompt_mode_type prompt_mode_type;
1394 enum {
1395 ALLOW_GOTO_PREVIOUS_HUNK = 1 << 0,
1396 ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK = 1 << 1,
1397 ALLOW_GOTO_NEXT_HUNK = 1 << 2,
1398 ALLOW_GOTO_NEXT_UNDECIDED_HUNK = 1 << 3,
1399 ALLOW_SEARCH_AND_GOTO = 1 << 4,
1400 ALLOW_SPLIT = 1 << 5,
1401 ALLOW_EDIT = 1 << 6
1402 } permitted = 0;
1404 /* Empty added files have no hunks */
1405 if (!file_diff->hunk_nr && !file_diff->added)
1406 return 0;
1408 strbuf_reset(&s->buf);
1409 render_diff_header(s, file_diff, colored, &s->buf);
1410 fputs(s->buf.buf, stdout);
1411 for (;;) {
1412 if (hunk_index >= file_diff->hunk_nr)
1413 hunk_index = 0;
1414 hunk = file_diff->hunk_nr
1415 ? file_diff->hunk + hunk_index
1416 : &file_diff->head;
1417 undecided_previous = -1;
1418 undecided_next = -1;
1420 if (file_diff->hunk_nr) {
1421 for (i = hunk_index - 1; i >= 0; i--)
1422 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1423 undecided_previous = i;
1424 break;
1427 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1428 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1429 undecided_next = i;
1430 break;
1434 /* Everything decided? */
1435 if (undecided_previous < 0 && undecided_next < 0 &&
1436 hunk->use != UNDECIDED_HUNK)
1437 break;
1439 strbuf_reset(&s->buf);
1440 if (file_diff->hunk_nr) {
1441 render_hunk(s, hunk, 0, colored, &s->buf);
1442 fputs(s->buf.buf, stdout);
1444 strbuf_reset(&s->buf);
1445 if (undecided_previous >= 0) {
1446 permitted |= ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK;
1447 strbuf_addstr(&s->buf, ",k");
1449 if (hunk_index) {
1450 permitted |= ALLOW_GOTO_PREVIOUS_HUNK;
1451 strbuf_addstr(&s->buf, ",K");
1453 if (undecided_next >= 0) {
1454 permitted |= ALLOW_GOTO_NEXT_UNDECIDED_HUNK;
1455 strbuf_addstr(&s->buf, ",j");
1457 if (hunk_index + 1 < file_diff->hunk_nr) {
1458 permitted |= ALLOW_GOTO_NEXT_HUNK;
1459 strbuf_addstr(&s->buf, ",J");
1461 if (file_diff->hunk_nr > 1) {
1462 permitted |= ALLOW_SEARCH_AND_GOTO;
1463 strbuf_addstr(&s->buf, ",g,/");
1465 if (hunk->splittable_into > 1) {
1466 permitted |= ALLOW_SPLIT;
1467 strbuf_addstr(&s->buf, ",s");
1469 if (hunk_index + 1 > file_diff->mode_change &&
1470 !file_diff->deleted) {
1471 permitted |= ALLOW_EDIT;
1472 strbuf_addstr(&s->buf, ",e");
1475 if (file_diff->deleted)
1476 prompt_mode_type = PROMPT_DELETION;
1477 else if (file_diff->added)
1478 prompt_mode_type = PROMPT_ADDITION;
1479 else if (file_diff->mode_change && !hunk_index)
1480 prompt_mode_type = PROMPT_MODE_CHANGE;
1481 else
1482 prompt_mode_type = PROMPT_HUNK;
1484 printf("%s(%"PRIuMAX"/%"PRIuMAX") ", s->s.prompt_color,
1485 (uintmax_t)hunk_index + 1,
1486 (uintmax_t)(file_diff->hunk_nr
1487 ? file_diff->hunk_nr
1488 : 1));
1489 printf(_(s->mode->prompt_mode[prompt_mode_type]),
1490 s->buf.buf);
1491 if (*s->s.reset_color)
1492 fputs(s->s.reset_color, stdout);
1493 fflush(stdout);
1494 if (read_single_character(s) == EOF)
1495 break;
1497 if (!s->answer.len)
1498 continue;
1499 ch = tolower(s->answer.buf[0]);
1500 if (ch == 'y') {
1501 hunk->use = USE_HUNK;
1502 soft_increment:
1503 hunk_index = undecided_next < 0 ?
1504 file_diff->hunk_nr : undecided_next;
1505 } else if (ch == 'n') {
1506 hunk->use = SKIP_HUNK;
1507 goto soft_increment;
1508 } else if (ch == 'a') {
1509 if (file_diff->hunk_nr) {
1510 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1511 hunk = file_diff->hunk + hunk_index;
1512 if (hunk->use == UNDECIDED_HUNK)
1513 hunk->use = USE_HUNK;
1515 } else if (hunk->use == UNDECIDED_HUNK) {
1516 hunk->use = USE_HUNK;
1518 } else if (ch == 'd' || ch == 'q') {
1519 if (file_diff->hunk_nr) {
1520 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1521 hunk = file_diff->hunk + hunk_index;
1522 if (hunk->use == UNDECIDED_HUNK)
1523 hunk->use = SKIP_HUNK;
1525 } else if (hunk->use == UNDECIDED_HUNK) {
1526 hunk->use = SKIP_HUNK;
1528 if (ch == 'q') {
1529 quit = 1;
1530 break;
1532 } else if (s->answer.buf[0] == 'K') {
1533 if (permitted & ALLOW_GOTO_PREVIOUS_HUNK)
1534 hunk_index--;
1535 else
1536 err(s, _("No previous hunk"));
1537 } else if (s->answer.buf[0] == 'J') {
1538 if (permitted & ALLOW_GOTO_NEXT_HUNK)
1539 hunk_index++;
1540 else
1541 err(s, _("No next hunk"));
1542 } else if (s->answer.buf[0] == 'k') {
1543 if (permitted & ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK)
1544 hunk_index = undecided_previous;
1545 else
1546 err(s, _("No previous hunk"));
1547 } else if (s->answer.buf[0] == 'j') {
1548 if (permitted & ALLOW_GOTO_NEXT_UNDECIDED_HUNK)
1549 hunk_index = undecided_next;
1550 else
1551 err(s, _("No next hunk"));
1552 } else if (s->answer.buf[0] == 'g') {
1553 char *pend;
1554 unsigned long response;
1556 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1557 err(s, _("No other hunks to goto"));
1558 continue;
1560 strbuf_remove(&s->answer, 0, 1);
1561 strbuf_trim(&s->answer);
1562 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1563 if (i < (int)file_diff->mode_change)
1564 i = file_diff->mode_change;
1565 while (s->answer.len == 0) {
1566 i = display_hunks(s, file_diff, i);
1567 printf("%s", i < file_diff->hunk_nr ?
1568 _("go to which hunk (<ret> to see "
1569 "more)? ") : _("go to which hunk? "));
1570 fflush(stdout);
1571 if (strbuf_getline(&s->answer,
1572 stdin) == EOF)
1573 break;
1574 strbuf_trim_trailing_newline(&s->answer);
1577 strbuf_trim(&s->answer);
1578 response = strtoul(s->answer.buf, &pend, 10);
1579 if (*pend || pend == s->answer.buf)
1580 err(s, _("Invalid number: '%s'"),
1581 s->answer.buf);
1582 else if (0 < response && response <= file_diff->hunk_nr)
1583 hunk_index = response - 1;
1584 else
1585 err(s, Q_("Sorry, only %d hunk available.",
1586 "Sorry, only %d hunks available.",
1587 file_diff->hunk_nr),
1588 (int)file_diff->hunk_nr);
1589 } else if (s->answer.buf[0] == '/') {
1590 regex_t regex;
1591 int ret;
1593 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1594 err(s, _("No other hunks to search"));
1595 continue;
1597 strbuf_remove(&s->answer, 0, 1);
1598 strbuf_trim_trailing_newline(&s->answer);
1599 if (s->answer.len == 0) {
1600 printf("%s", _("search for regex? "));
1601 fflush(stdout);
1602 if (strbuf_getline(&s->answer,
1603 stdin) == EOF)
1604 break;
1605 strbuf_trim_trailing_newline(&s->answer);
1606 if (s->answer.len == 0)
1607 continue;
1609 ret = regcomp(&regex, s->answer.buf,
1610 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1611 if (ret) {
1612 char errbuf[1024];
1614 regerror(ret, &regex, errbuf, sizeof(errbuf));
1615 err(s, _("Malformed search regexp %s: %s"),
1616 s->answer.buf, errbuf);
1617 continue;
1619 i = hunk_index;
1620 for (;;) {
1621 /* render the hunk into a scratch buffer */
1622 render_hunk(s, file_diff->hunk + i, 0, 0,
1623 &s->buf);
1624 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1625 != REG_NOMATCH)
1626 break;
1627 i++;
1628 if (i == file_diff->hunk_nr)
1629 i = 0;
1630 if (i != hunk_index)
1631 continue;
1632 err(s, _("No hunk matches the given pattern"));
1633 break;
1635 hunk_index = i;
1636 } else if (s->answer.buf[0] == 's') {
1637 size_t splittable_into = hunk->splittable_into;
1638 if (!(permitted & ALLOW_SPLIT))
1639 err(s, _("Sorry, cannot split this hunk"));
1640 else if (!split_hunk(s, file_diff,
1641 hunk - file_diff->hunk))
1642 color_fprintf_ln(stdout, s->s.header_color,
1643 _("Split into %d hunks."),
1644 (int)splittable_into);
1645 } else if (s->answer.buf[0] == 'e') {
1646 if (!(permitted & ALLOW_EDIT))
1647 err(s, _("Sorry, cannot edit this hunk"));
1648 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1649 hunk->use = USE_HUNK;
1650 goto soft_increment;
1652 } else {
1653 const char *p = _(help_patch_remainder), *eol = p;
1655 color_fprintf(stdout, s->s.help_color, "%s",
1656 _(s->mode->help_patch_text));
1659 * Show only those lines of the remainder that are
1660 * actually applicable with the current hunk.
1662 for (; *p; p = eol + (*eol == '\n')) {
1663 eol = strchrnul(p, '\n');
1666 * `s->buf` still contains the part of the
1667 * commands shown in the prompt that are not
1668 * always available.
1670 if (*p != '?' && !strchr(s->buf.buf, *p))
1671 continue;
1673 color_fprintf_ln(stdout, s->s.help_color,
1674 "%.*s", (int)(eol - p), p);
1679 /* Any hunk to be used? */
1680 for (i = 0; i < file_diff->hunk_nr; i++)
1681 if (file_diff->hunk[i].use == USE_HUNK)
1682 break;
1684 if (i < file_diff->hunk_nr ||
1685 (!file_diff->hunk_nr && file_diff->head.use == USE_HUNK)) {
1686 /* At least one hunk selected: apply */
1687 strbuf_reset(&s->buf);
1688 reassemble_patch(s, file_diff, 0, &s->buf);
1690 discard_index(s->s.r->index);
1691 if (s->mode->apply_for_checkout)
1692 apply_for_checkout(s, &s->buf,
1693 s->mode->is_reverse);
1694 else {
1695 setup_child_process(s, &cp, "apply", NULL);
1696 strvec_pushv(&cp.args, s->mode->apply_args);
1697 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1698 NULL, 0, NULL, 0))
1699 error(_("'git apply' failed"));
1701 if (repo_read_index(s->s.r) >= 0)
1702 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
1703 1, NULL, NULL, NULL);
1706 putchar('\n');
1707 return quit;
1710 int run_add_p(struct repository *r, enum add_p_mode mode,
1711 const char *revision, const struct pathspec *ps)
1713 struct add_p_state s = {
1714 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1716 size_t i, binary_count = 0;
1718 init_add_i_state(&s.s, r);
1720 if (mode == ADD_P_STASH)
1721 s.mode = &patch_mode_stash;
1722 else if (mode == ADD_P_RESET) {
1724 * NEEDSWORK: Instead of comparing to the literal "HEAD",
1725 * compare the commit objects instead so that other ways of
1726 * saying the same thing (such as "@") are also handled
1727 * appropriately.
1729 * This applies to the cases below too.
1731 if (!revision || !strcmp(revision, "HEAD"))
1732 s.mode = &patch_mode_reset_head;
1733 else
1734 s.mode = &patch_mode_reset_nothead;
1735 } else if (mode == ADD_P_CHECKOUT) {
1736 if (!revision)
1737 s.mode = &patch_mode_checkout_index;
1738 else if (!strcmp(revision, "HEAD"))
1739 s.mode = &patch_mode_checkout_head;
1740 else
1741 s.mode = &patch_mode_checkout_nothead;
1742 } else if (mode == ADD_P_WORKTREE) {
1743 if (!revision)
1744 s.mode = &patch_mode_checkout_index;
1745 else if (!strcmp(revision, "HEAD"))
1746 s.mode = &patch_mode_worktree_head;
1747 else
1748 s.mode = &patch_mode_worktree_nothead;
1749 } else
1750 s.mode = &patch_mode_add;
1751 s.revision = revision;
1753 discard_index(r->index);
1754 if (repo_read_index(r) < 0 ||
1755 (!s.mode->index_only &&
1756 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1757 NULL, NULL, NULL) < 0) ||
1758 parse_diff(&s, ps) < 0) {
1759 add_p_state_clear(&s);
1760 return -1;
1763 for (i = 0; i < s.file_diff_nr; i++)
1764 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1765 binary_count++;
1766 else if (patch_update_file(&s, s.file_diff + i))
1767 break;
1769 if (s.file_diff_nr == 0)
1770 fprintf(stderr, _("No changes.\n"));
1771 else if (binary_count == s.file_diff_nr)
1772 fprintf(stderr, _("Only binary files changed.\n"));
1774 add_p_state_clear(&s);
1775 return 0;