The ninth batch
[alt-git.git] / add-patch.c
blobba629add62a9b7e5134ac3ef442646e6457e4c40
1 #include "git-compat-util.h"
2 #include "add-interactive.h"
3 #include "advice.h"
4 #include "alloc.h"
5 #include "editor.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "object-name.h"
9 #include "read-cache-ll.h"
10 #include "repository.h"
11 #include "strbuf.h"
12 #include "run-command.h"
13 #include "strvec.h"
14 #include "pathspec.h"
15 #include "color.h"
16 #include "diff.h"
17 #include "compat/terminal.h"
18 #include "prompt.h"
20 enum prompt_mode_type {
21 PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_ADDITION, PROMPT_HUNK,
22 PROMPT_MODE_MAX, /* must be last */
25 struct patch_mode {
27 * The magic constant 4 is chosen such that all patch modes
28 * provide enough space for three command-line arguments followed by a
29 * trailing `NULL`.
31 const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
32 unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
33 const char *prompt_mode[PROMPT_MODE_MAX];
34 const char *edit_hunk_hint, *help_patch_text;
37 static struct patch_mode patch_mode_add = {
38 .diff_cmd = { "diff-files", NULL },
39 .apply_args = { "--cached", NULL },
40 .apply_check_args = { "--cached", NULL },
41 .prompt_mode = {
42 N_("Stage mode change [y,n,q,a,d%s,?]? "),
43 N_("Stage deletion [y,n,q,a,d%s,?]? "),
44 N_("Stage addition [y,n,q,a,d%s,?]? "),
45 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
47 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
48 "will immediately be marked for staging."),
49 .help_patch_text =
50 N_("y - stage this hunk\n"
51 "n - do not stage this hunk\n"
52 "q - quit; do not stage this hunk or any of the remaining "
53 "ones\n"
54 "a - stage this hunk and all later hunks in the file\n"
55 "d - do not stage this hunk or any of the later hunks in "
56 "the file\n")
59 static struct patch_mode patch_mode_stash = {
60 .diff_cmd = { "diff-index", "HEAD", NULL },
61 .apply_args = { "--cached", NULL },
62 .apply_check_args = { "--cached", NULL },
63 .prompt_mode = {
64 N_("Stash mode change [y,n,q,a,d%s,?]? "),
65 N_("Stash deletion [y,n,q,a,d%s,?]? "),
66 N_("Stash addition [y,n,q,a,d%s,?]? "),
67 N_("Stash this hunk [y,n,q,a,d%s,?]? "),
69 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
70 "will immediately be marked for stashing."),
71 .help_patch_text =
72 N_("y - stash this hunk\n"
73 "n - do not stash this hunk\n"
74 "q - quit; do not stash this hunk or any of the remaining "
75 "ones\n"
76 "a - stash this hunk and all later hunks in the file\n"
77 "d - do not stash this hunk or any of the later hunks in "
78 "the file\n"),
81 static struct patch_mode patch_mode_reset_head = {
82 .diff_cmd = { "diff-index", "--cached", NULL },
83 .apply_args = { "-R", "--cached", NULL },
84 .apply_check_args = { "-R", "--cached", NULL },
85 .is_reverse = 1,
86 .index_only = 1,
87 .prompt_mode = {
88 N_("Unstage mode change [y,n,q,a,d%s,?]? "),
89 N_("Unstage deletion [y,n,q,a,d%s,?]? "),
90 N_("Unstage addition [y,n,q,a,d%s,?]? "),
91 N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
93 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
94 "will immediately be marked for unstaging."),
95 .help_patch_text =
96 N_("y - unstage this hunk\n"
97 "n - do not unstage this hunk\n"
98 "q - quit; do not unstage this hunk or any of the remaining "
99 "ones\n"
100 "a - unstage this hunk and all later hunks in the file\n"
101 "d - do not unstage this hunk or any of the later hunks in "
102 "the file\n"),
105 static struct patch_mode patch_mode_reset_nothead = {
106 .diff_cmd = { "diff-index", "-R", "--cached", NULL },
107 .apply_args = { "--cached", NULL },
108 .apply_check_args = { "--cached", NULL },
109 .index_only = 1,
110 .prompt_mode = {
111 N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
112 N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
113 N_("Apply addition to index [y,n,q,a,d%s,?]? "),
114 N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
116 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
117 "will immediately be marked for applying."),
118 .help_patch_text =
119 N_("y - apply this hunk to index\n"
120 "n - do not apply this hunk to index\n"
121 "q - quit; do not apply this hunk or any of the remaining "
122 "ones\n"
123 "a - apply this hunk and all later hunks in the file\n"
124 "d - do not apply this hunk or any of the later hunks in "
125 "the file\n"),
128 static struct patch_mode patch_mode_checkout_index = {
129 .diff_cmd = { "diff-files", NULL },
130 .apply_args = { "-R", NULL },
131 .apply_check_args = { "-R", NULL },
132 .is_reverse = 1,
133 .prompt_mode = {
134 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
135 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
136 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
137 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
139 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
140 "will immediately be marked for discarding."),
141 .help_patch_text =
142 N_("y - discard this hunk from worktree\n"
143 "n - do not discard this hunk from worktree\n"
144 "q - quit; do not discard this hunk or any of the remaining "
145 "ones\n"
146 "a - discard this hunk and all later hunks in the file\n"
147 "d - do not discard this hunk or any of the later hunks in "
148 "the file\n"),
151 static struct patch_mode patch_mode_checkout_head = {
152 .diff_cmd = { "diff-index", NULL },
153 .apply_for_checkout = 1,
154 .apply_check_args = { "-R", NULL },
155 .is_reverse = 1,
156 .prompt_mode = {
157 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
158 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
159 N_("Discard addition from index and worktree [y,n,q,a,d%s,?]? "),
160 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
162 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
163 "will immediately be marked for discarding."),
164 .help_patch_text =
165 N_("y - discard this hunk from index and worktree\n"
166 "n - do not discard this hunk from index and worktree\n"
167 "q - quit; do not discard this hunk or any of the remaining "
168 "ones\n"
169 "a - discard this hunk and all later hunks in the file\n"
170 "d - do not discard this hunk or any of the later hunks in "
171 "the file\n"),
174 static struct patch_mode patch_mode_checkout_nothead = {
175 .diff_cmd = { "diff-index", "-R", NULL },
176 .apply_for_checkout = 1,
177 .apply_check_args = { NULL },
178 .prompt_mode = {
179 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
180 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
181 N_("Apply addition to index and worktree [y,n,q,a,d%s,?]? "),
182 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
184 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
185 "will immediately be marked for applying."),
186 .help_patch_text =
187 N_("y - apply this hunk to index and worktree\n"
188 "n - do not apply this hunk to index and worktree\n"
189 "q - quit; do not apply this hunk or any of the remaining "
190 "ones\n"
191 "a - apply this hunk and all later hunks in the file\n"
192 "d - do not apply this hunk or any of the later hunks in "
193 "the file\n"),
196 static struct patch_mode patch_mode_worktree_head = {
197 .diff_cmd = { "diff-index", NULL },
198 .apply_args = { "-R", NULL },
199 .apply_check_args = { "-R", NULL },
200 .is_reverse = 1,
201 .prompt_mode = {
202 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
203 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
204 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
205 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
207 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
208 "will immediately be marked for discarding."),
209 .help_patch_text =
210 N_("y - discard this hunk from worktree\n"
211 "n - do not discard this hunk from worktree\n"
212 "q - quit; do not discard this hunk or any of the remaining "
213 "ones\n"
214 "a - discard this hunk and all later hunks in the file\n"
215 "d - do not discard this hunk or any of the later hunks in "
216 "the file\n"),
219 static struct patch_mode patch_mode_worktree_nothead = {
220 .diff_cmd = { "diff-index", "-R", NULL },
221 .apply_args = { NULL },
222 .apply_check_args = { NULL },
223 .prompt_mode = {
224 N_("Apply mode change to worktree [y,n,q,a,d%s,?]? "),
225 N_("Apply deletion to worktree [y,n,q,a,d%s,?]? "),
226 N_("Apply addition to worktree [y,n,q,a,d%s,?]? "),
227 N_("Apply this hunk to worktree [y,n,q,a,d%s,?]? "),
229 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
230 "will immediately be marked for applying."),
231 .help_patch_text =
232 N_("y - apply this hunk to worktree\n"
233 "n - do not apply this hunk to worktree\n"
234 "q - quit; do not apply this hunk or any of the remaining "
235 "ones\n"
236 "a - apply this hunk and all later hunks in the file\n"
237 "d - do not apply this hunk or any of the later hunks in "
238 "the file\n"),
241 struct hunk_header {
242 unsigned long old_offset, old_count, new_offset, new_count;
244 * Start/end offsets to the extra text after the second `@@` in the
245 * hunk header, e.g. the function signature. This is expected to
246 * include the newline.
248 size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
249 unsigned suppress_colored_line_range:1;
252 struct hunk {
253 size_t start, end, colored_start, colored_end, splittable_into;
254 ssize_t delta;
255 enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
256 struct hunk_header header;
259 struct add_p_state {
260 struct add_i_state s;
261 struct strbuf answer, buf;
263 /* parsed diff */
264 struct strbuf plain, colored;
265 struct file_diff {
266 struct hunk head;
267 struct hunk *hunk;
268 size_t hunk_nr, hunk_alloc;
269 unsigned deleted:1, added:1, mode_change:1,binary:1;
270 } *file_diff;
271 size_t file_diff_nr;
273 /* patch mode */
274 struct patch_mode *mode;
275 const char *revision;
278 static void add_p_state_clear(struct add_p_state *s)
280 size_t i;
282 strbuf_release(&s->answer);
283 strbuf_release(&s->buf);
284 strbuf_release(&s->plain);
285 strbuf_release(&s->colored);
286 for (i = 0; i < s->file_diff_nr; i++)
287 free(s->file_diff[i].hunk);
288 free(s->file_diff);
289 clear_add_i_state(&s->s);
292 __attribute__((format (printf, 2, 3)))
293 static void err(struct add_p_state *s, const char *fmt, ...)
295 va_list args;
297 va_start(args, fmt);
298 fputs(s->s.error_color, stderr);
299 vfprintf(stderr, fmt, args);
300 fputs(s->s.reset_color, stderr);
301 fputc('\n', stderr);
302 va_end(args);
305 static void setup_child_process(struct add_p_state *s,
306 struct child_process *cp, ...)
308 va_list ap;
309 const char *arg;
311 va_start(ap, cp);
312 while ((arg = va_arg(ap, const char *)))
313 strvec_push(&cp->args, arg);
314 va_end(ap);
316 cp->git_cmd = 1;
317 strvec_pushf(&cp->env,
318 INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
321 static int parse_range(const char **p,
322 unsigned long *offset, unsigned long *count)
324 char *pend;
326 *offset = strtoul(*p, &pend, 10);
327 if (pend == *p)
328 return -1;
329 if (*pend != ',') {
330 *count = 1;
331 *p = pend;
332 return 0;
334 *count = strtoul(pend + 1, (char **)p, 10);
335 return *p == pend + 1 ? -1 : 0;
338 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
340 struct hunk_header *header = &hunk->header;
341 const char *line = s->plain.buf + hunk->start, *p = line;
342 char *eol = memchr(p, '\n', s->plain.len - hunk->start);
344 if (!eol)
345 eol = s->plain.buf + s->plain.len;
347 if (!skip_prefix(p, "@@ -", &p) ||
348 parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
349 !skip_prefix(p, " +", &p) ||
350 parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
351 !skip_prefix(p, " @@", &p))
352 return error(_("could not parse hunk header '%.*s'"),
353 (int)(eol - line), line);
355 hunk->start = eol - s->plain.buf + (*eol == '\n');
356 header->extra_start = p - s->plain.buf;
357 header->extra_end = hunk->start;
359 if (!s->colored.len) {
360 header->colored_extra_start = header->colored_extra_end = 0;
361 return 0;
364 /* Now find the extra text in the colored diff */
365 line = s->colored.buf + hunk->colored_start;
366 eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
367 if (!eol)
368 eol = s->colored.buf + s->colored.len;
369 p = memmem(line, eol - line, "@@ -", 4);
370 if (p && (p = memmem(p + 4, eol - p - 4, " @@", 3))) {
371 header->colored_extra_start = p + 3 - s->colored.buf;
372 } else {
373 /* could not parse colored hunk header, leave as-is */
374 header->colored_extra_start = hunk->colored_start;
375 header->suppress_colored_line_range = 1;
377 hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
378 header->colored_extra_end = hunk->colored_start;
380 return 0;
383 static int is_octal(const char *p, size_t len)
385 if (!len)
386 return 0;
388 while (len--)
389 if (*p < '0' || *(p++) > '7')
390 return 0;
391 return 1;
394 static void complete_file(char marker, struct hunk *hunk)
396 if (marker == '-' || marker == '+')
398 * Last hunk ended in non-context line (i.e. it
399 * appended lines to the file, so there are no
400 * trailing context lines).
402 hunk->splittable_into++;
405 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
407 struct strvec args = STRVEC_INIT;
408 const char *diff_algorithm = s->s.interactive_diff_algorithm;
409 struct strbuf *plain = &s->plain, *colored = NULL;
410 struct child_process cp = CHILD_PROCESS_INIT;
411 char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
412 size_t file_diff_alloc = 0, i, color_arg_index;
413 struct file_diff *file_diff = NULL;
414 struct hunk *hunk = NULL;
415 int res;
417 strvec_pushv(&args, s->mode->diff_cmd);
418 if (diff_algorithm)
419 strvec_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
420 if (s->revision) {
421 struct object_id oid;
422 strvec_push(&args,
423 /* could be on an unborn branch */
424 !strcmp("HEAD", s->revision) &&
425 repo_get_oid(the_repository, "HEAD", &oid) ?
426 empty_tree_oid_hex() : s->revision);
428 color_arg_index = args.nr;
429 /* Use `--no-color` explicitly, just in case `diff.color = always`. */
430 strvec_pushl(&args, "--no-color", "--ignore-submodules=dirty", "-p",
431 "--", NULL);
432 for (i = 0; i < ps->nr; i++)
433 strvec_push(&args, ps->items[i].original);
435 setup_child_process(s, &cp, NULL);
436 strvec_pushv(&cp.args, args.v);
437 res = capture_command(&cp, plain, 0);
438 if (res) {
439 strvec_clear(&args);
440 return error(_("could not parse diff"));
442 if (!plain->len) {
443 strvec_clear(&args);
444 return 0;
446 strbuf_complete_line(plain);
448 if (want_color_fd(1, -1)) {
449 struct child_process colored_cp = CHILD_PROCESS_INIT;
450 const char *diff_filter = s->s.interactive_diff_filter;
452 setup_child_process(s, &colored_cp, NULL);
453 xsnprintf((char *)args.v[color_arg_index], 8, "--color");
454 strvec_pushv(&colored_cp.args, args.v);
455 colored = &s->colored;
456 res = capture_command(&colored_cp, colored, 0);
457 strvec_clear(&args);
458 if (res)
459 return error(_("could not parse colored diff"));
461 if (diff_filter) {
462 struct child_process filter_cp = CHILD_PROCESS_INIT;
464 setup_child_process(s, &filter_cp,
465 diff_filter, NULL);
466 filter_cp.git_cmd = 0;
467 filter_cp.use_shell = 1;
468 strbuf_reset(&s->buf);
469 if (pipe_command(&filter_cp,
470 colored->buf, colored->len,
471 &s->buf, colored->len,
472 NULL, 0) < 0)
473 return error(_("failed to run '%s'"),
474 diff_filter);
475 strbuf_swap(colored, &s->buf);
478 strbuf_complete_line(colored);
479 colored_p = colored->buf;
480 colored_pend = colored_p + colored->len;
482 strvec_clear(&args);
484 /* parse files and hunks */
485 p = plain->buf;
486 pend = p + plain->len;
487 while (p != pend) {
488 char *eol = memchr(p, '\n', pend - p);
489 const char *deleted = NULL, *mode_change = NULL;
491 if (!eol)
492 eol = pend;
494 if (starts_with(p, "diff ") ||
495 starts_with(p, "* Unmerged path ")) {
496 complete_file(marker, hunk);
497 ALLOC_GROW_BY(s->file_diff, s->file_diff_nr, 1,
498 file_diff_alloc);
499 file_diff = s->file_diff + s->file_diff_nr - 1;
500 hunk = &file_diff->head;
501 hunk->start = p - plain->buf;
502 if (colored_p)
503 hunk->colored_start = colored_p - colored->buf;
504 marker = '\0';
505 } else if (p == plain->buf)
506 BUG("diff starts with unexpected line:\n"
507 "%.*s\n", (int)(eol - p), p);
508 else if (file_diff->deleted)
509 ; /* keep the rest of the file in a single "hunk" */
510 else if (starts_with(p, "@@ ") ||
511 (hunk == &file_diff->head &&
512 (skip_prefix(p, "deleted file", &deleted)))) {
513 if (marker == '-' || marker == '+')
515 * Should not happen; previous hunk did not end
516 * in a context line? Handle it anyway.
518 hunk->splittable_into++;
520 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
521 file_diff->hunk_alloc);
522 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
524 hunk->start = p - plain->buf;
525 if (colored)
526 hunk->colored_start = colored_p - colored->buf;
528 if (deleted)
529 file_diff->deleted = 1;
530 else if (parse_hunk_header(s, hunk) < 0)
531 return -1;
534 * Start counting into how many hunks this one can be
535 * split
537 marker = *p;
538 } else if (hunk == &file_diff->head &&
539 starts_with(p, "new file")) {
540 file_diff->added = 1;
541 } else if (hunk == &file_diff->head &&
542 skip_prefix(p, "old mode ", &mode_change) &&
543 is_octal(mode_change, eol - mode_change)) {
544 if (file_diff->mode_change)
545 BUG("double mode change?\n\n%.*s",
546 (int)(eol - plain->buf), plain->buf);
547 if (file_diff->hunk_nr)
548 BUG("mode change in the middle?\n\n%.*s",
549 (int)(eol - plain->buf), plain->buf);
552 * Do *not* change `hunk`: the mode change pseudo-hunk
553 * is _part of_ the header "hunk".
555 file_diff->mode_change = 1;
556 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
557 file_diff->hunk_alloc);
558 file_diff->hunk->start = p - plain->buf;
559 if (colored_p)
560 file_diff->hunk->colored_start =
561 colored_p - colored->buf;
562 } else if (hunk == &file_diff->head &&
563 skip_prefix(p, "new mode ", &mode_change) &&
564 is_octal(mode_change, eol - mode_change)) {
567 * Extend the "mode change" pseudo-hunk to include also
568 * the "new mode" line.
570 if (!file_diff->mode_change)
571 BUG("'new mode' without 'old mode'?\n\n%.*s",
572 (int)(eol - plain->buf), plain->buf);
573 if (file_diff->hunk_nr != 1)
574 BUG("mode change in the middle?\n\n%.*s",
575 (int)(eol - plain->buf), plain->buf);
576 if (p - plain->buf != file_diff->hunk->end)
577 BUG("'new mode' does not immediately follow "
578 "'old mode'?\n\n%.*s",
579 (int)(eol - plain->buf), plain->buf);
580 } else if (hunk == &file_diff->head &&
581 starts_with(p, "Binary files "))
582 file_diff->binary = 1;
584 if (!!file_diff->deleted + !!file_diff->added +
585 !!file_diff->mode_change > 1)
586 BUG("diff can only contain delete *or* add *or* a "
587 "mode change?!?\n%.*s",
588 (int)(eol - (plain->buf + file_diff->head.start)),
589 plain->buf + file_diff->head.start);
591 if ((marker == '-' || marker == '+') && *p == ' ')
592 hunk->splittable_into++;
593 if (marker && *p != '\\')
594 marker = *p;
596 p = eol == pend ? pend : eol + 1;
597 hunk->end = p - plain->buf;
599 if (colored) {
600 char *colored_eol = memchr(colored_p, '\n',
601 colored_pend - colored_p);
602 if (colored_eol)
603 colored_p = colored_eol + 1;
604 else if (p != pend)
605 /* non-colored has more lines? */
606 goto mismatched_output;
607 else if (colored_p == colored_pend)
608 /* last line has no matching colored one? */
609 goto mismatched_output;
610 else
611 colored_p = colored_pend;
613 hunk->colored_end = colored_p - colored->buf;
616 if (mode_change) {
617 if (file_diff->hunk_nr != 1)
618 BUG("mode change in hunk #%d???",
619 (int)file_diff->hunk_nr);
620 /* Adjust the end of the "mode change" pseudo-hunk */
621 file_diff->hunk->end = hunk->end;
622 if (colored)
623 file_diff->hunk->colored_end = hunk->colored_end;
626 complete_file(marker, hunk);
628 /* non-colored shorter than colored? */
629 if (colored_p != colored_pend) {
630 mismatched_output:
631 error(_("mismatched output from interactive.diffFilter"));
632 advise(_("Your filter must maintain a one-to-one correspondence\n"
633 "between its input and output lines."));
634 return -1;
637 return 0;
640 static size_t find_next_line(struct strbuf *sb, size_t offset)
642 char *eol;
644 if (offset >= sb->len)
645 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
646 (int)offset, (int)sb->len, sb->buf);
648 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
649 if (!eol)
650 return sb->len;
651 return eol - sb->buf + 1;
654 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
655 ssize_t delta, int colored, struct strbuf *out)
657 struct hunk_header *header = &hunk->header;
659 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
661 * Generate the hunk header dynamically, except for special
662 * hunks (such as the diff header).
664 const char *p;
665 size_t len;
666 unsigned long old_offset = header->old_offset;
667 unsigned long new_offset = header->new_offset;
669 if (!colored) {
670 p = s->plain.buf + header->extra_start;
671 len = header->extra_end - header->extra_start;
672 } else if (header->suppress_colored_line_range) {
673 strbuf_add(out,
674 s->colored.buf + header->colored_extra_start,
675 header->colored_extra_end -
676 header->colored_extra_start);
678 strbuf_add(out, s->colored.buf + hunk->colored_start,
679 hunk->colored_end - hunk->colored_start);
680 return;
681 } else {
682 strbuf_addstr(out, s->s.fraginfo_color);
683 p = s->colored.buf + header->colored_extra_start;
684 len = header->colored_extra_end
685 - header->colored_extra_start;
688 if (s->mode->is_reverse)
689 old_offset -= delta;
690 else
691 new_offset += delta;
693 strbuf_addf(out, "@@ -%lu", old_offset);
694 if (header->old_count != 1)
695 strbuf_addf(out, ",%lu", header->old_count);
696 strbuf_addf(out, " +%lu", new_offset);
697 if (header->new_count != 1)
698 strbuf_addf(out, ",%lu", header->new_count);
699 strbuf_addstr(out, " @@");
701 if (len)
702 strbuf_add(out, p, len);
703 else if (colored)
704 strbuf_addf(out, "%s\n", s->s.reset_color);
705 else
706 strbuf_addch(out, '\n');
709 if (colored)
710 strbuf_add(out, s->colored.buf + hunk->colored_start,
711 hunk->colored_end - hunk->colored_start);
712 else
713 strbuf_add(out, s->plain.buf + hunk->start,
714 hunk->end - hunk->start);
717 static void render_diff_header(struct add_p_state *s,
718 struct file_diff *file_diff, int colored,
719 struct strbuf *out)
722 * If there was a mode change, the first hunk is a pseudo hunk that
723 * corresponds to the mode line in the header. If the user did not want
724 * to stage that "hunk", we actually have to cut it out from the header.
726 int skip_mode_change =
727 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
728 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
730 if (!skip_mode_change) {
731 render_hunk(s, head, 0, colored, out);
732 return;
735 if (colored) {
736 const char *p = s->colored.buf;
738 strbuf_add(out, p + head->colored_start,
739 first->colored_start - head->colored_start);
740 strbuf_add(out, p + first->colored_end,
741 head->colored_end - first->colored_end);
742 } else {
743 const char *p = s->plain.buf;
745 strbuf_add(out, p + head->start, first->start - head->start);
746 strbuf_add(out, p + first->end, head->end - first->end);
750 /* Coalesce hunks again that were split */
751 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
752 size_t *hunk_index, int use_all, struct hunk *merged)
754 size_t i = *hunk_index, delta;
755 struct hunk *hunk = file_diff->hunk + i;
756 /* `header` corresponds to the merged hunk */
757 struct hunk_header *header = &merged->header, *next;
759 if (!use_all && hunk->use != USE_HUNK)
760 return 0;
762 *merged = *hunk;
763 /* We simply skip the colored part (if any) when merging hunks */
764 merged->colored_start = merged->colored_end = 0;
766 for (; i + 1 < file_diff->hunk_nr; i++) {
767 hunk++;
768 next = &hunk->header;
771 * Stop merging hunks when:
773 * - the hunk is not selected for use, or
774 * - the hunk does not overlap with the already-merged hunk(s)
776 if ((!use_all && hunk->use != USE_HUNK) ||
777 header->new_offset >= next->new_offset + merged->delta ||
778 header->new_offset + header->new_count
779 < next->new_offset + merged->delta)
780 break;
783 * If the hunks were not edited, and overlap, we can simply
784 * extend the line range.
786 if (merged->start < hunk->start && merged->end > hunk->start) {
787 merged->end = hunk->end;
788 merged->colored_end = hunk->colored_end;
789 delta = 0;
790 } else {
791 const char *plain = s->plain.buf;
792 size_t overlapping_line_count = header->new_offset
793 + header->new_count - merged->delta
794 - next->new_offset;
795 size_t overlap_end = hunk->start;
796 size_t overlap_start = overlap_end;
797 size_t overlap_next, len, j;
800 * One of the hunks was edited: the modified hunk was
801 * appended to the strbuf `s->plain`.
803 * Let's ensure that at least the last context line of
804 * the first hunk overlaps with the corresponding line
805 * of the second hunk, and then merge.
807 for (j = 0; j < overlapping_line_count; j++) {
808 overlap_next = find_next_line(&s->plain,
809 overlap_end);
811 if (overlap_next > hunk->end)
812 BUG("failed to find %d context lines "
813 "in:\n%.*s",
814 (int)overlapping_line_count,
815 (int)(hunk->end - hunk->start),
816 plain + hunk->start);
818 if (plain[overlap_end] != ' ')
819 return error(_("expected context line "
820 "#%d in\n%.*s"),
821 (int)(j + 1),
822 (int)(hunk->end
823 - hunk->start),
824 plain + hunk->start);
826 overlap_start = overlap_end;
827 overlap_end = overlap_next;
829 len = overlap_end - overlap_start;
831 if (len > merged->end - merged->start ||
832 memcmp(plain + merged->end - len,
833 plain + overlap_start, len))
834 return error(_("hunks do not overlap:\n%.*s\n"
835 "\tdoes not end with:\n%.*s"),
836 (int)(merged->end - merged->start),
837 plain + merged->start,
838 (int)len, plain + overlap_start);
841 * Since the start-end ranges are not adjacent, we
842 * cannot simply take the union of the ranges. To
843 * address that, we temporarily append the union of the
844 * lines to the `plain` strbuf.
846 if (merged->end != s->plain.len) {
847 size_t start = s->plain.len;
849 strbuf_add(&s->plain, plain + merged->start,
850 merged->end - merged->start);
851 plain = s->plain.buf;
852 merged->start = start;
853 merged->end = s->plain.len;
856 strbuf_add(&s->plain,
857 plain + overlap_end,
858 hunk->end - overlap_end);
859 merged->end = s->plain.len;
860 merged->splittable_into += hunk->splittable_into;
861 delta = merged->delta;
862 merged->delta += hunk->delta;
865 header->old_count = next->old_offset + next->old_count
866 - header->old_offset;
867 header->new_count = next->new_offset + delta
868 + next->new_count - header->new_offset;
871 if (i == *hunk_index)
872 return 0;
874 *hunk_index = i;
875 return 1;
878 static void reassemble_patch(struct add_p_state *s,
879 struct file_diff *file_diff, int use_all,
880 struct strbuf *out)
882 struct hunk *hunk;
883 size_t save_len = s->plain.len, i;
884 ssize_t delta = 0;
886 render_diff_header(s, file_diff, 0, out);
888 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
889 struct hunk merged = { 0 };
891 hunk = file_diff->hunk + i;
892 if (!use_all && hunk->use != USE_HUNK)
893 delta += hunk->header.old_count
894 - hunk->header.new_count;
895 else {
896 /* merge overlapping hunks into a temporary hunk */
897 if (merge_hunks(s, file_diff, &i, use_all, &merged))
898 hunk = &merged;
900 render_hunk(s, hunk, delta, 0, out);
903 * In case `merge_hunks()` used `plain` as a scratch
904 * pad (this happens when an edited hunk had to be
905 * coalesced with another hunk).
907 strbuf_setlen(&s->plain, save_len);
909 delta += hunk->delta;
914 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
915 size_t hunk_index)
917 int colored = !!s->colored.len, first = 1;
918 struct hunk *hunk = file_diff->hunk + hunk_index;
919 size_t splittable_into;
920 size_t end, colored_end, current, colored_current = 0, context_line_count;
921 struct hunk_header remaining, *header;
922 char marker, ch;
924 if (hunk_index >= file_diff->hunk_nr)
925 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
926 (int)hunk_index, (int)file_diff->hunk_nr);
928 if (hunk->splittable_into < 2)
929 return 0;
930 splittable_into = hunk->splittable_into;
932 end = hunk->end;
933 colored_end = hunk->colored_end;
935 remaining = hunk->header;
937 file_diff->hunk_nr += splittable_into - 1;
938 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
939 if (hunk_index + splittable_into < file_diff->hunk_nr)
940 memmove(file_diff->hunk + hunk_index + splittable_into,
941 file_diff->hunk + hunk_index + 1,
942 (file_diff->hunk_nr - hunk_index - splittable_into)
943 * sizeof(*hunk));
944 hunk = file_diff->hunk + hunk_index;
945 hunk->splittable_into = 1;
946 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
948 header = &hunk->header;
949 header->old_count = header->new_count = 0;
951 current = hunk->start;
952 if (colored)
953 colored_current = hunk->colored_start;
954 marker = '\0';
955 context_line_count = 0;
957 while (splittable_into > 1) {
958 ch = s->plain.buf[current];
960 if (!ch)
961 BUG("buffer overrun while splitting hunks");
964 * Is this the first context line after a chain of +/- lines?
965 * Then record the start of the next split hunk.
967 if ((marker == '-' || marker == '+') && ch == ' ') {
968 first = 0;
969 hunk[1].start = current;
970 if (colored)
971 hunk[1].colored_start = colored_current;
972 context_line_count = 0;
976 * Was the previous line a +/- one? Alternatively, is this the
977 * first line (and not a +/- one)?
979 * Then just increment the appropriate counter and continue
980 * with the next line.
982 if (marker != ' ' || (ch != '-' && ch != '+')) {
983 next_hunk_line:
984 /* Comment lines are attached to the previous line */
985 if (ch == '\\')
986 ch = marker ? marker : ' ';
988 /* current hunk not done yet */
989 if (ch == ' ')
990 context_line_count++;
991 else if (ch == '-')
992 header->old_count++;
993 else if (ch == '+')
994 header->new_count++;
995 else
996 BUG("unhandled diff marker: '%c'", ch);
997 marker = ch;
998 current = find_next_line(&s->plain, current);
999 if (colored)
1000 colored_current =
1001 find_next_line(&s->colored,
1002 colored_current);
1003 continue;
1007 * We got us the start of a new hunk!
1009 * This is a context line, so it is shared with the previous
1010 * hunk, if any.
1013 if (first) {
1014 if (header->old_count || header->new_count)
1015 BUG("counts are off: %d/%d",
1016 (int)header->old_count,
1017 (int)header->new_count);
1019 header->old_count = context_line_count;
1020 header->new_count = context_line_count;
1021 context_line_count = 0;
1022 first = 0;
1023 goto next_hunk_line;
1026 remaining.old_offset += header->old_count;
1027 remaining.old_count -= header->old_count;
1028 remaining.new_offset += header->new_count;
1029 remaining.new_count -= header->new_count;
1031 /* initialize next hunk header's offsets */
1032 hunk[1].header.old_offset =
1033 header->old_offset + header->old_count;
1034 hunk[1].header.new_offset =
1035 header->new_offset + header->new_count;
1037 /* add one split hunk */
1038 header->old_count += context_line_count;
1039 header->new_count += context_line_count;
1041 hunk->end = current;
1042 if (colored)
1043 hunk->colored_end = colored_current;
1045 hunk++;
1046 hunk->splittable_into = 1;
1047 hunk->use = hunk[-1].use;
1048 header = &hunk->header;
1050 header->old_count = header->new_count = context_line_count;
1051 context_line_count = 0;
1053 splittable_into--;
1054 marker = ch;
1057 /* last hunk simply gets the rest */
1058 if (header->old_offset != remaining.old_offset)
1059 BUG("miscounted old_offset: %lu != %lu",
1060 header->old_offset, remaining.old_offset);
1061 if (header->new_offset != remaining.new_offset)
1062 BUG("miscounted new_offset: %lu != %lu",
1063 header->new_offset, remaining.new_offset);
1064 header->old_count = remaining.old_count;
1065 header->new_count = remaining.new_count;
1066 hunk->end = end;
1067 if (colored)
1068 hunk->colored_end = colored_end;
1070 return 0;
1073 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1075 const char *plain = s->plain.buf;
1076 size_t current, eol, next;
1078 if (!s->colored.len)
1079 return;
1081 hunk->colored_start = s->colored.len;
1082 for (current = hunk->start; current < hunk->end; ) {
1083 for (eol = current; eol < hunk->end; eol++)
1084 if (plain[eol] == '\n')
1085 break;
1086 next = eol + (eol < hunk->end);
1087 if (eol > current && plain[eol - 1] == '\r')
1088 eol--;
1090 strbuf_addstr(&s->colored,
1091 plain[current] == '-' ?
1092 s->s.file_old_color :
1093 plain[current] == '+' ?
1094 s->s.file_new_color :
1095 s->s.context_color);
1096 strbuf_add(&s->colored, plain + current, eol - current);
1097 strbuf_addstr(&s->colored, s->s.reset_color);
1098 if (next > eol)
1099 strbuf_add(&s->colored, plain + eol, next - eol);
1100 current = next;
1102 hunk->colored_end = s->colored.len;
1105 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1107 size_t i;
1109 strbuf_reset(&s->buf);
1110 strbuf_commented_addf(&s->buf, comment_line_char,
1111 _("Manual hunk edit mode -- see bottom for "
1112 "a quick guide.\n"));
1113 render_hunk(s, hunk, 0, 0, &s->buf);
1114 strbuf_commented_addf(&s->buf, comment_line_char,
1115 _("---\n"
1116 "To remove '%c' lines, make them ' ' lines "
1117 "(context).\n"
1118 "To remove '%c' lines, delete them.\n"
1119 "Lines starting with %c will be removed.\n"),
1120 s->mode->is_reverse ? '+' : '-',
1121 s->mode->is_reverse ? '-' : '+',
1122 comment_line_char);
1123 strbuf_commented_addf(&s->buf, comment_line_char, "%s",
1124 _(s->mode->edit_hunk_hint));
1126 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1127 * messages.
1129 strbuf_commented_addf(&s->buf, comment_line_char,
1130 _("If it does not apply cleanly, you will be "
1131 "given an opportunity to\n"
1132 "edit again. If all lines of the hunk are "
1133 "removed, then the edit is\n"
1134 "aborted and the hunk is left unchanged.\n"));
1136 if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1137 return -1;
1139 /* strip out commented lines */
1140 hunk->start = s->plain.len;
1141 for (i = 0; i < s->buf.len; ) {
1142 size_t next = find_next_line(&s->buf, i);
1144 if (s->buf.buf[i] != comment_line_char)
1145 strbuf_add(&s->plain, s->buf.buf + i, next - i);
1146 i = next;
1149 hunk->end = s->plain.len;
1150 if (hunk->end == hunk->start)
1151 /* The user aborted editing by deleting everything */
1152 return 0;
1154 recolor_hunk(s, hunk);
1157 * If the hunk header is intact, parse it, otherwise simply use the
1158 * hunk header prior to editing (which will adjust `hunk->start` to
1159 * skip the hunk header).
1161 if (s->plain.buf[hunk->start] == '@' &&
1162 parse_hunk_header(s, hunk) < 0)
1163 return error(_("could not parse hunk header"));
1165 return 1;
1168 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1169 size_t orig_old_count, size_t orig_new_count)
1171 struct hunk_header *header = &hunk->header;
1172 size_t i;
1174 header->old_count = header->new_count = 0;
1175 for (i = hunk->start; i < hunk->end; ) {
1176 switch (s->plain.buf[i]) {
1177 case '-':
1178 header->old_count++;
1179 break;
1180 case '+':
1181 header->new_count++;
1182 break;
1183 case ' ': case '\r': case '\n':
1184 header->old_count++;
1185 header->new_count++;
1186 break;
1189 i = find_next_line(&s->plain, i);
1192 return orig_old_count - orig_new_count
1193 - header->old_count + header->new_count;
1196 static int run_apply_check(struct add_p_state *s,
1197 struct file_diff *file_diff)
1199 struct child_process cp = CHILD_PROCESS_INIT;
1201 strbuf_reset(&s->buf);
1202 reassemble_patch(s, file_diff, 1, &s->buf);
1204 setup_child_process(s, &cp,
1205 "apply", "--check", NULL);
1206 strvec_pushv(&cp.args, s->mode->apply_check_args);
1207 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1208 return error(_("'git apply --cached' failed"));
1210 return 0;
1213 static int read_single_character(struct add_p_state *s)
1215 if (s->s.use_single_key) {
1216 int res = read_key_without_echo(&s->answer);
1217 printf("%s\n", res == EOF ? "" : s->answer.buf);
1218 return res;
1221 if (git_read_line_interactively(&s->answer) == EOF)
1222 return EOF;
1223 return 0;
1226 static int prompt_yesno(struct add_p_state *s, const char *prompt)
1228 for (;;) {
1229 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1230 fflush(stdout);
1231 if (read_single_character(s) == EOF)
1232 return -1;
1233 switch (tolower(s->answer.buf[0])) {
1234 case 'n': return 0;
1235 case 'y': return 1;
1240 static int edit_hunk_loop(struct add_p_state *s,
1241 struct file_diff *file_diff, struct hunk *hunk)
1243 size_t plain_len = s->plain.len, colored_len = s->colored.len;
1244 struct hunk backup;
1246 backup = *hunk;
1248 for (;;) {
1249 int res = edit_hunk_manually(s, hunk);
1250 if (res == 0) {
1251 /* abandoned */
1252 *hunk = backup;
1253 return -1;
1256 if (res > 0) {
1257 hunk->delta +=
1258 recount_edited_hunk(s, hunk,
1259 backup.header.old_count,
1260 backup.header.new_count);
1261 if (!run_apply_check(s, file_diff))
1262 return 0;
1265 /* Drop edits (they were appended to s->plain) */
1266 strbuf_setlen(&s->plain, plain_len);
1267 strbuf_setlen(&s->colored, colored_len);
1268 *hunk = backup;
1271 * TRANSLATORS: do not translate [y/n]
1272 * The program will only accept that input at this point.
1273 * Consider translating (saying "no" discards!) as
1274 * (saying "n" for "no" discards!) if the translation
1275 * of the word "no" does not start with n.
1277 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1278 "Edit again (saying \"no\" discards!) "
1279 "[y/n]? "));
1280 if (res < 1)
1281 return -1;
1285 static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1286 int is_reverse)
1288 const char *reverse = is_reverse ? "-R" : NULL;
1289 struct child_process check_index = CHILD_PROCESS_INIT;
1290 struct child_process check_worktree = CHILD_PROCESS_INIT;
1291 struct child_process apply_index = CHILD_PROCESS_INIT;
1292 struct child_process apply_worktree = CHILD_PROCESS_INIT;
1293 int applies_index, applies_worktree;
1295 setup_child_process(s, &check_index,
1296 "apply", "--cached", "--check", reverse, NULL);
1297 applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1298 NULL, 0, NULL, 0);
1300 setup_child_process(s, &check_worktree,
1301 "apply", "--check", reverse, NULL);
1302 applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1303 NULL, 0, NULL, 0);
1305 if (applies_worktree && applies_index) {
1306 setup_child_process(s, &apply_index,
1307 "apply", "--cached", reverse, NULL);
1308 pipe_command(&apply_index, diff->buf, diff->len,
1309 NULL, 0, NULL, 0);
1311 setup_child_process(s, &apply_worktree,
1312 "apply", reverse, NULL);
1313 pipe_command(&apply_worktree, diff->buf, diff->len,
1314 NULL, 0, NULL, 0);
1316 return 1;
1319 if (!applies_index) {
1320 err(s, _("The selected hunks do not apply to the index!"));
1321 if (prompt_yesno(s, _("Apply them to the worktree "
1322 "anyway? ")) > 0) {
1323 setup_child_process(s, &apply_worktree,
1324 "apply", reverse, NULL);
1325 return pipe_command(&apply_worktree, diff->buf,
1326 diff->len, NULL, 0, NULL, 0);
1328 err(s, _("Nothing was applied.\n"));
1329 } else
1330 /* As a last resort, show the diff to the user */
1331 fwrite(diff->buf, diff->len, 1, stderr);
1333 return 0;
1336 #define SUMMARY_HEADER_WIDTH 20
1337 #define SUMMARY_LINE_WIDTH 80
1338 static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1339 struct strbuf *out)
1341 struct hunk_header *header = &hunk->header;
1342 struct strbuf *plain = &s->plain;
1343 size_t len = out->len, i;
1345 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1346 header->old_offset, header->old_count,
1347 header->new_offset, header->new_count);
1348 if (out->len - len < SUMMARY_HEADER_WIDTH)
1349 strbuf_addchars(out, ' ',
1350 SUMMARY_HEADER_WIDTH + len - out->len);
1351 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1352 if (plain->buf[i] != ' ')
1353 break;
1354 if (i < hunk->end)
1355 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1356 if (out->len - len > SUMMARY_LINE_WIDTH)
1357 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1358 strbuf_complete_line(out);
1361 #define DISPLAY_HUNKS_LINES 20
1362 static size_t display_hunks(struct add_p_state *s,
1363 struct file_diff *file_diff, size_t start_index)
1365 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1367 if (end_index > file_diff->hunk_nr)
1368 end_index = file_diff->hunk_nr;
1370 while (start_index < end_index) {
1371 struct hunk *hunk = file_diff->hunk + start_index++;
1373 strbuf_reset(&s->buf);
1374 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1375 : hunk->use == SKIP_HUNK ? '-' : ' ',
1376 (int)start_index);
1377 summarize_hunk(s, hunk, &s->buf);
1378 fputs(s->buf.buf, stdout);
1381 return end_index;
1384 static const char help_patch_remainder[] =
1385 N_("j - leave this hunk undecided, see next undecided hunk\n"
1386 "J - leave this hunk undecided, see next hunk\n"
1387 "k - leave this hunk undecided, see previous undecided hunk\n"
1388 "K - leave this hunk undecided, see previous hunk\n"
1389 "g - select a hunk to go to\n"
1390 "/ - search for a hunk matching the given regex\n"
1391 "s - split the current hunk into smaller hunks\n"
1392 "e - manually edit the current hunk\n"
1393 "? - print help\n");
1395 static int patch_update_file(struct add_p_state *s,
1396 struct file_diff *file_diff)
1398 size_t hunk_index = 0;
1399 ssize_t i, undecided_previous, undecided_next;
1400 struct hunk *hunk;
1401 char ch;
1402 struct child_process cp = CHILD_PROCESS_INIT;
1403 int colored = !!s->colored.len, quit = 0;
1404 enum prompt_mode_type prompt_mode_type;
1405 enum {
1406 ALLOW_GOTO_PREVIOUS_HUNK = 1 << 0,
1407 ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK = 1 << 1,
1408 ALLOW_GOTO_NEXT_HUNK = 1 << 2,
1409 ALLOW_GOTO_NEXT_UNDECIDED_HUNK = 1 << 3,
1410 ALLOW_SEARCH_AND_GOTO = 1 << 4,
1411 ALLOW_SPLIT = 1 << 5,
1412 ALLOW_EDIT = 1 << 6
1413 } permitted = 0;
1415 /* Empty added files have no hunks */
1416 if (!file_diff->hunk_nr && !file_diff->added)
1417 return 0;
1419 strbuf_reset(&s->buf);
1420 render_diff_header(s, file_diff, colored, &s->buf);
1421 fputs(s->buf.buf, stdout);
1422 for (;;) {
1423 if (hunk_index >= file_diff->hunk_nr)
1424 hunk_index = 0;
1425 hunk = file_diff->hunk_nr
1426 ? file_diff->hunk + hunk_index
1427 : &file_diff->head;
1428 undecided_previous = -1;
1429 undecided_next = -1;
1431 if (file_diff->hunk_nr) {
1432 for (i = hunk_index - 1; i >= 0; i--)
1433 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1434 undecided_previous = i;
1435 break;
1438 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1439 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1440 undecided_next = i;
1441 break;
1445 /* Everything decided? */
1446 if (undecided_previous < 0 && undecided_next < 0 &&
1447 hunk->use != UNDECIDED_HUNK)
1448 break;
1450 strbuf_reset(&s->buf);
1451 if (file_diff->hunk_nr) {
1452 render_hunk(s, hunk, 0, colored, &s->buf);
1453 fputs(s->buf.buf, stdout);
1455 strbuf_reset(&s->buf);
1456 if (undecided_previous >= 0) {
1457 permitted |= ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK;
1458 strbuf_addstr(&s->buf, ",k");
1460 if (hunk_index) {
1461 permitted |= ALLOW_GOTO_PREVIOUS_HUNK;
1462 strbuf_addstr(&s->buf, ",K");
1464 if (undecided_next >= 0) {
1465 permitted |= ALLOW_GOTO_NEXT_UNDECIDED_HUNK;
1466 strbuf_addstr(&s->buf, ",j");
1468 if (hunk_index + 1 < file_diff->hunk_nr) {
1469 permitted |= ALLOW_GOTO_NEXT_HUNK;
1470 strbuf_addstr(&s->buf, ",J");
1472 if (file_diff->hunk_nr > 1) {
1473 permitted |= ALLOW_SEARCH_AND_GOTO;
1474 strbuf_addstr(&s->buf, ",g,/");
1476 if (hunk->splittable_into > 1) {
1477 permitted |= ALLOW_SPLIT;
1478 strbuf_addstr(&s->buf, ",s");
1480 if (hunk_index + 1 > file_diff->mode_change &&
1481 !file_diff->deleted) {
1482 permitted |= ALLOW_EDIT;
1483 strbuf_addstr(&s->buf, ",e");
1486 if (file_diff->deleted)
1487 prompt_mode_type = PROMPT_DELETION;
1488 else if (file_diff->added)
1489 prompt_mode_type = PROMPT_ADDITION;
1490 else if (file_diff->mode_change && !hunk_index)
1491 prompt_mode_type = PROMPT_MODE_CHANGE;
1492 else
1493 prompt_mode_type = PROMPT_HUNK;
1495 printf("%s(%"PRIuMAX"/%"PRIuMAX") ", s->s.prompt_color,
1496 (uintmax_t)hunk_index + 1,
1497 (uintmax_t)(file_diff->hunk_nr
1498 ? file_diff->hunk_nr
1499 : 1));
1500 printf(_(s->mode->prompt_mode[prompt_mode_type]),
1501 s->buf.buf);
1502 if (*s->s.reset_color)
1503 fputs(s->s.reset_color, stdout);
1504 fflush(stdout);
1505 if (read_single_character(s) == EOF)
1506 break;
1508 if (!s->answer.len)
1509 continue;
1510 ch = tolower(s->answer.buf[0]);
1511 if (ch == 'y') {
1512 hunk->use = USE_HUNK;
1513 soft_increment:
1514 hunk_index = undecided_next < 0 ?
1515 file_diff->hunk_nr : undecided_next;
1516 } else if (ch == 'n') {
1517 hunk->use = SKIP_HUNK;
1518 goto soft_increment;
1519 } else if (ch == 'a') {
1520 if (file_diff->hunk_nr) {
1521 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1522 hunk = file_diff->hunk + hunk_index;
1523 if (hunk->use == UNDECIDED_HUNK)
1524 hunk->use = USE_HUNK;
1526 } else if (hunk->use == UNDECIDED_HUNK) {
1527 hunk->use = USE_HUNK;
1529 } else if (ch == 'd' || ch == 'q') {
1530 if (file_diff->hunk_nr) {
1531 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1532 hunk = file_diff->hunk + hunk_index;
1533 if (hunk->use == UNDECIDED_HUNK)
1534 hunk->use = SKIP_HUNK;
1536 } else if (hunk->use == UNDECIDED_HUNK) {
1537 hunk->use = SKIP_HUNK;
1539 if (ch == 'q') {
1540 quit = 1;
1541 break;
1543 } else if (s->answer.buf[0] == 'K') {
1544 if (permitted & ALLOW_GOTO_PREVIOUS_HUNK)
1545 hunk_index--;
1546 else
1547 err(s, _("No previous hunk"));
1548 } else if (s->answer.buf[0] == 'J') {
1549 if (permitted & ALLOW_GOTO_NEXT_HUNK)
1550 hunk_index++;
1551 else
1552 err(s, _("No next hunk"));
1553 } else if (s->answer.buf[0] == 'k') {
1554 if (permitted & ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK)
1555 hunk_index = undecided_previous;
1556 else
1557 err(s, _("No previous hunk"));
1558 } else if (s->answer.buf[0] == 'j') {
1559 if (permitted & ALLOW_GOTO_NEXT_UNDECIDED_HUNK)
1560 hunk_index = undecided_next;
1561 else
1562 err(s, _("No next hunk"));
1563 } else if (s->answer.buf[0] == 'g') {
1564 char *pend;
1565 unsigned long response;
1567 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1568 err(s, _("No other hunks to goto"));
1569 continue;
1571 strbuf_remove(&s->answer, 0, 1);
1572 strbuf_trim(&s->answer);
1573 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1574 if (i < (int)file_diff->mode_change)
1575 i = file_diff->mode_change;
1576 while (s->answer.len == 0) {
1577 i = display_hunks(s, file_diff, i);
1578 printf("%s", i < file_diff->hunk_nr ?
1579 _("go to which hunk (<ret> to see "
1580 "more)? ") : _("go to which hunk? "));
1581 fflush(stdout);
1582 if (strbuf_getline(&s->answer,
1583 stdin) == EOF)
1584 break;
1585 strbuf_trim_trailing_newline(&s->answer);
1588 strbuf_trim(&s->answer);
1589 response = strtoul(s->answer.buf, &pend, 10);
1590 if (*pend || pend == s->answer.buf)
1591 err(s, _("Invalid number: '%s'"),
1592 s->answer.buf);
1593 else if (0 < response && response <= file_diff->hunk_nr)
1594 hunk_index = response - 1;
1595 else
1596 err(s, Q_("Sorry, only %d hunk available.",
1597 "Sorry, only %d hunks available.",
1598 file_diff->hunk_nr),
1599 (int)file_diff->hunk_nr);
1600 } else if (s->answer.buf[0] == '/') {
1601 regex_t regex;
1602 int ret;
1604 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1605 err(s, _("No other hunks to search"));
1606 continue;
1608 strbuf_remove(&s->answer, 0, 1);
1609 strbuf_trim_trailing_newline(&s->answer);
1610 if (s->answer.len == 0) {
1611 printf("%s", _("search for regex? "));
1612 fflush(stdout);
1613 if (strbuf_getline(&s->answer,
1614 stdin) == EOF)
1615 break;
1616 strbuf_trim_trailing_newline(&s->answer);
1617 if (s->answer.len == 0)
1618 continue;
1620 ret = regcomp(&regex, s->answer.buf,
1621 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1622 if (ret) {
1623 char errbuf[1024];
1625 regerror(ret, &regex, errbuf, sizeof(errbuf));
1626 err(s, _("Malformed search regexp %s: %s"),
1627 s->answer.buf, errbuf);
1628 continue;
1630 i = hunk_index;
1631 for (;;) {
1632 /* render the hunk into a scratch buffer */
1633 render_hunk(s, file_diff->hunk + i, 0, 0,
1634 &s->buf);
1635 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1636 != REG_NOMATCH)
1637 break;
1638 i++;
1639 if (i == file_diff->hunk_nr)
1640 i = 0;
1641 if (i != hunk_index)
1642 continue;
1643 err(s, _("No hunk matches the given pattern"));
1644 break;
1646 hunk_index = i;
1647 } else if (s->answer.buf[0] == 's') {
1648 size_t splittable_into = hunk->splittable_into;
1649 if (!(permitted & ALLOW_SPLIT))
1650 err(s, _("Sorry, cannot split this hunk"));
1651 else if (!split_hunk(s, file_diff,
1652 hunk - file_diff->hunk))
1653 color_fprintf_ln(stdout, s->s.header_color,
1654 _("Split into %d hunks."),
1655 (int)splittable_into);
1656 } else if (s->answer.buf[0] == 'e') {
1657 if (!(permitted & ALLOW_EDIT))
1658 err(s, _("Sorry, cannot edit this hunk"));
1659 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1660 hunk->use = USE_HUNK;
1661 goto soft_increment;
1663 } else {
1664 const char *p = _(help_patch_remainder), *eol = p;
1666 color_fprintf(stdout, s->s.help_color, "%s",
1667 _(s->mode->help_patch_text));
1670 * Show only those lines of the remainder that are
1671 * actually applicable with the current hunk.
1673 for (; *p; p = eol + (*eol == '\n')) {
1674 eol = strchrnul(p, '\n');
1677 * `s->buf` still contains the part of the
1678 * commands shown in the prompt that are not
1679 * always available.
1681 if (*p != '?' && !strchr(s->buf.buf, *p))
1682 continue;
1684 color_fprintf_ln(stdout, s->s.help_color,
1685 "%.*s", (int)(eol - p), p);
1690 /* Any hunk to be used? */
1691 for (i = 0; i < file_diff->hunk_nr; i++)
1692 if (file_diff->hunk[i].use == USE_HUNK)
1693 break;
1695 if (i < file_diff->hunk_nr ||
1696 (!file_diff->hunk_nr && file_diff->head.use == USE_HUNK)) {
1697 /* At least one hunk selected: apply */
1698 strbuf_reset(&s->buf);
1699 reassemble_patch(s, file_diff, 0, &s->buf);
1701 discard_index(s->s.r->index);
1702 if (s->mode->apply_for_checkout)
1703 apply_for_checkout(s, &s->buf,
1704 s->mode->is_reverse);
1705 else {
1706 setup_child_process(s, &cp, "apply", NULL);
1707 strvec_pushv(&cp.args, s->mode->apply_args);
1708 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1709 NULL, 0, NULL, 0))
1710 error(_("'git apply' failed"));
1712 if (repo_read_index(s->s.r) >= 0)
1713 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
1714 1, NULL, NULL, NULL);
1717 putchar('\n');
1718 return quit;
1721 int run_add_p(struct repository *r, enum add_p_mode mode,
1722 const char *revision, const struct pathspec *ps)
1724 struct add_p_state s = {
1725 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1727 size_t i, binary_count = 0;
1729 init_add_i_state(&s.s, r);
1731 if (mode == ADD_P_STASH)
1732 s.mode = &patch_mode_stash;
1733 else if (mode == ADD_P_RESET) {
1735 * NEEDSWORK: Instead of comparing to the literal "HEAD",
1736 * compare the commit objects instead so that other ways of
1737 * saying the same thing (such as "@") are also handled
1738 * appropriately.
1740 * This applies to the cases below too.
1742 if (!revision || !strcmp(revision, "HEAD"))
1743 s.mode = &patch_mode_reset_head;
1744 else
1745 s.mode = &patch_mode_reset_nothead;
1746 } else if (mode == ADD_P_CHECKOUT) {
1747 if (!revision)
1748 s.mode = &patch_mode_checkout_index;
1749 else if (!strcmp(revision, "HEAD"))
1750 s.mode = &patch_mode_checkout_head;
1751 else
1752 s.mode = &patch_mode_checkout_nothead;
1753 } else if (mode == ADD_P_WORKTREE) {
1754 if (!revision)
1755 s.mode = &patch_mode_checkout_index;
1756 else if (!strcmp(revision, "HEAD"))
1757 s.mode = &patch_mode_worktree_head;
1758 else
1759 s.mode = &patch_mode_worktree_nothead;
1760 } else
1761 s.mode = &patch_mode_add;
1762 s.revision = revision;
1764 discard_index(r->index);
1765 if (repo_read_index(r) < 0 ||
1766 (!s.mode->index_only &&
1767 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1768 NULL, NULL, NULL) < 0) ||
1769 parse_diff(&s, ps) < 0) {
1770 add_p_state_clear(&s);
1771 return -1;
1774 for (i = 0; i < s.file_diff_nr; i++)
1775 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1776 binary_count++;
1777 else if (patch_update_file(&s, s.file_diff + i))
1778 break;
1780 if (s.file_diff_nr == 0)
1781 fprintf(stderr, _("No changes.\n"));
1782 else if (binary_count == s.file_diff_nr)
1783 fprintf(stderr, _("Only binary files changed.\n"));
1785 add_p_state_clear(&s);
1786 return 0;