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