Merge branch 'js/complete-checkout-t' into maint-2.42
[alt-git.git] / add-patch.c
blobbfe19876cd50c5aca2e465d9334c49e65a1972fc
1 #include "git-compat-util.h"
2 #include "add-interactive.h"
3 #include "advice.h"
4 #include "editor.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "object-name.h"
8 #include "read-cache-ll.h"
9 #include "repository.h"
10 #include "strbuf.h"
11 #include "run-command.h"
12 #include "strvec.h"
13 #include "pathspec.h"
14 #include "color.h"
15 #include "diff.h"
16 #include "compat/terminal.h"
17 #include "prompt.h"
19 enum prompt_mode_type {
20 PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_ADDITION, PROMPT_HUNK,
21 PROMPT_MODE_MAX, /* must be last */
24 struct patch_mode {
26 * The magic constant 4 is chosen such that all patch modes
27 * provide enough space for three command-line arguments followed by a
28 * trailing `NULL`.
30 const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
31 unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
32 const char *prompt_mode[PROMPT_MODE_MAX];
33 const char *edit_hunk_hint, *help_patch_text;
36 static struct patch_mode patch_mode_add = {
37 .diff_cmd = { "diff-files", NULL },
38 .apply_args = { "--cached", NULL },
39 .apply_check_args = { "--cached", NULL },
40 .prompt_mode = {
41 N_("Stage mode change [y,n,q,a,d%s,?]? "),
42 N_("Stage deletion [y,n,q,a,d%s,?]? "),
43 N_("Stage addition [y,n,q,a,d%s,?]? "),
44 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
46 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
47 "will immediately be marked for staging."),
48 .help_patch_text =
49 N_("y - stage this hunk\n"
50 "n - do not stage this hunk\n"
51 "q - quit; do not stage this hunk or any of the remaining "
52 "ones\n"
53 "a - stage this hunk and all later hunks in the file\n"
54 "d - do not stage this hunk or any of the later hunks in "
55 "the file\n")
58 static struct patch_mode patch_mode_stash = {
59 .diff_cmd = { "diff-index", "HEAD", NULL },
60 .apply_args = { "--cached", NULL },
61 .apply_check_args = { "--cached", NULL },
62 .prompt_mode = {
63 N_("Stash mode change [y,n,q,a,d%s,?]? "),
64 N_("Stash deletion [y,n,q,a,d%s,?]? "),
65 N_("Stash addition [y,n,q,a,d%s,?]? "),
66 N_("Stash this hunk [y,n,q,a,d%s,?]? "),
68 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
69 "will immediately be marked for stashing."),
70 .help_patch_text =
71 N_("y - stash this hunk\n"
72 "n - do not stash this hunk\n"
73 "q - quit; do not stash this hunk or any of the remaining "
74 "ones\n"
75 "a - stash this hunk and all later hunks in the file\n"
76 "d - do not stash this hunk or any of the later hunks in "
77 "the file\n"),
80 static struct patch_mode patch_mode_reset_head = {
81 .diff_cmd = { "diff-index", "--cached", NULL },
82 .apply_args = { "-R", "--cached", NULL },
83 .apply_check_args = { "-R", "--cached", NULL },
84 .is_reverse = 1,
85 .index_only = 1,
86 .prompt_mode = {
87 N_("Unstage mode change [y,n,q,a,d%s,?]? "),
88 N_("Unstage deletion [y,n,q,a,d%s,?]? "),
89 N_("Unstage addition [y,n,q,a,d%s,?]? "),
90 N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
92 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
93 "will immediately be marked for unstaging."),
94 .help_patch_text =
95 N_("y - unstage this hunk\n"
96 "n - do not unstage this hunk\n"
97 "q - quit; do not unstage this hunk or any of the remaining "
98 "ones\n"
99 "a - unstage this hunk and all later hunks in the file\n"
100 "d - do not unstage this hunk or any of the later hunks in "
101 "the file\n"),
104 static struct patch_mode patch_mode_reset_nothead = {
105 .diff_cmd = { "diff-index", "-R", "--cached", NULL },
106 .apply_args = { "--cached", NULL },
107 .apply_check_args = { "--cached", NULL },
108 .index_only = 1,
109 .prompt_mode = {
110 N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
111 N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
112 N_("Apply addition to index [y,n,q,a,d%s,?]? "),
113 N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
115 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
116 "will immediately be marked for applying."),
117 .help_patch_text =
118 N_("y - apply this hunk to index\n"
119 "n - do not apply this hunk to index\n"
120 "q - quit; do not apply this hunk or any of the remaining "
121 "ones\n"
122 "a - apply this hunk and all later hunks in the file\n"
123 "d - do not apply this hunk or any of the later hunks in "
124 "the file\n"),
127 static struct patch_mode patch_mode_checkout_index = {
128 .diff_cmd = { "diff-files", NULL },
129 .apply_args = { "-R", NULL },
130 .apply_check_args = { "-R", NULL },
131 .is_reverse = 1,
132 .prompt_mode = {
133 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
134 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
135 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
136 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
138 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
139 "will immediately be marked for discarding."),
140 .help_patch_text =
141 N_("y - discard this hunk from worktree\n"
142 "n - do not discard this hunk from worktree\n"
143 "q - quit; do not discard this hunk or any of the remaining "
144 "ones\n"
145 "a - discard this hunk and all later hunks in the file\n"
146 "d - do not discard this hunk or any of the later hunks in "
147 "the file\n"),
150 static struct patch_mode patch_mode_checkout_head = {
151 .diff_cmd = { "diff-index", NULL },
152 .apply_for_checkout = 1,
153 .apply_check_args = { "-R", NULL },
154 .is_reverse = 1,
155 .prompt_mode = {
156 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
157 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
158 N_("Discard addition from index and worktree [y,n,q,a,d%s,?]? "),
159 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
161 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
162 "will immediately be marked for discarding."),
163 .help_patch_text =
164 N_("y - discard this hunk from index and worktree\n"
165 "n - do not discard this hunk from index and worktree\n"
166 "q - quit; do not discard this hunk or any of the remaining "
167 "ones\n"
168 "a - discard this hunk and all later hunks in the file\n"
169 "d - do not discard this hunk or any of the later hunks in "
170 "the file\n"),
173 static struct patch_mode patch_mode_checkout_nothead = {
174 .diff_cmd = { "diff-index", "-R", NULL },
175 .apply_for_checkout = 1,
176 .apply_check_args = { NULL },
177 .prompt_mode = {
178 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
179 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
180 N_("Apply addition to index and worktree [y,n,q,a,d%s,?]? "),
181 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
183 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
184 "will immediately be marked for applying."),
185 .help_patch_text =
186 N_("y - apply this hunk to index and worktree\n"
187 "n - do not apply this hunk to index and worktree\n"
188 "q - quit; do not apply this hunk or any of the remaining "
189 "ones\n"
190 "a - apply this hunk and all later hunks in the file\n"
191 "d - do not apply this hunk or any of the later hunks in "
192 "the file\n"),
195 static struct patch_mode patch_mode_worktree_head = {
196 .diff_cmd = { "diff-index", NULL },
197 .apply_args = { "-R", NULL },
198 .apply_check_args = { "-R", NULL },
199 .is_reverse = 1,
200 .prompt_mode = {
201 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
202 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
203 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
204 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
206 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
207 "will immediately be marked for discarding."),
208 .help_patch_text =
209 N_("y - discard this hunk from worktree\n"
210 "n - do not discard this hunk from worktree\n"
211 "q - quit; do not discard this hunk or any of the remaining "
212 "ones\n"
213 "a - discard this hunk and all later hunks in the file\n"
214 "d - do not discard this hunk or any of the later hunks in "
215 "the file\n"),
218 static struct patch_mode patch_mode_worktree_nothead = {
219 .diff_cmd = { "diff-index", "-R", NULL },
220 .apply_args = { NULL },
221 .apply_check_args = { NULL },
222 .prompt_mode = {
223 N_("Apply mode change to worktree [y,n,q,a,d%s,?]? "),
224 N_("Apply deletion to worktree [y,n,q,a,d%s,?]? "),
225 N_("Apply addition to worktree [y,n,q,a,d%s,?]? "),
226 N_("Apply this hunk to worktree [y,n,q,a,d%s,?]? "),
228 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
229 "will immediately be marked for applying."),
230 .help_patch_text =
231 N_("y - apply this hunk to worktree\n"
232 "n - do not apply this hunk to worktree\n"
233 "q - quit; do not apply this hunk or any of the remaining "
234 "ones\n"
235 "a - apply this hunk and all later hunks in the file\n"
236 "d - do not apply this hunk or any of the later hunks in "
237 "the file\n"),
240 struct hunk_header {
241 unsigned long old_offset, old_count, new_offset, new_count;
243 * Start/end offsets to the extra text after the second `@@` in the
244 * hunk header, e.g. the function signature. This is expected to
245 * include the newline.
247 size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
248 unsigned suppress_colored_line_range:1;
251 struct hunk {
252 size_t start, end, colored_start, colored_end, splittable_into;
253 ssize_t delta;
254 enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
255 struct hunk_header header;
258 struct add_p_state {
259 struct add_i_state s;
260 struct strbuf answer, buf;
262 /* parsed diff */
263 struct strbuf plain, colored;
264 struct file_diff {
265 struct hunk head;
266 struct hunk *hunk;
267 size_t hunk_nr, hunk_alloc;
268 unsigned deleted:1, added:1, mode_change:1,binary:1;
269 } *file_diff;
270 size_t file_diff_nr;
272 /* patch mode */
273 struct patch_mode *mode;
274 const char *revision;
277 static void add_p_state_clear(struct add_p_state *s)
279 size_t i;
281 strbuf_release(&s->answer);
282 strbuf_release(&s->buf);
283 strbuf_release(&s->plain);
284 strbuf_release(&s->colored);
285 for (i = 0; i < s->file_diff_nr; i++)
286 free(s->file_diff[i].hunk);
287 free(s->file_diff);
288 clear_add_i_state(&s->s);
291 __attribute__((format (printf, 2, 3)))
292 static void err(struct add_p_state *s, const char *fmt, ...)
294 va_list args;
296 va_start(args, fmt);
297 fputs(s->s.error_color, stderr);
298 vfprintf(stderr, fmt, args);
299 fputs(s->s.reset_color, stderr);
300 fputc('\n', stderr);
301 va_end(args);
304 static void setup_child_process(struct add_p_state *s,
305 struct child_process *cp, ...)
307 va_list ap;
308 const char *arg;
310 va_start(ap, cp);
311 while ((arg = va_arg(ap, const char *)))
312 strvec_push(&cp->args, arg);
313 va_end(ap);
315 cp->git_cmd = 1;
316 strvec_pushf(&cp->env,
317 INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
320 static int parse_range(const char **p,
321 unsigned long *offset, unsigned long *count)
323 char *pend;
325 *offset = strtoul(*p, &pend, 10);
326 if (pend == *p)
327 return -1;
328 if (*pend != ',') {
329 *count = 1;
330 *p = pend;
331 return 0;
333 *count = strtoul(pend + 1, (char **)p, 10);
334 return *p == pend + 1 ? -1 : 0;
337 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
339 struct hunk_header *header = &hunk->header;
340 const char *line = s->plain.buf + hunk->start, *p = line;
341 char *eol = memchr(p, '\n', s->plain.len - hunk->start);
343 if (!eol)
344 eol = s->plain.buf + s->plain.len;
346 if (!skip_prefix(p, "@@ -", &p) ||
347 parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
348 !skip_prefix(p, " +", &p) ||
349 parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
350 !skip_prefix(p, " @@", &p))
351 return error(_("could not parse hunk header '%.*s'"),
352 (int)(eol - line), line);
354 hunk->start = eol - s->plain.buf + (*eol == '\n');
355 header->extra_start = p - s->plain.buf;
356 header->extra_end = hunk->start;
358 if (!s->colored.len) {
359 header->colored_extra_start = header->colored_extra_end = 0;
360 return 0;
363 /* Now find the extra text in the colored diff */
364 line = s->colored.buf + hunk->colored_start;
365 eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
366 if (!eol)
367 eol = s->colored.buf + s->colored.len;
368 p = memmem(line, eol - line, "@@ -", 4);
369 if (p && (p = memmem(p + 4, eol - p - 4, " @@", 3))) {
370 header->colored_extra_start = p + 3 - s->colored.buf;
371 } else {
372 /* could not parse colored hunk header, leave as-is */
373 header->colored_extra_start = hunk->colored_start;
374 header->suppress_colored_line_range = 1;
376 hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
377 header->colored_extra_end = hunk->colored_start;
379 return 0;
382 static int is_octal(const char *p, size_t len)
384 if (!len)
385 return 0;
387 while (len--)
388 if (*p < '0' || *(p++) > '7')
389 return 0;
390 return 1;
393 static void complete_file(char marker, struct hunk *hunk)
395 if (marker == '-' || marker == '+')
397 * Last hunk ended in non-context line (i.e. it
398 * appended lines to the file, so there are no
399 * trailing context lines).
401 hunk->splittable_into++;
404 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
406 struct strvec args = STRVEC_INIT;
407 const char *diff_algorithm = s->s.interactive_diff_algorithm;
408 struct strbuf *plain = &s->plain, *colored = NULL;
409 struct child_process cp = CHILD_PROCESS_INIT;
410 char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
411 size_t file_diff_alloc = 0, i, color_arg_index;
412 struct file_diff *file_diff = NULL;
413 struct hunk *hunk = NULL;
414 int res;
416 strvec_pushv(&args, s->mode->diff_cmd);
417 if (diff_algorithm)
418 strvec_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
419 if (s->revision) {
420 struct object_id oid;
421 strvec_push(&args,
422 /* could be on an unborn branch */
423 !strcmp("HEAD", s->revision) &&
424 repo_get_oid(the_repository, "HEAD", &oid) ?
425 empty_tree_oid_hex() : s->revision);
427 color_arg_index = args.nr;
428 /* Use `--no-color` explicitly, just in case `diff.color = always`. */
429 strvec_pushl(&args, "--no-color", "--ignore-submodules=dirty", "-p",
430 "--", NULL);
431 for (i = 0; i < ps->nr; i++)
432 strvec_push(&args, ps->items[i].original);
434 setup_child_process(s, &cp, NULL);
435 strvec_pushv(&cp.args, args.v);
436 res = capture_command(&cp, plain, 0);
437 if (res) {
438 strvec_clear(&args);
439 return error(_("could not parse diff"));
441 if (!plain->len) {
442 strvec_clear(&args);
443 return 0;
445 strbuf_complete_line(plain);
447 if (want_color_fd(1, -1)) {
448 struct child_process colored_cp = CHILD_PROCESS_INIT;
449 const char *diff_filter = s->s.interactive_diff_filter;
451 setup_child_process(s, &colored_cp, NULL);
452 xsnprintf((char *)args.v[color_arg_index], 8, "--color");
453 strvec_pushv(&colored_cp.args, args.v);
454 colored = &s->colored;
455 res = capture_command(&colored_cp, colored, 0);
456 strvec_clear(&args);
457 if (res)
458 return error(_("could not parse colored diff"));
460 if (diff_filter) {
461 struct child_process filter_cp = CHILD_PROCESS_INIT;
463 setup_child_process(s, &filter_cp,
464 diff_filter, NULL);
465 filter_cp.git_cmd = 0;
466 filter_cp.use_shell = 1;
467 strbuf_reset(&s->buf);
468 if (pipe_command(&filter_cp,
469 colored->buf, colored->len,
470 &s->buf, colored->len,
471 NULL, 0) < 0)
472 return error(_("failed to run '%s'"),
473 diff_filter);
474 strbuf_swap(colored, &s->buf);
477 strbuf_complete_line(colored);
478 colored_p = colored->buf;
479 colored_pend = colored_p + colored->len;
481 strvec_clear(&args);
483 /* parse files and hunks */
484 p = plain->buf;
485 pend = p + plain->len;
486 while (p != pend) {
487 char *eol = memchr(p, '\n', pend - p);
488 const char *deleted = NULL, *mode_change = NULL;
490 if (!eol)
491 eol = pend;
493 if (starts_with(p, "diff ") ||
494 starts_with(p, "* Unmerged path ")) {
495 complete_file(marker, hunk);
496 ALLOC_GROW_BY(s->file_diff, s->file_diff_nr, 1,
497 file_diff_alloc);
498 file_diff = s->file_diff + s->file_diff_nr - 1;
499 hunk = &file_diff->head;
500 hunk->start = p - plain->buf;
501 if (colored_p)
502 hunk->colored_start = colored_p - colored->buf;
503 marker = '\0';
504 } else if (p == plain->buf)
505 BUG("diff starts with unexpected line:\n"
506 "%.*s\n", (int)(eol - p), p);
507 else if (file_diff->deleted)
508 ; /* keep the rest of the file in a single "hunk" */
509 else if (starts_with(p, "@@ ") ||
510 (hunk == &file_diff->head &&
511 (skip_prefix(p, "deleted file", &deleted)))) {
512 if (marker == '-' || marker == '+')
514 * Should not happen; previous hunk did not end
515 * in a context line? Handle it anyway.
517 hunk->splittable_into++;
519 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
520 file_diff->hunk_alloc);
521 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
523 hunk->start = p - plain->buf;
524 if (colored)
525 hunk->colored_start = colored_p - colored->buf;
527 if (deleted)
528 file_diff->deleted = 1;
529 else if (parse_hunk_header(s, hunk) < 0)
530 return -1;
533 * Start counting into how many hunks this one can be
534 * split
536 marker = *p;
537 } else if (hunk == &file_diff->head &&
538 starts_with(p, "new file")) {
539 file_diff->added = 1;
540 } else if (hunk == &file_diff->head &&
541 skip_prefix(p, "old mode ", &mode_change) &&
542 is_octal(mode_change, eol - mode_change)) {
543 if (file_diff->mode_change)
544 BUG("double mode change?\n\n%.*s",
545 (int)(eol - plain->buf), plain->buf);
546 if (file_diff->hunk_nr)
547 BUG("mode change in the middle?\n\n%.*s",
548 (int)(eol - plain->buf), plain->buf);
551 * Do *not* change `hunk`: the mode change pseudo-hunk
552 * is _part of_ the header "hunk".
554 file_diff->mode_change = 1;
555 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
556 file_diff->hunk_alloc);
557 file_diff->hunk->start = p - plain->buf;
558 if (colored_p)
559 file_diff->hunk->colored_start =
560 colored_p - colored->buf;
561 } else if (hunk == &file_diff->head &&
562 skip_prefix(p, "new mode ", &mode_change) &&
563 is_octal(mode_change, eol - mode_change)) {
566 * Extend the "mode change" pseudo-hunk to include also
567 * the "new mode" line.
569 if (!file_diff->mode_change)
570 BUG("'new mode' without 'old mode'?\n\n%.*s",
571 (int)(eol - plain->buf), plain->buf);
572 if (file_diff->hunk_nr != 1)
573 BUG("mode change in the middle?\n\n%.*s",
574 (int)(eol - plain->buf), plain->buf);
575 if (p - plain->buf != file_diff->hunk->end)
576 BUG("'new mode' does not immediately follow "
577 "'old mode'?\n\n%.*s",
578 (int)(eol - plain->buf), plain->buf);
579 } else if (hunk == &file_diff->head &&
580 starts_with(p, "Binary files "))
581 file_diff->binary = 1;
583 if (!!file_diff->deleted + !!file_diff->added +
584 !!file_diff->mode_change > 1)
585 BUG("diff can only contain delete *or* add *or* a "
586 "mode change?!?\n%.*s",
587 (int)(eol - (plain->buf + file_diff->head.start)),
588 plain->buf + file_diff->head.start);
590 if ((marker == '-' || marker == '+') && *p == ' ')
591 hunk->splittable_into++;
592 if (marker && *p != '\\')
593 marker = *p;
595 p = eol == pend ? pend : eol + 1;
596 hunk->end = p - plain->buf;
598 if (colored) {
599 char *colored_eol = memchr(colored_p, '\n',
600 colored_pend - colored_p);
601 if (colored_eol)
602 colored_p = colored_eol + 1;
603 else if (p != pend)
604 /* non-colored has more lines? */
605 goto mismatched_output;
606 else if (colored_p == colored_pend)
607 /* last line has no matching colored one? */
608 goto mismatched_output;
609 else
610 colored_p = colored_pend;
612 hunk->colored_end = colored_p - colored->buf;
615 if (mode_change) {
616 if (file_diff->hunk_nr != 1)
617 BUG("mode change in hunk #%d???",
618 (int)file_diff->hunk_nr);
619 /* Adjust the end of the "mode change" pseudo-hunk */
620 file_diff->hunk->end = hunk->end;
621 if (colored)
622 file_diff->hunk->colored_end = hunk->colored_end;
625 complete_file(marker, hunk);
627 /* non-colored shorter than colored? */
628 if (colored_p != colored_pend) {
629 mismatched_output:
630 error(_("mismatched output from interactive.diffFilter"));
631 advise(_("Your filter must maintain a one-to-one correspondence\n"
632 "between its input and output lines."));
633 return -1;
636 return 0;
639 static size_t find_next_line(struct strbuf *sb, size_t offset)
641 char *eol;
643 if (offset >= sb->len)
644 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
645 (int)offset, (int)sb->len, sb->buf);
647 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
648 if (!eol)
649 return sb->len;
650 return eol - sb->buf + 1;
653 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
654 ssize_t delta, int colored, struct strbuf *out)
656 struct hunk_header *header = &hunk->header;
658 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
660 * Generate the hunk header dynamically, except for special
661 * hunks (such as the diff header).
663 const char *p;
664 size_t len;
665 unsigned long old_offset = header->old_offset;
666 unsigned long new_offset = header->new_offset;
668 if (!colored) {
669 p = s->plain.buf + header->extra_start;
670 len = header->extra_end - header->extra_start;
671 } else if (header->suppress_colored_line_range) {
672 strbuf_add(out,
673 s->colored.buf + header->colored_extra_start,
674 header->colored_extra_end -
675 header->colored_extra_start);
677 strbuf_add(out, s->colored.buf + hunk->colored_start,
678 hunk->colored_end - hunk->colored_start);
679 return;
680 } else {
681 strbuf_addstr(out, s->s.fraginfo_color);
682 p = s->colored.buf + header->colored_extra_start;
683 len = header->colored_extra_end
684 - header->colored_extra_start;
687 if (s->mode->is_reverse)
688 old_offset -= delta;
689 else
690 new_offset += delta;
692 strbuf_addf(out, "@@ -%lu", old_offset);
693 if (header->old_count != 1)
694 strbuf_addf(out, ",%lu", header->old_count);
695 strbuf_addf(out, " +%lu", new_offset);
696 if (header->new_count != 1)
697 strbuf_addf(out, ",%lu", header->new_count);
698 strbuf_addstr(out, " @@");
700 if (len)
701 strbuf_add(out, p, len);
702 else if (colored)
703 strbuf_addf(out, "%s\n", s->s.reset_color);
704 else
705 strbuf_addch(out, '\n');
708 if (colored)
709 strbuf_add(out, s->colored.buf + hunk->colored_start,
710 hunk->colored_end - hunk->colored_start);
711 else
712 strbuf_add(out, s->plain.buf + hunk->start,
713 hunk->end - hunk->start);
716 static void render_diff_header(struct add_p_state *s,
717 struct file_diff *file_diff, int colored,
718 struct strbuf *out)
721 * If there was a mode change, the first hunk is a pseudo hunk that
722 * corresponds to the mode line in the header. If the user did not want
723 * to stage that "hunk", we actually have to cut it out from the header.
725 int skip_mode_change =
726 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
727 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
729 if (!skip_mode_change) {
730 render_hunk(s, head, 0, colored, out);
731 return;
734 if (colored) {
735 const char *p = s->colored.buf;
737 strbuf_add(out, p + head->colored_start,
738 first->colored_start - head->colored_start);
739 strbuf_add(out, p + first->colored_end,
740 head->colored_end - first->colored_end);
741 } else {
742 const char *p = s->plain.buf;
744 strbuf_add(out, p + head->start, first->start - head->start);
745 strbuf_add(out, p + first->end, head->end - first->end);
749 /* Coalesce hunks again that were split */
750 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
751 size_t *hunk_index, int use_all, struct hunk *merged)
753 size_t i = *hunk_index, delta;
754 struct hunk *hunk = file_diff->hunk + i;
755 /* `header` corresponds to the merged hunk */
756 struct hunk_header *header = &merged->header, *next;
758 if (!use_all && hunk->use != USE_HUNK)
759 return 0;
761 *merged = *hunk;
762 /* We simply skip the colored part (if any) when merging hunks */
763 merged->colored_start = merged->colored_end = 0;
765 for (; i + 1 < file_diff->hunk_nr; i++) {
766 hunk++;
767 next = &hunk->header;
770 * Stop merging hunks when:
772 * - the hunk is not selected for use, or
773 * - the hunk does not overlap with the already-merged hunk(s)
775 if ((!use_all && hunk->use != USE_HUNK) ||
776 header->new_offset >= next->new_offset + merged->delta ||
777 header->new_offset + header->new_count
778 < next->new_offset + merged->delta)
779 break;
782 * If the hunks were not edited, and overlap, we can simply
783 * extend the line range.
785 if (merged->start < hunk->start && merged->end > hunk->start) {
786 merged->end = hunk->end;
787 merged->colored_end = hunk->colored_end;
788 delta = 0;
789 } else {
790 const char *plain = s->plain.buf;
791 size_t overlapping_line_count = header->new_offset
792 + header->new_count - merged->delta
793 - next->new_offset;
794 size_t overlap_end = hunk->start;
795 size_t overlap_start = overlap_end;
796 size_t overlap_next, len, j;
799 * One of the hunks was edited: the modified hunk was
800 * appended to the strbuf `s->plain`.
802 * Let's ensure that at least the last context line of
803 * the first hunk overlaps with the corresponding line
804 * of the second hunk, and then merge.
806 for (j = 0; j < overlapping_line_count; j++) {
807 overlap_next = find_next_line(&s->plain,
808 overlap_end);
810 if (overlap_next > hunk->end)
811 BUG("failed to find %d context lines "
812 "in:\n%.*s",
813 (int)overlapping_line_count,
814 (int)(hunk->end - hunk->start),
815 plain + hunk->start);
817 if (plain[overlap_end] != ' ')
818 return error(_("expected context line "
819 "#%d in\n%.*s"),
820 (int)(j + 1),
821 (int)(hunk->end
822 - hunk->start),
823 plain + hunk->start);
825 overlap_start = overlap_end;
826 overlap_end = overlap_next;
828 len = overlap_end - overlap_start;
830 if (len > merged->end - merged->start ||
831 memcmp(plain + merged->end - len,
832 plain + overlap_start, len))
833 return error(_("hunks do not overlap:\n%.*s\n"
834 "\tdoes not end with:\n%.*s"),
835 (int)(merged->end - merged->start),
836 plain + merged->start,
837 (int)len, plain + overlap_start);
840 * Since the start-end ranges are not adjacent, we
841 * cannot simply take the union of the ranges. To
842 * address that, we temporarily append the union of the
843 * lines to the `plain` strbuf.
845 if (merged->end != s->plain.len) {
846 size_t start = s->plain.len;
848 strbuf_add(&s->plain, plain + merged->start,
849 merged->end - merged->start);
850 plain = s->plain.buf;
851 merged->start = start;
852 merged->end = s->plain.len;
855 strbuf_add(&s->plain,
856 plain + overlap_end,
857 hunk->end - overlap_end);
858 merged->end = s->plain.len;
859 merged->splittable_into += hunk->splittable_into;
860 delta = merged->delta;
861 merged->delta += hunk->delta;
864 header->old_count = next->old_offset + next->old_count
865 - header->old_offset;
866 header->new_count = next->new_offset + delta
867 + next->new_count - header->new_offset;
870 if (i == *hunk_index)
871 return 0;
873 *hunk_index = i;
874 return 1;
877 static void reassemble_patch(struct add_p_state *s,
878 struct file_diff *file_diff, int use_all,
879 struct strbuf *out)
881 struct hunk *hunk;
882 size_t save_len = s->plain.len, i;
883 ssize_t delta = 0;
885 render_diff_header(s, file_diff, 0, out);
887 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
888 struct hunk merged = { 0 };
890 hunk = file_diff->hunk + i;
891 if (!use_all && hunk->use != USE_HUNK)
892 delta += hunk->header.old_count
893 - hunk->header.new_count;
894 else {
895 /* merge overlapping hunks into a temporary hunk */
896 if (merge_hunks(s, file_diff, &i, use_all, &merged))
897 hunk = &merged;
899 render_hunk(s, hunk, delta, 0, out);
902 * In case `merge_hunks()` used `plain` as a scratch
903 * pad (this happens when an edited hunk had to be
904 * coalesced with another hunk).
906 strbuf_setlen(&s->plain, save_len);
908 delta += hunk->delta;
913 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
914 size_t hunk_index)
916 int colored = !!s->colored.len, first = 1;
917 struct hunk *hunk = file_diff->hunk + hunk_index;
918 size_t splittable_into;
919 size_t end, colored_end, current, colored_current = 0, context_line_count;
920 struct hunk_header remaining, *header;
921 char marker, ch;
923 if (hunk_index >= file_diff->hunk_nr)
924 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
925 (int)hunk_index, (int)file_diff->hunk_nr);
927 if (hunk->splittable_into < 2)
928 return 0;
929 splittable_into = hunk->splittable_into;
931 end = hunk->end;
932 colored_end = hunk->colored_end;
934 remaining = hunk->header;
936 file_diff->hunk_nr += splittable_into - 1;
937 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
938 if (hunk_index + splittable_into < file_diff->hunk_nr)
939 memmove(file_diff->hunk + hunk_index + splittable_into,
940 file_diff->hunk + hunk_index + 1,
941 (file_diff->hunk_nr - hunk_index - splittable_into)
942 * sizeof(*hunk));
943 hunk = file_diff->hunk + hunk_index;
944 hunk->splittable_into = 1;
945 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
947 header = &hunk->header;
948 header->old_count = header->new_count = 0;
950 current = hunk->start;
951 if (colored)
952 colored_current = hunk->colored_start;
953 marker = '\0';
954 context_line_count = 0;
956 while (splittable_into > 1) {
957 ch = s->plain.buf[current];
959 if (!ch)
960 BUG("buffer overrun while splitting hunks");
963 * Is this the first context line after a chain of +/- lines?
964 * Then record the start of the next split hunk.
966 if ((marker == '-' || marker == '+') && ch == ' ') {
967 first = 0;
968 hunk[1].start = current;
969 if (colored)
970 hunk[1].colored_start = colored_current;
971 context_line_count = 0;
975 * Was the previous line a +/- one? Alternatively, is this the
976 * first line (and not a +/- one)?
978 * Then just increment the appropriate counter and continue
979 * with the next line.
981 if (marker != ' ' || (ch != '-' && ch != '+')) {
982 next_hunk_line:
983 /* Comment lines are attached to the previous line */
984 if (ch == '\\')
985 ch = marker ? marker : ' ';
987 /* current hunk not done yet */
988 if (ch == ' ')
989 context_line_count++;
990 else if (ch == '-')
991 header->old_count++;
992 else if (ch == '+')
993 header->new_count++;
994 else
995 BUG("unhandled diff marker: '%c'", ch);
996 marker = ch;
997 current = find_next_line(&s->plain, current);
998 if (colored)
999 colored_current =
1000 find_next_line(&s->colored,
1001 colored_current);
1002 continue;
1006 * We got us the start of a new hunk!
1008 * This is a context line, so it is shared with the previous
1009 * hunk, if any.
1012 if (first) {
1013 if (header->old_count || header->new_count)
1014 BUG("counts are off: %d/%d",
1015 (int)header->old_count,
1016 (int)header->new_count);
1018 header->old_count = context_line_count;
1019 header->new_count = context_line_count;
1020 context_line_count = 0;
1021 first = 0;
1022 goto next_hunk_line;
1025 remaining.old_offset += header->old_count;
1026 remaining.old_count -= header->old_count;
1027 remaining.new_offset += header->new_count;
1028 remaining.new_count -= header->new_count;
1030 /* initialize next hunk header's offsets */
1031 hunk[1].header.old_offset =
1032 header->old_offset + header->old_count;
1033 hunk[1].header.new_offset =
1034 header->new_offset + header->new_count;
1036 /* add one split hunk */
1037 header->old_count += context_line_count;
1038 header->new_count += context_line_count;
1040 hunk->end = current;
1041 if (colored)
1042 hunk->colored_end = colored_current;
1044 hunk++;
1045 hunk->splittable_into = 1;
1046 hunk->use = hunk[-1].use;
1047 header = &hunk->header;
1049 header->old_count = header->new_count = context_line_count;
1050 context_line_count = 0;
1052 splittable_into--;
1053 marker = ch;
1056 /* last hunk simply gets the rest */
1057 if (header->old_offset != remaining.old_offset)
1058 BUG("miscounted old_offset: %lu != %lu",
1059 header->old_offset, remaining.old_offset);
1060 if (header->new_offset != remaining.new_offset)
1061 BUG("miscounted new_offset: %lu != %lu",
1062 header->new_offset, remaining.new_offset);
1063 header->old_count = remaining.old_count;
1064 header->new_count = remaining.new_count;
1065 hunk->end = end;
1066 if (colored)
1067 hunk->colored_end = colored_end;
1069 return 0;
1072 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1074 const char *plain = s->plain.buf;
1075 size_t current, eol, next;
1077 if (!s->colored.len)
1078 return;
1080 hunk->colored_start = s->colored.len;
1081 for (current = hunk->start; current < hunk->end; ) {
1082 for (eol = current; eol < hunk->end; eol++)
1083 if (plain[eol] == '\n')
1084 break;
1085 next = eol + (eol < hunk->end);
1086 if (eol > current && plain[eol - 1] == '\r')
1087 eol--;
1089 strbuf_addstr(&s->colored,
1090 plain[current] == '-' ?
1091 s->s.file_old_color :
1092 plain[current] == '+' ?
1093 s->s.file_new_color :
1094 s->s.context_color);
1095 strbuf_add(&s->colored, plain + current, eol - current);
1096 strbuf_addstr(&s->colored, s->s.reset_color);
1097 if (next > eol)
1098 strbuf_add(&s->colored, plain + eol, next - eol);
1099 current = next;
1101 hunk->colored_end = s->colored.len;
1104 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1106 size_t i;
1108 strbuf_reset(&s->buf);
1109 strbuf_commented_addf(&s->buf, comment_line_char,
1110 _("Manual hunk edit mode -- see bottom for "
1111 "a quick guide.\n"));
1112 render_hunk(s, hunk, 0, 0, &s->buf);
1113 strbuf_commented_addf(&s->buf, comment_line_char,
1114 _("---\n"
1115 "To remove '%c' lines, make them ' ' lines "
1116 "(context).\n"
1117 "To remove '%c' lines, delete them.\n"
1118 "Lines starting with %c will be removed.\n"),
1119 s->mode->is_reverse ? '+' : '-',
1120 s->mode->is_reverse ? '-' : '+',
1121 comment_line_char);
1122 strbuf_commented_addf(&s->buf, comment_line_char, "%s",
1123 _(s->mode->edit_hunk_hint));
1125 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1126 * messages.
1128 strbuf_commented_addf(&s->buf, comment_line_char,
1129 _("If it does not apply cleanly, you will be "
1130 "given an opportunity to\n"
1131 "edit again. If all lines of the hunk are "
1132 "removed, then the edit is\n"
1133 "aborted and the hunk is left unchanged.\n"));
1135 if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1136 return -1;
1138 /* strip out commented lines */
1139 hunk->start = s->plain.len;
1140 for (i = 0; i < s->buf.len; ) {
1141 size_t next = find_next_line(&s->buf, i);
1143 if (s->buf.buf[i] != comment_line_char)
1144 strbuf_add(&s->plain, s->buf.buf + i, next - i);
1145 i = next;
1148 hunk->end = s->plain.len;
1149 if (hunk->end == hunk->start)
1150 /* The user aborted editing by deleting everything */
1151 return 0;
1153 recolor_hunk(s, hunk);
1156 * If the hunk header is intact, parse it, otherwise simply use the
1157 * hunk header prior to editing (which will adjust `hunk->start` to
1158 * skip the hunk header).
1160 if (s->plain.buf[hunk->start] == '@' &&
1161 parse_hunk_header(s, hunk) < 0)
1162 return error(_("could not parse hunk header"));
1164 return 1;
1167 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1168 size_t orig_old_count, size_t orig_new_count)
1170 struct hunk_header *header = &hunk->header;
1171 size_t i;
1173 header->old_count = header->new_count = 0;
1174 for (i = hunk->start; i < hunk->end; ) {
1175 switch (s->plain.buf[i]) {
1176 case '-':
1177 header->old_count++;
1178 break;
1179 case '+':
1180 header->new_count++;
1181 break;
1182 case ' ': case '\r': case '\n':
1183 header->old_count++;
1184 header->new_count++;
1185 break;
1188 i = find_next_line(&s->plain, i);
1191 return orig_old_count - orig_new_count
1192 - header->old_count + header->new_count;
1195 static int run_apply_check(struct add_p_state *s,
1196 struct file_diff *file_diff)
1198 struct child_process cp = CHILD_PROCESS_INIT;
1200 strbuf_reset(&s->buf);
1201 reassemble_patch(s, file_diff, 1, &s->buf);
1203 setup_child_process(s, &cp,
1204 "apply", "--check", NULL);
1205 strvec_pushv(&cp.args, s->mode->apply_check_args);
1206 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1207 return error(_("'git apply --cached' failed"));
1209 return 0;
1212 static int read_single_character(struct add_p_state *s)
1214 if (s->s.use_single_key) {
1215 int res = read_key_without_echo(&s->answer);
1216 printf("%s\n", res == EOF ? "" : s->answer.buf);
1217 return res;
1220 if (git_read_line_interactively(&s->answer) == EOF)
1221 return EOF;
1222 return 0;
1225 static int prompt_yesno(struct add_p_state *s, const char *prompt)
1227 for (;;) {
1228 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1229 fflush(stdout);
1230 if (read_single_character(s) == EOF)
1231 return -1;
1232 switch (tolower(s->answer.buf[0])) {
1233 case 'n': return 0;
1234 case 'y': return 1;
1239 static int edit_hunk_loop(struct add_p_state *s,
1240 struct file_diff *file_diff, struct hunk *hunk)
1242 size_t plain_len = s->plain.len, colored_len = s->colored.len;
1243 struct hunk backup;
1245 backup = *hunk;
1247 for (;;) {
1248 int res = edit_hunk_manually(s, hunk);
1249 if (res == 0) {
1250 /* abandoned */
1251 *hunk = backup;
1252 return -1;
1255 if (res > 0) {
1256 hunk->delta +=
1257 recount_edited_hunk(s, hunk,
1258 backup.header.old_count,
1259 backup.header.new_count);
1260 if (!run_apply_check(s, file_diff))
1261 return 0;
1264 /* Drop edits (they were appended to s->plain) */
1265 strbuf_setlen(&s->plain, plain_len);
1266 strbuf_setlen(&s->colored, colored_len);
1267 *hunk = backup;
1270 * TRANSLATORS: do not translate [y/n]
1271 * The program will only accept that input at this point.
1272 * Consider translating (saying "no" discards!) as
1273 * (saying "n" for "no" discards!) if the translation
1274 * of the word "no" does not start with n.
1276 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1277 "Edit again (saying \"no\" discards!) "
1278 "[y/n]? "));
1279 if (res < 1)
1280 return -1;
1284 static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1285 int is_reverse)
1287 const char *reverse = is_reverse ? "-R" : NULL;
1288 struct child_process check_index = CHILD_PROCESS_INIT;
1289 struct child_process check_worktree = CHILD_PROCESS_INIT;
1290 struct child_process apply_index = CHILD_PROCESS_INIT;
1291 struct child_process apply_worktree = CHILD_PROCESS_INIT;
1292 int applies_index, applies_worktree;
1294 setup_child_process(s, &check_index,
1295 "apply", "--cached", "--check", reverse, NULL);
1296 applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1297 NULL, 0, NULL, 0);
1299 setup_child_process(s, &check_worktree,
1300 "apply", "--check", reverse, NULL);
1301 applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1302 NULL, 0, NULL, 0);
1304 if (applies_worktree && applies_index) {
1305 setup_child_process(s, &apply_index,
1306 "apply", "--cached", reverse, NULL);
1307 pipe_command(&apply_index, diff->buf, diff->len,
1308 NULL, 0, NULL, 0);
1310 setup_child_process(s, &apply_worktree,
1311 "apply", reverse, NULL);
1312 pipe_command(&apply_worktree, diff->buf, diff->len,
1313 NULL, 0, NULL, 0);
1315 return 1;
1318 if (!applies_index) {
1319 err(s, _("The selected hunks do not apply to the index!"));
1320 if (prompt_yesno(s, _("Apply them to the worktree "
1321 "anyway? ")) > 0) {
1322 setup_child_process(s, &apply_worktree,
1323 "apply", reverse, NULL);
1324 return pipe_command(&apply_worktree, diff->buf,
1325 diff->len, NULL, 0, NULL, 0);
1327 err(s, _("Nothing was applied.\n"));
1328 } else
1329 /* As a last resort, show the diff to the user */
1330 fwrite(diff->buf, diff->len, 1, stderr);
1332 return 0;
1335 #define SUMMARY_HEADER_WIDTH 20
1336 #define SUMMARY_LINE_WIDTH 80
1337 static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1338 struct strbuf *out)
1340 struct hunk_header *header = &hunk->header;
1341 struct strbuf *plain = &s->plain;
1342 size_t len = out->len, i;
1344 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1345 header->old_offset, header->old_count,
1346 header->new_offset, header->new_count);
1347 if (out->len - len < SUMMARY_HEADER_WIDTH)
1348 strbuf_addchars(out, ' ',
1349 SUMMARY_HEADER_WIDTH + len - out->len);
1350 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1351 if (plain->buf[i] != ' ')
1352 break;
1353 if (i < hunk->end)
1354 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1355 if (out->len - len > SUMMARY_LINE_WIDTH)
1356 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1357 strbuf_complete_line(out);
1360 #define DISPLAY_HUNKS_LINES 20
1361 static size_t display_hunks(struct add_p_state *s,
1362 struct file_diff *file_diff, size_t start_index)
1364 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1366 if (end_index > file_diff->hunk_nr)
1367 end_index = file_diff->hunk_nr;
1369 while (start_index < end_index) {
1370 struct hunk *hunk = file_diff->hunk + start_index++;
1372 strbuf_reset(&s->buf);
1373 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1374 : hunk->use == SKIP_HUNK ? '-' : ' ',
1375 (int)start_index);
1376 summarize_hunk(s, hunk, &s->buf);
1377 fputs(s->buf.buf, stdout);
1380 return end_index;
1383 static const char help_patch_remainder[] =
1384 N_("j - leave this hunk undecided, see next undecided hunk\n"
1385 "J - leave this hunk undecided, see next hunk\n"
1386 "k - leave this hunk undecided, see previous undecided hunk\n"
1387 "K - leave this hunk undecided, see previous hunk\n"
1388 "g - select a hunk to go to\n"
1389 "/ - search for a hunk matching the given regex\n"
1390 "s - split the current hunk into smaller hunks\n"
1391 "e - manually edit the current hunk\n"
1392 "? - print help\n");
1394 static int patch_update_file(struct add_p_state *s,
1395 struct file_diff *file_diff)
1397 size_t hunk_index = 0;
1398 ssize_t i, undecided_previous, undecided_next;
1399 struct hunk *hunk;
1400 char ch;
1401 struct child_process cp = CHILD_PROCESS_INIT;
1402 int colored = !!s->colored.len, quit = 0;
1403 enum prompt_mode_type prompt_mode_type;
1404 enum {
1405 ALLOW_GOTO_PREVIOUS_HUNK = 1 << 0,
1406 ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK = 1 << 1,
1407 ALLOW_GOTO_NEXT_HUNK = 1 << 2,
1408 ALLOW_GOTO_NEXT_UNDECIDED_HUNK = 1 << 3,
1409 ALLOW_SEARCH_AND_GOTO = 1 << 4,
1410 ALLOW_SPLIT = 1 << 5,
1411 ALLOW_EDIT = 1 << 6
1412 } permitted = 0;
1414 /* Empty added files have no hunks */
1415 if (!file_diff->hunk_nr && !file_diff->added)
1416 return 0;
1418 strbuf_reset(&s->buf);
1419 render_diff_header(s, file_diff, colored, &s->buf);
1420 fputs(s->buf.buf, stdout);
1421 for (;;) {
1422 if (hunk_index >= file_diff->hunk_nr)
1423 hunk_index = 0;
1424 hunk = file_diff->hunk_nr
1425 ? file_diff->hunk + hunk_index
1426 : &file_diff->head;
1427 undecided_previous = -1;
1428 undecided_next = -1;
1430 if (file_diff->hunk_nr) {
1431 for (i = hunk_index - 1; i >= 0; i--)
1432 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1433 undecided_previous = i;
1434 break;
1437 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1438 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1439 undecided_next = i;
1440 break;
1444 /* Everything decided? */
1445 if (undecided_previous < 0 && undecided_next < 0 &&
1446 hunk->use != UNDECIDED_HUNK)
1447 break;
1449 strbuf_reset(&s->buf);
1450 if (file_diff->hunk_nr) {
1451 render_hunk(s, hunk, 0, colored, &s->buf);
1452 fputs(s->buf.buf, stdout);
1454 strbuf_reset(&s->buf);
1455 if (undecided_previous >= 0) {
1456 permitted |= ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK;
1457 strbuf_addstr(&s->buf, ",k");
1459 if (hunk_index) {
1460 permitted |= ALLOW_GOTO_PREVIOUS_HUNK;
1461 strbuf_addstr(&s->buf, ",K");
1463 if (undecided_next >= 0) {
1464 permitted |= ALLOW_GOTO_NEXT_UNDECIDED_HUNK;
1465 strbuf_addstr(&s->buf, ",j");
1467 if (hunk_index + 1 < file_diff->hunk_nr) {
1468 permitted |= ALLOW_GOTO_NEXT_HUNK;
1469 strbuf_addstr(&s->buf, ",J");
1471 if (file_diff->hunk_nr > 1) {
1472 permitted |= ALLOW_SEARCH_AND_GOTO;
1473 strbuf_addstr(&s->buf, ",g,/");
1475 if (hunk->splittable_into > 1) {
1476 permitted |= ALLOW_SPLIT;
1477 strbuf_addstr(&s->buf, ",s");
1479 if (hunk_index + 1 > file_diff->mode_change &&
1480 !file_diff->deleted) {
1481 permitted |= ALLOW_EDIT;
1482 strbuf_addstr(&s->buf, ",e");
1485 if (file_diff->deleted)
1486 prompt_mode_type = PROMPT_DELETION;
1487 else if (file_diff->added)
1488 prompt_mode_type = PROMPT_ADDITION;
1489 else if (file_diff->mode_change && !hunk_index)
1490 prompt_mode_type = PROMPT_MODE_CHANGE;
1491 else
1492 prompt_mode_type = PROMPT_HUNK;
1494 printf("%s(%"PRIuMAX"/%"PRIuMAX") ", s->s.prompt_color,
1495 (uintmax_t)hunk_index + 1,
1496 (uintmax_t)(file_diff->hunk_nr
1497 ? file_diff->hunk_nr
1498 : 1));
1499 printf(_(s->mode->prompt_mode[prompt_mode_type]),
1500 s->buf.buf);
1501 if (*s->s.reset_color)
1502 fputs(s->s.reset_color, stdout);
1503 fflush(stdout);
1504 if (read_single_character(s) == EOF)
1505 break;
1507 if (!s->answer.len)
1508 continue;
1509 ch = tolower(s->answer.buf[0]);
1510 if (ch == 'y') {
1511 hunk->use = USE_HUNK;
1512 soft_increment:
1513 hunk_index = undecided_next < 0 ?
1514 file_diff->hunk_nr : undecided_next;
1515 } else if (ch == 'n') {
1516 hunk->use = SKIP_HUNK;
1517 goto soft_increment;
1518 } else if (ch == 'a') {
1519 if (file_diff->hunk_nr) {
1520 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1521 hunk = file_diff->hunk + hunk_index;
1522 if (hunk->use == UNDECIDED_HUNK)
1523 hunk->use = USE_HUNK;
1525 } else if (hunk->use == UNDECIDED_HUNK) {
1526 hunk->use = USE_HUNK;
1528 } else if (ch == 'd' || ch == 'q') {
1529 if (file_diff->hunk_nr) {
1530 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1531 hunk = file_diff->hunk + hunk_index;
1532 if (hunk->use == UNDECIDED_HUNK)
1533 hunk->use = SKIP_HUNK;
1535 } else if (hunk->use == UNDECIDED_HUNK) {
1536 hunk->use = SKIP_HUNK;
1538 if (ch == 'q') {
1539 quit = 1;
1540 break;
1542 } else if (s->answer.buf[0] == 'K') {
1543 if (permitted & ALLOW_GOTO_PREVIOUS_HUNK)
1544 hunk_index--;
1545 else
1546 err(s, _("No previous hunk"));
1547 } else if (s->answer.buf[0] == 'J') {
1548 if (permitted & ALLOW_GOTO_NEXT_HUNK)
1549 hunk_index++;
1550 else
1551 err(s, _("No next hunk"));
1552 } else if (s->answer.buf[0] == 'k') {
1553 if (permitted & ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK)
1554 hunk_index = undecided_previous;
1555 else
1556 err(s, _("No previous hunk"));
1557 } else if (s->answer.buf[0] == 'j') {
1558 if (permitted & ALLOW_GOTO_NEXT_UNDECIDED_HUNK)
1559 hunk_index = undecided_next;
1560 else
1561 err(s, _("No next hunk"));
1562 } else if (s->answer.buf[0] == 'g') {
1563 char *pend;
1564 unsigned long response;
1566 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1567 err(s, _("No other hunks to goto"));
1568 continue;
1570 strbuf_remove(&s->answer, 0, 1);
1571 strbuf_trim(&s->answer);
1572 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1573 if (i < (int)file_diff->mode_change)
1574 i = file_diff->mode_change;
1575 while (s->answer.len == 0) {
1576 i = display_hunks(s, file_diff, i);
1577 printf("%s", i < file_diff->hunk_nr ?
1578 _("go to which hunk (<ret> to see "
1579 "more)? ") : _("go to which hunk? "));
1580 fflush(stdout);
1581 if (strbuf_getline(&s->answer,
1582 stdin) == EOF)
1583 break;
1584 strbuf_trim_trailing_newline(&s->answer);
1587 strbuf_trim(&s->answer);
1588 response = strtoul(s->answer.buf, &pend, 10);
1589 if (*pend || pend == s->answer.buf)
1590 err(s, _("Invalid number: '%s'"),
1591 s->answer.buf);
1592 else if (0 < response && response <= file_diff->hunk_nr)
1593 hunk_index = response - 1;
1594 else
1595 err(s, Q_("Sorry, only %d hunk available.",
1596 "Sorry, only %d hunks available.",
1597 file_diff->hunk_nr),
1598 (int)file_diff->hunk_nr);
1599 } else if (s->answer.buf[0] == '/') {
1600 regex_t regex;
1601 int ret;
1603 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1604 err(s, _("No other hunks to search"));
1605 continue;
1607 strbuf_remove(&s->answer, 0, 1);
1608 strbuf_trim_trailing_newline(&s->answer);
1609 if (s->answer.len == 0) {
1610 printf("%s", _("search for regex? "));
1611 fflush(stdout);
1612 if (strbuf_getline(&s->answer,
1613 stdin) == EOF)
1614 break;
1615 strbuf_trim_trailing_newline(&s->answer);
1616 if (s->answer.len == 0)
1617 continue;
1619 ret = regcomp(&regex, s->answer.buf,
1620 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1621 if (ret) {
1622 char errbuf[1024];
1624 regerror(ret, &regex, errbuf, sizeof(errbuf));
1625 err(s, _("Malformed search regexp %s: %s"),
1626 s->answer.buf, errbuf);
1627 continue;
1629 i = hunk_index;
1630 for (;;) {
1631 /* render the hunk into a scratch buffer */
1632 render_hunk(s, file_diff->hunk + i, 0, 0,
1633 &s->buf);
1634 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1635 != REG_NOMATCH)
1636 break;
1637 i++;
1638 if (i == file_diff->hunk_nr)
1639 i = 0;
1640 if (i != hunk_index)
1641 continue;
1642 err(s, _("No hunk matches the given pattern"));
1643 break;
1645 hunk_index = i;
1646 } else if (s->answer.buf[0] == 's') {
1647 size_t splittable_into = hunk->splittable_into;
1648 if (!(permitted & ALLOW_SPLIT))
1649 err(s, _("Sorry, cannot split this hunk"));
1650 else if (!split_hunk(s, file_diff,
1651 hunk - file_diff->hunk))
1652 color_fprintf_ln(stdout, s->s.header_color,
1653 _("Split into %d hunks."),
1654 (int)splittable_into);
1655 } else if (s->answer.buf[0] == 'e') {
1656 if (!(permitted & ALLOW_EDIT))
1657 err(s, _("Sorry, cannot edit this hunk"));
1658 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1659 hunk->use = USE_HUNK;
1660 goto soft_increment;
1662 } else {
1663 const char *p = _(help_patch_remainder), *eol = p;
1665 color_fprintf(stdout, s->s.help_color, "%s",
1666 _(s->mode->help_patch_text));
1669 * Show only those lines of the remainder that are
1670 * actually applicable with the current hunk.
1672 for (; *p; p = eol + (*eol == '\n')) {
1673 eol = strchrnul(p, '\n');
1676 * `s->buf` still contains the part of the
1677 * commands shown in the prompt that are not
1678 * always available.
1680 if (*p != '?' && !strchr(s->buf.buf, *p))
1681 continue;
1683 color_fprintf_ln(stdout, s->s.help_color,
1684 "%.*s", (int)(eol - p), p);
1689 /* Any hunk to be used? */
1690 for (i = 0; i < file_diff->hunk_nr; i++)
1691 if (file_diff->hunk[i].use == USE_HUNK)
1692 break;
1694 if (i < file_diff->hunk_nr ||
1695 (!file_diff->hunk_nr && file_diff->head.use == USE_HUNK)) {
1696 /* At least one hunk selected: apply */
1697 strbuf_reset(&s->buf);
1698 reassemble_patch(s, file_diff, 0, &s->buf);
1700 discard_index(s->s.r->index);
1701 if (s->mode->apply_for_checkout)
1702 apply_for_checkout(s, &s->buf,
1703 s->mode->is_reverse);
1704 else {
1705 setup_child_process(s, &cp, "apply", NULL);
1706 strvec_pushv(&cp.args, s->mode->apply_args);
1707 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1708 NULL, 0, NULL, 0))
1709 error(_("'git apply' failed"));
1711 if (repo_read_index(s->s.r) >= 0)
1712 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
1713 1, NULL, NULL, NULL);
1716 putchar('\n');
1717 return quit;
1720 int run_add_p(struct repository *r, enum add_p_mode mode,
1721 const char *revision, const struct pathspec *ps)
1723 struct add_p_state s = {
1724 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1726 size_t i, binary_count = 0;
1728 init_add_i_state(&s.s, r);
1730 if (mode == ADD_P_STASH)
1731 s.mode = &patch_mode_stash;
1732 else if (mode == ADD_P_RESET) {
1734 * NEEDSWORK: Instead of comparing to the literal "HEAD",
1735 * compare the commit objects instead so that other ways of
1736 * saying the same thing (such as "@") are also handled
1737 * appropriately.
1739 * This applies to the cases below too.
1741 if (!revision || !strcmp(revision, "HEAD"))
1742 s.mode = &patch_mode_reset_head;
1743 else
1744 s.mode = &patch_mode_reset_nothead;
1745 } else if (mode == ADD_P_CHECKOUT) {
1746 if (!revision)
1747 s.mode = &patch_mode_checkout_index;
1748 else if (!strcmp(revision, "HEAD"))
1749 s.mode = &patch_mode_checkout_head;
1750 else
1751 s.mode = &patch_mode_checkout_nothead;
1752 } else if (mode == ADD_P_WORKTREE) {
1753 if (!revision)
1754 s.mode = &patch_mode_checkout_index;
1755 else if (!strcmp(revision, "HEAD"))
1756 s.mode = &patch_mode_worktree_head;
1757 else
1758 s.mode = &patch_mode_worktree_nothead;
1759 } else
1760 s.mode = &patch_mode_add;
1761 s.revision = revision;
1763 discard_index(r->index);
1764 if (repo_read_index(r) < 0 ||
1765 (!s.mode->index_only &&
1766 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1767 NULL, NULL, NULL) < 0) ||
1768 parse_diff(&s, ps) < 0) {
1769 add_p_state_clear(&s);
1770 return -1;
1773 for (i = 0; i < s.file_diff_nr; i++)
1774 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1775 binary_count++;
1776 else if (patch_update_file(&s, s.file_diff + i))
1777 break;
1779 if (s.file_diff_nr == 0)
1780 fprintf(stderr, _("No changes.\n"));
1781 else if (binary_count == s.file_diff_nr)
1782 fprintf(stderr, _("Only binary files changed.\n"));
1784 add_p_state_clear(&s);
1785 return 0;