treewide: be explicit about dependence on oid-array.h
[alt-git.git] / add-patch.c
blobb381f14a7de525d296af3d10871281dd80e5761d
1 #include "cache.h"
2 #include "add-interactive.h"
3 #include "advice.h"
4 #include "alloc.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "strbuf.h"
8 #include "run-command.h"
9 #include "strvec.h"
10 #include "pathspec.h"
11 #include "color.h"
12 #include "diff.h"
13 #include "compat/terminal.h"
14 #include "prompt.h"
16 enum prompt_mode_type {
17 PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_ADDITION, PROMPT_HUNK,
18 PROMPT_MODE_MAX, /* must be last */
21 struct patch_mode {
23 * The magic constant 4 is chosen such that all patch modes
24 * provide enough space for three command-line arguments followed by a
25 * trailing `NULL`.
27 const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
28 unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
29 const char *prompt_mode[PROMPT_MODE_MAX];
30 const char *edit_hunk_hint, *help_patch_text;
33 static struct patch_mode patch_mode_add = {
34 .diff_cmd = { "diff-files", NULL },
35 .apply_args = { "--cached", NULL },
36 .apply_check_args = { "--cached", NULL },
37 .prompt_mode = {
38 N_("Stage mode change [y,n,q,a,d%s,?]? "),
39 N_("Stage deletion [y,n,q,a,d%s,?]? "),
40 N_("Stage addition [y,n,q,a,d%s,?]? "),
41 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
43 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
44 "will immediately be marked for staging."),
45 .help_patch_text =
46 N_("y - stage this hunk\n"
47 "n - do not stage this hunk\n"
48 "q - quit; do not stage this hunk or any of the remaining "
49 "ones\n"
50 "a - stage this hunk and all later hunks in the file\n"
51 "d - do not stage this hunk or any of the later hunks in "
52 "the file\n")
55 static struct patch_mode patch_mode_stash = {
56 .diff_cmd = { "diff-index", "HEAD", NULL },
57 .apply_args = { "--cached", NULL },
58 .apply_check_args = { "--cached", NULL },
59 .prompt_mode = {
60 N_("Stash mode change [y,n,q,a,d%s,?]? "),
61 N_("Stash deletion [y,n,q,a,d%s,?]? "),
62 N_("Stash addition [y,n,q,a,d%s,?]? "),
63 N_("Stash this hunk [y,n,q,a,d%s,?]? "),
65 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
66 "will immediately be marked for stashing."),
67 .help_patch_text =
68 N_("y - stash this hunk\n"
69 "n - do not stash this hunk\n"
70 "q - quit; do not stash this hunk or any of the remaining "
71 "ones\n"
72 "a - stash this hunk and all later hunks in the file\n"
73 "d - do not stash this hunk or any of the later hunks in "
74 "the file\n"),
77 static struct patch_mode patch_mode_reset_head = {
78 .diff_cmd = { "diff-index", "--cached", NULL },
79 .apply_args = { "-R", "--cached", NULL },
80 .apply_check_args = { "-R", "--cached", NULL },
81 .is_reverse = 1,
82 .index_only = 1,
83 .prompt_mode = {
84 N_("Unstage mode change [y,n,q,a,d%s,?]? "),
85 N_("Unstage deletion [y,n,q,a,d%s,?]? "),
86 N_("Unstage addition [y,n,q,a,d%s,?]? "),
87 N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
89 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
90 "will immediately be marked for unstaging."),
91 .help_patch_text =
92 N_("y - unstage this hunk\n"
93 "n - do not unstage this hunk\n"
94 "q - quit; do not unstage this hunk or any of the remaining "
95 "ones\n"
96 "a - unstage this hunk and all later hunks in the file\n"
97 "d - do not unstage this hunk or any of the later hunks in "
98 "the file\n"),
101 static struct patch_mode patch_mode_reset_nothead = {
102 .diff_cmd = { "diff-index", "-R", "--cached", NULL },
103 .apply_args = { "--cached", NULL },
104 .apply_check_args = { "--cached", NULL },
105 .index_only = 1,
106 .prompt_mode = {
107 N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
108 N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
109 N_("Apply addition to index [y,n,q,a,d%s,?]? "),
110 N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
112 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
113 "will immediately be marked for applying."),
114 .help_patch_text =
115 N_("y - apply this hunk to index\n"
116 "n - do not apply this hunk to index\n"
117 "q - quit; do not apply this hunk or any of the remaining "
118 "ones\n"
119 "a - apply this hunk and all later hunks in the file\n"
120 "d - do not apply this hunk or any of the later hunks in "
121 "the file\n"),
124 static struct patch_mode patch_mode_checkout_index = {
125 .diff_cmd = { "diff-files", NULL },
126 .apply_args = { "-R", NULL },
127 .apply_check_args = { "-R", NULL },
128 .is_reverse = 1,
129 .prompt_mode = {
130 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
131 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
132 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
133 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
135 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
136 "will immediately be marked for discarding."),
137 .help_patch_text =
138 N_("y - discard this hunk from worktree\n"
139 "n - do not discard this hunk from worktree\n"
140 "q - quit; do not discard this hunk or any of the remaining "
141 "ones\n"
142 "a - discard this hunk and all later hunks in the file\n"
143 "d - do not discard this hunk or any of the later hunks in "
144 "the file\n"),
147 static struct patch_mode patch_mode_checkout_head = {
148 .diff_cmd = { "diff-index", NULL },
149 .apply_for_checkout = 1,
150 .apply_check_args = { "-R", NULL },
151 .is_reverse = 1,
152 .prompt_mode = {
153 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
154 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
155 N_("Discard addition from index and worktree [y,n,q,a,d%s,?]? "),
156 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
158 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
159 "will immediately be marked for discarding."),
160 .help_patch_text =
161 N_("y - discard this hunk from index and worktree\n"
162 "n - do not discard this hunk from index and worktree\n"
163 "q - quit; do not discard this hunk or any of the remaining "
164 "ones\n"
165 "a - discard this hunk and all later hunks in the file\n"
166 "d - do not discard this hunk or any of the later hunks in "
167 "the file\n"),
170 static struct patch_mode patch_mode_checkout_nothead = {
171 .diff_cmd = { "diff-index", "-R", NULL },
172 .apply_for_checkout = 1,
173 .apply_check_args = { NULL },
174 .prompt_mode = {
175 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
176 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
177 N_("Apply addition to index and worktree [y,n,q,a,d%s,?]? "),
178 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
180 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
181 "will immediately be marked for applying."),
182 .help_patch_text =
183 N_("y - apply this hunk to index and worktree\n"
184 "n - do not apply this hunk to index and worktree\n"
185 "q - quit; do not apply this hunk or any of the remaining "
186 "ones\n"
187 "a - apply this hunk and all later hunks in the file\n"
188 "d - do not apply this hunk or any of the later hunks in "
189 "the file\n"),
192 static struct patch_mode patch_mode_worktree_head = {
193 .diff_cmd = { "diff-index", NULL },
194 .apply_args = { "-R", NULL },
195 .apply_check_args = { "-R", NULL },
196 .is_reverse = 1,
197 .prompt_mode = {
198 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
199 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
200 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
201 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
203 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
204 "will immediately be marked for discarding."),
205 .help_patch_text =
206 N_("y - discard this hunk from worktree\n"
207 "n - do not discard this hunk from worktree\n"
208 "q - quit; do not discard this hunk or any of the remaining "
209 "ones\n"
210 "a - discard this hunk and all later hunks in the file\n"
211 "d - do not discard this hunk or any of the later hunks in "
212 "the file\n"),
215 static struct patch_mode patch_mode_worktree_nothead = {
216 .diff_cmd = { "diff-index", "-R", NULL },
217 .apply_args = { NULL },
218 .apply_check_args = { NULL },
219 .prompt_mode = {
220 N_("Apply mode change to worktree [y,n,q,a,d%s,?]? "),
221 N_("Apply deletion to worktree [y,n,q,a,d%s,?]? "),
222 N_("Apply addition to worktree [y,n,q,a,d%s,?]? "),
223 N_("Apply this hunk to worktree [y,n,q,a,d%s,?]? "),
225 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
226 "will immediately be marked for applying."),
227 .help_patch_text =
228 N_("y - apply this hunk to worktree\n"
229 "n - do not apply this hunk to worktree\n"
230 "q - quit; do not apply this hunk or any of the remaining "
231 "ones\n"
232 "a - apply this hunk and all later hunks in the file\n"
233 "d - do not apply this hunk or any of the later hunks in "
234 "the file\n"),
237 struct hunk_header {
238 unsigned long old_offset, old_count, new_offset, new_count;
240 * Start/end offsets to the extra text after the second `@@` in the
241 * hunk header, e.g. the function signature. This is expected to
242 * include the newline.
244 size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
245 unsigned suppress_colored_line_range:1;
248 struct hunk {
249 size_t start, end, colored_start, colored_end, splittable_into;
250 ssize_t delta;
251 enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
252 struct hunk_header header;
255 struct add_p_state {
256 struct add_i_state s;
257 struct strbuf answer, buf;
259 /* parsed diff */
260 struct strbuf plain, colored;
261 struct file_diff {
262 struct hunk head;
263 struct hunk *hunk;
264 size_t hunk_nr, hunk_alloc;
265 unsigned deleted:1, added:1, mode_change:1,binary:1;
266 } *file_diff;
267 size_t file_diff_nr;
269 /* patch mode */
270 struct patch_mode *mode;
271 const char *revision;
274 static void add_p_state_clear(struct add_p_state *s)
276 size_t i;
278 strbuf_release(&s->answer);
279 strbuf_release(&s->buf);
280 strbuf_release(&s->plain);
281 strbuf_release(&s->colored);
282 for (i = 0; i < s->file_diff_nr; i++)
283 free(s->file_diff[i].hunk);
284 free(s->file_diff);
285 clear_add_i_state(&s->s);
288 __attribute__((format (printf, 2, 3)))
289 static void err(struct add_p_state *s, const char *fmt, ...)
291 va_list args;
293 va_start(args, fmt);
294 fputs(s->s.error_color, stderr);
295 vfprintf(stderr, fmt, args);
296 fputs(s->s.reset_color, stderr);
297 fputc('\n', stderr);
298 va_end(args);
301 static void setup_child_process(struct add_p_state *s,
302 struct child_process *cp, ...)
304 va_list ap;
305 const char *arg;
307 va_start(ap, cp);
308 while ((arg = va_arg(ap, const char *)))
309 strvec_push(&cp->args, arg);
310 va_end(ap);
312 cp->git_cmd = 1;
313 strvec_pushf(&cp->env,
314 INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
317 static int parse_range(const char **p,
318 unsigned long *offset, unsigned long *count)
320 char *pend;
322 *offset = strtoul(*p, &pend, 10);
323 if (pend == *p)
324 return -1;
325 if (*pend != ',') {
326 *count = 1;
327 *p = pend;
328 return 0;
330 *count = strtoul(pend + 1, (char **)p, 10);
331 return *p == pend + 1 ? -1 : 0;
334 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
336 struct hunk_header *header = &hunk->header;
337 const char *line = s->plain.buf + hunk->start, *p = line;
338 char *eol = memchr(p, '\n', s->plain.len - hunk->start);
340 if (!eol)
341 eol = s->plain.buf + s->plain.len;
343 if (!skip_prefix(p, "@@ -", &p) ||
344 parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
345 !skip_prefix(p, " +", &p) ||
346 parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
347 !skip_prefix(p, " @@", &p))
348 return error(_("could not parse hunk header '%.*s'"),
349 (int)(eol - line), line);
351 hunk->start = eol - s->plain.buf + (*eol == '\n');
352 header->extra_start = p - s->plain.buf;
353 header->extra_end = hunk->start;
355 if (!s->colored.len) {
356 header->colored_extra_start = header->colored_extra_end = 0;
357 return 0;
360 /* Now find the extra text in the colored diff */
361 line = s->colored.buf + hunk->colored_start;
362 eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
363 if (!eol)
364 eol = s->colored.buf + s->colored.len;
365 p = memmem(line, eol - line, "@@ -", 4);
366 if (p && (p = memmem(p + 4, eol - p - 4, " @@", 3))) {
367 header->colored_extra_start = p + 3 - s->colored.buf;
368 } else {
369 /* could not parse colored hunk header, leave as-is */
370 header->colored_extra_start = hunk->colored_start;
371 header->suppress_colored_line_range = 1;
373 hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
374 header->colored_extra_end = hunk->colored_start;
376 return 0;
379 static int is_octal(const char *p, size_t len)
381 if (!len)
382 return 0;
384 while (len--)
385 if (*p < '0' || *(p++) > '7')
386 return 0;
387 return 1;
390 static void complete_file(char marker, struct hunk *hunk)
392 if (marker == '-' || marker == '+')
394 * Last hunk ended in non-context line (i.e. it
395 * appended lines to the file, so there are no
396 * trailing context lines).
398 hunk->splittable_into++;
401 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
403 struct strvec args = STRVEC_INIT;
404 const char *diff_algorithm = s->s.interactive_diff_algorithm;
405 struct strbuf *plain = &s->plain, *colored = NULL;
406 struct child_process cp = CHILD_PROCESS_INIT;
407 char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
408 size_t file_diff_alloc = 0, i, color_arg_index;
409 struct file_diff *file_diff = NULL;
410 struct hunk *hunk = NULL;
411 int res;
413 strvec_pushv(&args, s->mode->diff_cmd);
414 if (diff_algorithm)
415 strvec_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
416 if (s->revision) {
417 struct object_id oid;
418 strvec_push(&args,
419 /* could be on an unborn branch */
420 !strcmp("HEAD", s->revision) &&
421 repo_get_oid(the_repository, "HEAD", &oid) ?
422 empty_tree_oid_hex() : s->revision);
424 color_arg_index = args.nr;
425 /* Use `--no-color` explicitly, just in case `diff.color = always`. */
426 strvec_pushl(&args, "--no-color", "--ignore-submodules=dirty", "-p",
427 "--", NULL);
428 for (i = 0; i < ps->nr; i++)
429 strvec_push(&args, ps->items[i].original);
431 setup_child_process(s, &cp, NULL);
432 strvec_pushv(&cp.args, args.v);
433 res = capture_command(&cp, plain, 0);
434 if (res) {
435 strvec_clear(&args);
436 return error(_("could not parse diff"));
438 if (!plain->len) {
439 strvec_clear(&args);
440 return 0;
442 strbuf_complete_line(plain);
444 if (want_color_fd(1, -1)) {
445 struct child_process colored_cp = CHILD_PROCESS_INIT;
446 const char *diff_filter = s->s.interactive_diff_filter;
448 setup_child_process(s, &colored_cp, NULL);
449 xsnprintf((char *)args.v[color_arg_index], 8, "--color");
450 strvec_pushv(&colored_cp.args, args.v);
451 colored = &s->colored;
452 res = capture_command(&colored_cp, colored, 0);
453 strvec_clear(&args);
454 if (res)
455 return error(_("could not parse colored diff"));
457 if (diff_filter) {
458 struct child_process filter_cp = CHILD_PROCESS_INIT;
460 setup_child_process(s, &filter_cp,
461 diff_filter, NULL);
462 filter_cp.git_cmd = 0;
463 filter_cp.use_shell = 1;
464 strbuf_reset(&s->buf);
465 if (pipe_command(&filter_cp,
466 colored->buf, colored->len,
467 &s->buf, colored->len,
468 NULL, 0) < 0)
469 return error(_("failed to run '%s'"),
470 diff_filter);
471 strbuf_swap(colored, &s->buf);
474 strbuf_complete_line(colored);
475 colored_p = colored->buf;
476 colored_pend = colored_p + colored->len;
478 strvec_clear(&args);
480 /* parse files and hunks */
481 p = plain->buf;
482 pend = p + plain->len;
483 while (p != pend) {
484 char *eol = memchr(p, '\n', pend - p);
485 const char *deleted = NULL, *mode_change = NULL;
487 if (!eol)
488 eol = pend;
490 if (starts_with(p, "diff ") ||
491 starts_with(p, "* Unmerged path ")) {
492 complete_file(marker, hunk);
493 ALLOC_GROW_BY(s->file_diff, s->file_diff_nr, 1,
494 file_diff_alloc);
495 file_diff = s->file_diff + s->file_diff_nr - 1;
496 hunk = &file_diff->head;
497 hunk->start = p - plain->buf;
498 if (colored_p)
499 hunk->colored_start = colored_p - colored->buf;
500 marker = '\0';
501 } else if (p == plain->buf)
502 BUG("diff starts with unexpected line:\n"
503 "%.*s\n", (int)(eol - p), p);
504 else if (file_diff->deleted)
505 ; /* keep the rest of the file in a single "hunk" */
506 else if (starts_with(p, "@@ ") ||
507 (hunk == &file_diff->head &&
508 (skip_prefix(p, "deleted file", &deleted)))) {
509 if (marker == '-' || marker == '+')
511 * Should not happen; previous hunk did not end
512 * in a context line? Handle it anyway.
514 hunk->splittable_into++;
516 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
517 file_diff->hunk_alloc);
518 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
520 hunk->start = p - plain->buf;
521 if (colored)
522 hunk->colored_start = colored_p - colored->buf;
524 if (deleted)
525 file_diff->deleted = 1;
526 else if (parse_hunk_header(s, hunk) < 0)
527 return -1;
530 * Start counting into how many hunks this one can be
531 * split
533 marker = *p;
534 } else if (hunk == &file_diff->head &&
535 starts_with(p, "new file")) {
536 file_diff->added = 1;
537 } else if (hunk == &file_diff->head &&
538 skip_prefix(p, "old mode ", &mode_change) &&
539 is_octal(mode_change, eol - mode_change)) {
540 if (file_diff->mode_change)
541 BUG("double mode change?\n\n%.*s",
542 (int)(eol - plain->buf), plain->buf);
543 if (file_diff->hunk_nr)
544 BUG("mode change in the middle?\n\n%.*s",
545 (int)(eol - plain->buf), plain->buf);
548 * Do *not* change `hunk`: the mode change pseudo-hunk
549 * is _part of_ the header "hunk".
551 file_diff->mode_change = 1;
552 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
553 file_diff->hunk_alloc);
554 file_diff->hunk->start = p - plain->buf;
555 if (colored_p)
556 file_diff->hunk->colored_start =
557 colored_p - colored->buf;
558 } else if (hunk == &file_diff->head &&
559 skip_prefix(p, "new mode ", &mode_change) &&
560 is_octal(mode_change, eol - mode_change)) {
563 * Extend the "mode change" pseudo-hunk to include also
564 * the "new mode" line.
566 if (!file_diff->mode_change)
567 BUG("'new mode' without 'old mode'?\n\n%.*s",
568 (int)(eol - plain->buf), plain->buf);
569 if (file_diff->hunk_nr != 1)
570 BUG("mode change in the middle?\n\n%.*s",
571 (int)(eol - plain->buf), plain->buf);
572 if (p - plain->buf != file_diff->hunk->end)
573 BUG("'new mode' does not immediately follow "
574 "'old mode'?\n\n%.*s",
575 (int)(eol - plain->buf), plain->buf);
576 } else if (hunk == &file_diff->head &&
577 starts_with(p, "Binary files "))
578 file_diff->binary = 1;
580 if (!!file_diff->deleted + !!file_diff->added +
581 !!file_diff->mode_change > 1)
582 BUG("diff can only contain delete *or* add *or* a "
583 "mode change?!?\n%.*s",
584 (int)(eol - (plain->buf + file_diff->head.start)),
585 plain->buf + file_diff->head.start);
587 if ((marker == '-' || marker == '+') && *p == ' ')
588 hunk->splittable_into++;
589 if (marker && *p != '\\')
590 marker = *p;
592 p = eol == pend ? pend : eol + 1;
593 hunk->end = p - plain->buf;
595 if (colored) {
596 char *colored_eol = memchr(colored_p, '\n',
597 colored_pend - colored_p);
598 if (colored_eol)
599 colored_p = colored_eol + 1;
600 else if (p != pend)
601 /* non-colored has more lines? */
602 goto mismatched_output;
603 else if (colored_p == colored_pend)
604 /* last line has no matching colored one? */
605 goto mismatched_output;
606 else
607 colored_p = colored_pend;
609 hunk->colored_end = colored_p - colored->buf;
612 if (mode_change) {
613 if (file_diff->hunk_nr != 1)
614 BUG("mode change in hunk #%d???",
615 (int)file_diff->hunk_nr);
616 /* Adjust the end of the "mode change" pseudo-hunk */
617 file_diff->hunk->end = hunk->end;
618 if (colored)
619 file_diff->hunk->colored_end = hunk->colored_end;
622 complete_file(marker, hunk);
624 /* non-colored shorter than colored? */
625 if (colored_p != colored_pend) {
626 mismatched_output:
627 error(_("mismatched output from interactive.diffFilter"));
628 advise(_("Your filter must maintain a one-to-one correspondence\n"
629 "between its input and output lines."));
630 return -1;
633 return 0;
636 static size_t find_next_line(struct strbuf *sb, size_t offset)
638 char *eol;
640 if (offset >= sb->len)
641 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
642 (int)offset, (int)sb->len, sb->buf);
644 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
645 if (!eol)
646 return sb->len;
647 return eol - sb->buf + 1;
650 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
651 ssize_t delta, int colored, struct strbuf *out)
653 struct hunk_header *header = &hunk->header;
655 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
657 * Generate the hunk header dynamically, except for special
658 * hunks (such as the diff header).
660 const char *p;
661 size_t len;
662 unsigned long old_offset = header->old_offset;
663 unsigned long new_offset = header->new_offset;
665 if (!colored) {
666 p = s->plain.buf + header->extra_start;
667 len = header->extra_end - header->extra_start;
668 } else if (header->suppress_colored_line_range) {
669 strbuf_add(out,
670 s->colored.buf + header->colored_extra_start,
671 header->colored_extra_end -
672 header->colored_extra_start);
674 strbuf_add(out, s->colored.buf + hunk->colored_start,
675 hunk->colored_end - hunk->colored_start);
676 return;
677 } else {
678 strbuf_addstr(out, s->s.fraginfo_color);
679 p = s->colored.buf + header->colored_extra_start;
680 len = header->colored_extra_end
681 - header->colored_extra_start;
684 if (s->mode->is_reverse)
685 old_offset -= delta;
686 else
687 new_offset += delta;
689 strbuf_addf(out, "@@ -%lu", old_offset);
690 if (header->old_count != 1)
691 strbuf_addf(out, ",%lu", header->old_count);
692 strbuf_addf(out, " +%lu", new_offset);
693 if (header->new_count != 1)
694 strbuf_addf(out, ",%lu", header->new_count);
695 strbuf_addstr(out, " @@");
697 if (len)
698 strbuf_add(out, p, len);
699 else if (colored)
700 strbuf_addf(out, "%s\n", s->s.reset_color);
701 else
702 strbuf_addch(out, '\n');
705 if (colored)
706 strbuf_add(out, s->colored.buf + hunk->colored_start,
707 hunk->colored_end - hunk->colored_start);
708 else
709 strbuf_add(out, s->plain.buf + hunk->start,
710 hunk->end - hunk->start);
713 static void render_diff_header(struct add_p_state *s,
714 struct file_diff *file_diff, int colored,
715 struct strbuf *out)
718 * If there was a mode change, the first hunk is a pseudo hunk that
719 * corresponds to the mode line in the header. If the user did not want
720 * to stage that "hunk", we actually have to cut it out from the header.
722 int skip_mode_change =
723 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
724 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
726 if (!skip_mode_change) {
727 render_hunk(s, head, 0, colored, out);
728 return;
731 if (colored) {
732 const char *p = s->colored.buf;
734 strbuf_add(out, p + head->colored_start,
735 first->colored_start - head->colored_start);
736 strbuf_add(out, p + first->colored_end,
737 head->colored_end - first->colored_end);
738 } else {
739 const char *p = s->plain.buf;
741 strbuf_add(out, p + head->start, first->start - head->start);
742 strbuf_add(out, p + first->end, head->end - first->end);
746 /* Coalesce hunks again that were split */
747 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
748 size_t *hunk_index, int use_all, struct hunk *merged)
750 size_t i = *hunk_index, delta;
751 struct hunk *hunk = file_diff->hunk + i;
752 /* `header` corresponds to the merged hunk */
753 struct hunk_header *header = &merged->header, *next;
755 if (!use_all && hunk->use != USE_HUNK)
756 return 0;
758 *merged = *hunk;
759 /* We simply skip the colored part (if any) when merging hunks */
760 merged->colored_start = merged->colored_end = 0;
762 for (; i + 1 < file_diff->hunk_nr; i++) {
763 hunk++;
764 next = &hunk->header;
767 * Stop merging hunks when:
769 * - the hunk is not selected for use, or
770 * - the hunk does not overlap with the already-merged hunk(s)
772 if ((!use_all && hunk->use != USE_HUNK) ||
773 header->new_offset >= next->new_offset + merged->delta ||
774 header->new_offset + header->new_count
775 < next->new_offset + merged->delta)
776 break;
779 * If the hunks were not edited, and overlap, we can simply
780 * extend the line range.
782 if (merged->start < hunk->start && merged->end > hunk->start) {
783 merged->end = hunk->end;
784 merged->colored_end = hunk->colored_end;
785 delta = 0;
786 } else {
787 const char *plain = s->plain.buf;
788 size_t overlapping_line_count = header->new_offset
789 + header->new_count - merged->delta
790 - next->new_offset;
791 size_t overlap_end = hunk->start;
792 size_t overlap_start = overlap_end;
793 size_t overlap_next, len, j;
796 * One of the hunks was edited: the modified hunk was
797 * appended to the strbuf `s->plain`.
799 * Let's ensure that at least the last context line of
800 * the first hunk overlaps with the corresponding line
801 * of the second hunk, and then merge.
803 for (j = 0; j < overlapping_line_count; j++) {
804 overlap_next = find_next_line(&s->plain,
805 overlap_end);
807 if (overlap_next > hunk->end)
808 BUG("failed to find %d context lines "
809 "in:\n%.*s",
810 (int)overlapping_line_count,
811 (int)(hunk->end - hunk->start),
812 plain + hunk->start);
814 if (plain[overlap_end] != ' ')
815 return error(_("expected context line "
816 "#%d in\n%.*s"),
817 (int)(j + 1),
818 (int)(hunk->end
819 - hunk->start),
820 plain + hunk->start);
822 overlap_start = overlap_end;
823 overlap_end = overlap_next;
825 len = overlap_end - overlap_start;
827 if (len > merged->end - merged->start ||
828 memcmp(plain + merged->end - len,
829 plain + overlap_start, len))
830 return error(_("hunks do not overlap:\n%.*s\n"
831 "\tdoes not end with:\n%.*s"),
832 (int)(merged->end - merged->start),
833 plain + merged->start,
834 (int)len, plain + overlap_start);
837 * Since the start-end ranges are not adjacent, we
838 * cannot simply take the union of the ranges. To
839 * address that, we temporarily append the union of the
840 * lines to the `plain` strbuf.
842 if (merged->end != s->plain.len) {
843 size_t start = s->plain.len;
845 strbuf_add(&s->plain, plain + merged->start,
846 merged->end - merged->start);
847 plain = s->plain.buf;
848 merged->start = start;
849 merged->end = s->plain.len;
852 strbuf_add(&s->plain,
853 plain + overlap_end,
854 hunk->end - overlap_end);
855 merged->end = s->plain.len;
856 merged->splittable_into += hunk->splittable_into;
857 delta = merged->delta;
858 merged->delta += hunk->delta;
861 header->old_count = next->old_offset + next->old_count
862 - header->old_offset;
863 header->new_count = next->new_offset + delta
864 + next->new_count - header->new_offset;
867 if (i == *hunk_index)
868 return 0;
870 *hunk_index = i;
871 return 1;
874 static void reassemble_patch(struct add_p_state *s,
875 struct file_diff *file_diff, int use_all,
876 struct strbuf *out)
878 struct hunk *hunk;
879 size_t save_len = s->plain.len, i;
880 ssize_t delta = 0;
882 render_diff_header(s, file_diff, 0, out);
884 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
885 struct hunk merged = { 0 };
887 hunk = file_diff->hunk + i;
888 if (!use_all && hunk->use != USE_HUNK)
889 delta += hunk->header.old_count
890 - hunk->header.new_count;
891 else {
892 /* merge overlapping hunks into a temporary hunk */
893 if (merge_hunks(s, file_diff, &i, use_all, &merged))
894 hunk = &merged;
896 render_hunk(s, hunk, delta, 0, out);
899 * In case `merge_hunks()` used `plain` as a scratch
900 * pad (this happens when an edited hunk had to be
901 * coalesced with another hunk).
903 strbuf_setlen(&s->plain, save_len);
905 delta += hunk->delta;
910 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
911 size_t hunk_index)
913 int colored = !!s->colored.len, first = 1;
914 struct hunk *hunk = file_diff->hunk + hunk_index;
915 size_t splittable_into;
916 size_t end, colored_end, current, colored_current = 0, context_line_count;
917 struct hunk_header remaining, *header;
918 char marker, ch;
920 if (hunk_index >= file_diff->hunk_nr)
921 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
922 (int)hunk_index, (int)file_diff->hunk_nr);
924 if (hunk->splittable_into < 2)
925 return 0;
926 splittable_into = hunk->splittable_into;
928 end = hunk->end;
929 colored_end = hunk->colored_end;
931 remaining = hunk->header;
933 file_diff->hunk_nr += splittable_into - 1;
934 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
935 if (hunk_index + splittable_into < file_diff->hunk_nr)
936 memmove(file_diff->hunk + hunk_index + splittable_into,
937 file_diff->hunk + hunk_index + 1,
938 (file_diff->hunk_nr - hunk_index - splittable_into)
939 * sizeof(*hunk));
940 hunk = file_diff->hunk + hunk_index;
941 hunk->splittable_into = 1;
942 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
944 header = &hunk->header;
945 header->old_count = header->new_count = 0;
947 current = hunk->start;
948 if (colored)
949 colored_current = hunk->colored_start;
950 marker = '\0';
951 context_line_count = 0;
953 while (splittable_into > 1) {
954 ch = s->plain.buf[current];
956 if (!ch)
957 BUG("buffer overrun while splitting hunks");
960 * Is this the first context line after a chain of +/- lines?
961 * Then record the start of the next split hunk.
963 if ((marker == '-' || marker == '+') && ch == ' ') {
964 first = 0;
965 hunk[1].start = current;
966 if (colored)
967 hunk[1].colored_start = colored_current;
968 context_line_count = 0;
972 * Was the previous line a +/- one? Alternatively, is this the
973 * first line (and not a +/- one)?
975 * Then just increment the appropriate counter and continue
976 * with the next line.
978 if (marker != ' ' || (ch != '-' && ch != '+')) {
979 next_hunk_line:
980 /* Comment lines are attached to the previous line */
981 if (ch == '\\')
982 ch = marker ? marker : ' ';
984 /* current hunk not done yet */
985 if (ch == ' ')
986 context_line_count++;
987 else if (ch == '-')
988 header->old_count++;
989 else if (ch == '+')
990 header->new_count++;
991 else
992 BUG("unhandled diff marker: '%c'", ch);
993 marker = ch;
994 current = find_next_line(&s->plain, current);
995 if (colored)
996 colored_current =
997 find_next_line(&s->colored,
998 colored_current);
999 continue;
1003 * We got us the start of a new hunk!
1005 * This is a context line, so it is shared with the previous
1006 * hunk, if any.
1009 if (first) {
1010 if (header->old_count || header->new_count)
1011 BUG("counts are off: %d/%d",
1012 (int)header->old_count,
1013 (int)header->new_count);
1015 header->old_count = context_line_count;
1016 header->new_count = context_line_count;
1017 context_line_count = 0;
1018 first = 0;
1019 goto next_hunk_line;
1022 remaining.old_offset += header->old_count;
1023 remaining.old_count -= header->old_count;
1024 remaining.new_offset += header->new_count;
1025 remaining.new_count -= header->new_count;
1027 /* initialize next hunk header's offsets */
1028 hunk[1].header.old_offset =
1029 header->old_offset + header->old_count;
1030 hunk[1].header.new_offset =
1031 header->new_offset + header->new_count;
1033 /* add one split hunk */
1034 header->old_count += context_line_count;
1035 header->new_count += context_line_count;
1037 hunk->end = current;
1038 if (colored)
1039 hunk->colored_end = colored_current;
1041 hunk++;
1042 hunk->splittable_into = 1;
1043 hunk->use = hunk[-1].use;
1044 header = &hunk->header;
1046 header->old_count = header->new_count = context_line_count;
1047 context_line_count = 0;
1049 splittable_into--;
1050 marker = ch;
1053 /* last hunk simply gets the rest */
1054 if (header->old_offset != remaining.old_offset)
1055 BUG("miscounted old_offset: %lu != %lu",
1056 header->old_offset, remaining.old_offset);
1057 if (header->new_offset != remaining.new_offset)
1058 BUG("miscounted new_offset: %lu != %lu",
1059 header->new_offset, remaining.new_offset);
1060 header->old_count = remaining.old_count;
1061 header->new_count = remaining.new_count;
1062 hunk->end = end;
1063 if (colored)
1064 hunk->colored_end = colored_end;
1066 return 0;
1069 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1071 const char *plain = s->plain.buf;
1072 size_t current, eol, next;
1074 if (!s->colored.len)
1075 return;
1077 hunk->colored_start = s->colored.len;
1078 for (current = hunk->start; current < hunk->end; ) {
1079 for (eol = current; eol < hunk->end; eol++)
1080 if (plain[eol] == '\n')
1081 break;
1082 next = eol + (eol < hunk->end);
1083 if (eol > current && plain[eol - 1] == '\r')
1084 eol--;
1086 strbuf_addstr(&s->colored,
1087 plain[current] == '-' ?
1088 s->s.file_old_color :
1089 plain[current] == '+' ?
1090 s->s.file_new_color :
1091 s->s.context_color);
1092 strbuf_add(&s->colored, plain + current, eol - current);
1093 strbuf_addstr(&s->colored, s->s.reset_color);
1094 if (next > eol)
1095 strbuf_add(&s->colored, plain + eol, next - eol);
1096 current = next;
1098 hunk->colored_end = s->colored.len;
1101 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1103 size_t i;
1105 strbuf_reset(&s->buf);
1106 strbuf_commented_addf(&s->buf, _("Manual hunk edit mode -- see bottom for "
1107 "a quick guide.\n"));
1108 render_hunk(s, hunk, 0, 0, &s->buf);
1109 strbuf_commented_addf(&s->buf,
1110 _("---\n"
1111 "To remove '%c' lines, make them ' ' lines "
1112 "(context).\n"
1113 "To remove '%c' lines, delete them.\n"
1114 "Lines starting with %c will be removed.\n"),
1115 s->mode->is_reverse ? '+' : '-',
1116 s->mode->is_reverse ? '-' : '+',
1117 comment_line_char);
1118 strbuf_commented_addf(&s->buf, "%s", _(s->mode->edit_hunk_hint));
1120 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1121 * messages.
1123 strbuf_commented_addf(&s->buf,
1124 _("If it does not apply cleanly, you will be "
1125 "given an opportunity to\n"
1126 "edit again. If all lines of the hunk are "
1127 "removed, then the edit is\n"
1128 "aborted and the hunk is left unchanged.\n"));
1130 if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1131 return -1;
1133 /* strip out commented lines */
1134 hunk->start = s->plain.len;
1135 for (i = 0; i < s->buf.len; ) {
1136 size_t next = find_next_line(&s->buf, i);
1138 if (s->buf.buf[i] != comment_line_char)
1139 strbuf_add(&s->plain, s->buf.buf + i, next - i);
1140 i = next;
1143 hunk->end = s->plain.len;
1144 if (hunk->end == hunk->start)
1145 /* The user aborted editing by deleting everything */
1146 return 0;
1148 recolor_hunk(s, hunk);
1151 * If the hunk header is intact, parse it, otherwise simply use the
1152 * hunk header prior to editing (which will adjust `hunk->start` to
1153 * skip the hunk header).
1155 if (s->plain.buf[hunk->start] == '@' &&
1156 parse_hunk_header(s, hunk) < 0)
1157 return error(_("could not parse hunk header"));
1159 return 1;
1162 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1163 size_t orig_old_count, size_t orig_new_count)
1165 struct hunk_header *header = &hunk->header;
1166 size_t i;
1168 header->old_count = header->new_count = 0;
1169 for (i = hunk->start; i < hunk->end; ) {
1170 switch (s->plain.buf[i]) {
1171 case '-':
1172 header->old_count++;
1173 break;
1174 case '+':
1175 header->new_count++;
1176 break;
1177 case ' ': case '\r': case '\n':
1178 header->old_count++;
1179 header->new_count++;
1180 break;
1183 i = find_next_line(&s->plain, i);
1186 return orig_old_count - orig_new_count
1187 - header->old_count + header->new_count;
1190 static int run_apply_check(struct add_p_state *s,
1191 struct file_diff *file_diff)
1193 struct child_process cp = CHILD_PROCESS_INIT;
1195 strbuf_reset(&s->buf);
1196 reassemble_patch(s, file_diff, 1, &s->buf);
1198 setup_child_process(s, &cp,
1199 "apply", "--check", NULL);
1200 strvec_pushv(&cp.args, s->mode->apply_check_args);
1201 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1202 return error(_("'git apply --cached' failed"));
1204 return 0;
1207 static int read_single_character(struct add_p_state *s)
1209 if (s->s.use_single_key) {
1210 int res = read_key_without_echo(&s->answer);
1211 printf("%s\n", res == EOF ? "" : s->answer.buf);
1212 return res;
1215 if (git_read_line_interactively(&s->answer) == EOF)
1216 return EOF;
1217 return 0;
1220 static int prompt_yesno(struct add_p_state *s, const char *prompt)
1222 for (;;) {
1223 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1224 fflush(stdout);
1225 if (read_single_character(s) == EOF)
1226 return -1;
1227 switch (tolower(s->answer.buf[0])) {
1228 case 'n': return 0;
1229 case 'y': return 1;
1234 static int edit_hunk_loop(struct add_p_state *s,
1235 struct file_diff *file_diff, struct hunk *hunk)
1237 size_t plain_len = s->plain.len, colored_len = s->colored.len;
1238 struct hunk backup;
1240 backup = *hunk;
1242 for (;;) {
1243 int res = edit_hunk_manually(s, hunk);
1244 if (res == 0) {
1245 /* abandoned */
1246 *hunk = backup;
1247 return -1;
1250 if (res > 0) {
1251 hunk->delta +=
1252 recount_edited_hunk(s, hunk,
1253 backup.header.old_count,
1254 backup.header.new_count);
1255 if (!run_apply_check(s, file_diff))
1256 return 0;
1259 /* Drop edits (they were appended to s->plain) */
1260 strbuf_setlen(&s->plain, plain_len);
1261 strbuf_setlen(&s->colored, colored_len);
1262 *hunk = backup;
1265 * TRANSLATORS: do not translate [y/n]
1266 * The program will only accept that input at this point.
1267 * Consider translating (saying "no" discards!) as
1268 * (saying "n" for "no" discards!) if the translation
1269 * of the word "no" does not start with n.
1271 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1272 "Edit again (saying \"no\" discards!) "
1273 "[y/n]? "));
1274 if (res < 1)
1275 return -1;
1279 static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1280 int is_reverse)
1282 const char *reverse = is_reverse ? "-R" : NULL;
1283 struct child_process check_index = CHILD_PROCESS_INIT;
1284 struct child_process check_worktree = CHILD_PROCESS_INIT;
1285 struct child_process apply_index = CHILD_PROCESS_INIT;
1286 struct child_process apply_worktree = CHILD_PROCESS_INIT;
1287 int applies_index, applies_worktree;
1289 setup_child_process(s, &check_index,
1290 "apply", "--cached", "--check", reverse, NULL);
1291 applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1292 NULL, 0, NULL, 0);
1294 setup_child_process(s, &check_worktree,
1295 "apply", "--check", reverse, NULL);
1296 applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1297 NULL, 0, NULL, 0);
1299 if (applies_worktree && applies_index) {
1300 setup_child_process(s, &apply_index,
1301 "apply", "--cached", reverse, NULL);
1302 pipe_command(&apply_index, diff->buf, diff->len,
1303 NULL, 0, NULL, 0);
1305 setup_child_process(s, &apply_worktree,
1306 "apply", reverse, NULL);
1307 pipe_command(&apply_worktree, diff->buf, diff->len,
1308 NULL, 0, NULL, 0);
1310 return 1;
1313 if (!applies_index) {
1314 err(s, _("The selected hunks do not apply to the index!"));
1315 if (prompt_yesno(s, _("Apply them to the worktree "
1316 "anyway? ")) > 0) {
1317 setup_child_process(s, &apply_worktree,
1318 "apply", reverse, NULL);
1319 return pipe_command(&apply_worktree, diff->buf,
1320 diff->len, NULL, 0, NULL, 0);
1322 err(s, _("Nothing was applied.\n"));
1323 } else
1324 /* As a last resort, show the diff to the user */
1325 fwrite(diff->buf, diff->len, 1, stderr);
1327 return 0;
1330 #define SUMMARY_HEADER_WIDTH 20
1331 #define SUMMARY_LINE_WIDTH 80
1332 static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1333 struct strbuf *out)
1335 struct hunk_header *header = &hunk->header;
1336 struct strbuf *plain = &s->plain;
1337 size_t len = out->len, i;
1339 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1340 header->old_offset, header->old_count,
1341 header->new_offset, header->new_count);
1342 if (out->len - len < SUMMARY_HEADER_WIDTH)
1343 strbuf_addchars(out, ' ',
1344 SUMMARY_HEADER_WIDTH + len - out->len);
1345 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1346 if (plain->buf[i] != ' ')
1347 break;
1348 if (i < hunk->end)
1349 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1350 if (out->len - len > SUMMARY_LINE_WIDTH)
1351 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1352 strbuf_complete_line(out);
1355 #define DISPLAY_HUNKS_LINES 20
1356 static size_t display_hunks(struct add_p_state *s,
1357 struct file_diff *file_diff, size_t start_index)
1359 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1361 if (end_index > file_diff->hunk_nr)
1362 end_index = file_diff->hunk_nr;
1364 while (start_index < end_index) {
1365 struct hunk *hunk = file_diff->hunk + start_index++;
1367 strbuf_reset(&s->buf);
1368 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1369 : hunk->use == SKIP_HUNK ? '-' : ' ',
1370 (int)start_index);
1371 summarize_hunk(s, hunk, &s->buf);
1372 fputs(s->buf.buf, stdout);
1375 return end_index;
1378 static const char help_patch_remainder[] =
1379 N_("j - leave this hunk undecided, see next undecided hunk\n"
1380 "J - leave this hunk undecided, see next hunk\n"
1381 "k - leave this hunk undecided, see previous undecided hunk\n"
1382 "K - leave this hunk undecided, see previous hunk\n"
1383 "g - select a hunk to go to\n"
1384 "/ - search for a hunk matching the given regex\n"
1385 "s - split the current hunk into smaller hunks\n"
1386 "e - manually edit the current hunk\n"
1387 "? - print help\n");
1389 static int patch_update_file(struct add_p_state *s,
1390 struct file_diff *file_diff)
1392 size_t hunk_index = 0;
1393 ssize_t i, undecided_previous, undecided_next;
1394 struct hunk *hunk;
1395 char ch;
1396 struct child_process cp = CHILD_PROCESS_INIT;
1397 int colored = !!s->colored.len, quit = 0;
1398 enum prompt_mode_type prompt_mode_type;
1399 enum {
1400 ALLOW_GOTO_PREVIOUS_HUNK = 1 << 0,
1401 ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK = 1 << 1,
1402 ALLOW_GOTO_NEXT_HUNK = 1 << 2,
1403 ALLOW_GOTO_NEXT_UNDECIDED_HUNK = 1 << 3,
1404 ALLOW_SEARCH_AND_GOTO = 1 << 4,
1405 ALLOW_SPLIT = 1 << 5,
1406 ALLOW_EDIT = 1 << 6
1407 } permitted = 0;
1409 /* Empty added files have no hunks */
1410 if (!file_diff->hunk_nr && !file_diff->added)
1411 return 0;
1413 strbuf_reset(&s->buf);
1414 render_diff_header(s, file_diff, colored, &s->buf);
1415 fputs(s->buf.buf, stdout);
1416 for (;;) {
1417 if (hunk_index >= file_diff->hunk_nr)
1418 hunk_index = 0;
1419 hunk = file_diff->hunk_nr
1420 ? file_diff->hunk + hunk_index
1421 : &file_diff->head;
1422 undecided_previous = -1;
1423 undecided_next = -1;
1425 if (file_diff->hunk_nr) {
1426 for (i = hunk_index - 1; i >= 0; i--)
1427 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1428 undecided_previous = i;
1429 break;
1432 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1433 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1434 undecided_next = i;
1435 break;
1439 /* Everything decided? */
1440 if (undecided_previous < 0 && undecided_next < 0 &&
1441 hunk->use != UNDECIDED_HUNK)
1442 break;
1444 strbuf_reset(&s->buf);
1445 if (file_diff->hunk_nr) {
1446 render_hunk(s, hunk, 0, colored, &s->buf);
1447 fputs(s->buf.buf, stdout);
1449 strbuf_reset(&s->buf);
1450 if (undecided_previous >= 0) {
1451 permitted |= ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK;
1452 strbuf_addstr(&s->buf, ",k");
1454 if (hunk_index) {
1455 permitted |= ALLOW_GOTO_PREVIOUS_HUNK;
1456 strbuf_addstr(&s->buf, ",K");
1458 if (undecided_next >= 0) {
1459 permitted |= ALLOW_GOTO_NEXT_UNDECIDED_HUNK;
1460 strbuf_addstr(&s->buf, ",j");
1462 if (hunk_index + 1 < file_diff->hunk_nr) {
1463 permitted |= ALLOW_GOTO_NEXT_HUNK;
1464 strbuf_addstr(&s->buf, ",J");
1466 if (file_diff->hunk_nr > 1) {
1467 permitted |= ALLOW_SEARCH_AND_GOTO;
1468 strbuf_addstr(&s->buf, ",g,/");
1470 if (hunk->splittable_into > 1) {
1471 permitted |= ALLOW_SPLIT;
1472 strbuf_addstr(&s->buf, ",s");
1474 if (hunk_index + 1 > file_diff->mode_change &&
1475 !file_diff->deleted) {
1476 permitted |= ALLOW_EDIT;
1477 strbuf_addstr(&s->buf, ",e");
1480 if (file_diff->deleted)
1481 prompt_mode_type = PROMPT_DELETION;
1482 else if (file_diff->added)
1483 prompt_mode_type = PROMPT_ADDITION;
1484 else if (file_diff->mode_change && !hunk_index)
1485 prompt_mode_type = PROMPT_MODE_CHANGE;
1486 else
1487 prompt_mode_type = PROMPT_HUNK;
1489 printf("%s(%"PRIuMAX"/%"PRIuMAX") ", s->s.prompt_color,
1490 (uintmax_t)hunk_index + 1,
1491 (uintmax_t)(file_diff->hunk_nr
1492 ? file_diff->hunk_nr
1493 : 1));
1494 printf(_(s->mode->prompt_mode[prompt_mode_type]),
1495 s->buf.buf);
1496 if (*s->s.reset_color)
1497 fputs(s->s.reset_color, stdout);
1498 fflush(stdout);
1499 if (read_single_character(s) == EOF)
1500 break;
1502 if (!s->answer.len)
1503 continue;
1504 ch = tolower(s->answer.buf[0]);
1505 if (ch == 'y') {
1506 hunk->use = USE_HUNK;
1507 soft_increment:
1508 hunk_index = undecided_next < 0 ?
1509 file_diff->hunk_nr : undecided_next;
1510 } else if (ch == 'n') {
1511 hunk->use = SKIP_HUNK;
1512 goto soft_increment;
1513 } else if (ch == 'a') {
1514 if (file_diff->hunk_nr) {
1515 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1516 hunk = file_diff->hunk + hunk_index;
1517 if (hunk->use == UNDECIDED_HUNK)
1518 hunk->use = USE_HUNK;
1520 } else if (hunk->use == UNDECIDED_HUNK) {
1521 hunk->use = USE_HUNK;
1523 } else if (ch == 'd' || ch == 'q') {
1524 if (file_diff->hunk_nr) {
1525 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1526 hunk = file_diff->hunk + hunk_index;
1527 if (hunk->use == UNDECIDED_HUNK)
1528 hunk->use = SKIP_HUNK;
1530 } else if (hunk->use == UNDECIDED_HUNK) {
1531 hunk->use = SKIP_HUNK;
1533 if (ch == 'q') {
1534 quit = 1;
1535 break;
1537 } else if (s->answer.buf[0] == 'K') {
1538 if (permitted & ALLOW_GOTO_PREVIOUS_HUNK)
1539 hunk_index--;
1540 else
1541 err(s, _("No previous hunk"));
1542 } else if (s->answer.buf[0] == 'J') {
1543 if (permitted & ALLOW_GOTO_NEXT_HUNK)
1544 hunk_index++;
1545 else
1546 err(s, _("No next hunk"));
1547 } else if (s->answer.buf[0] == 'k') {
1548 if (permitted & ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK)
1549 hunk_index = undecided_previous;
1550 else
1551 err(s, _("No previous hunk"));
1552 } else if (s->answer.buf[0] == 'j') {
1553 if (permitted & ALLOW_GOTO_NEXT_UNDECIDED_HUNK)
1554 hunk_index = undecided_next;
1555 else
1556 err(s, _("No next hunk"));
1557 } else if (s->answer.buf[0] == 'g') {
1558 char *pend;
1559 unsigned long response;
1561 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1562 err(s, _("No other hunks to goto"));
1563 continue;
1565 strbuf_remove(&s->answer, 0, 1);
1566 strbuf_trim(&s->answer);
1567 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1568 if (i < (int)file_diff->mode_change)
1569 i = file_diff->mode_change;
1570 while (s->answer.len == 0) {
1571 i = display_hunks(s, file_diff, i);
1572 printf("%s", i < file_diff->hunk_nr ?
1573 _("go to which hunk (<ret> to see "
1574 "more)? ") : _("go to which hunk? "));
1575 fflush(stdout);
1576 if (strbuf_getline(&s->answer,
1577 stdin) == EOF)
1578 break;
1579 strbuf_trim_trailing_newline(&s->answer);
1582 strbuf_trim(&s->answer);
1583 response = strtoul(s->answer.buf, &pend, 10);
1584 if (*pend || pend == s->answer.buf)
1585 err(s, _("Invalid number: '%s'"),
1586 s->answer.buf);
1587 else if (0 < response && response <= file_diff->hunk_nr)
1588 hunk_index = response - 1;
1589 else
1590 err(s, Q_("Sorry, only %d hunk available.",
1591 "Sorry, only %d hunks available.",
1592 file_diff->hunk_nr),
1593 (int)file_diff->hunk_nr);
1594 } else if (s->answer.buf[0] == '/') {
1595 regex_t regex;
1596 int ret;
1598 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1599 err(s, _("No other hunks to search"));
1600 continue;
1602 strbuf_remove(&s->answer, 0, 1);
1603 strbuf_trim_trailing_newline(&s->answer);
1604 if (s->answer.len == 0) {
1605 printf("%s", _("search for regex? "));
1606 fflush(stdout);
1607 if (strbuf_getline(&s->answer,
1608 stdin) == EOF)
1609 break;
1610 strbuf_trim_trailing_newline(&s->answer);
1611 if (s->answer.len == 0)
1612 continue;
1614 ret = regcomp(&regex, s->answer.buf,
1615 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1616 if (ret) {
1617 char errbuf[1024];
1619 regerror(ret, &regex, errbuf, sizeof(errbuf));
1620 err(s, _("Malformed search regexp %s: %s"),
1621 s->answer.buf, errbuf);
1622 continue;
1624 i = hunk_index;
1625 for (;;) {
1626 /* render the hunk into a scratch buffer */
1627 render_hunk(s, file_diff->hunk + i, 0, 0,
1628 &s->buf);
1629 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1630 != REG_NOMATCH)
1631 break;
1632 i++;
1633 if (i == file_diff->hunk_nr)
1634 i = 0;
1635 if (i != hunk_index)
1636 continue;
1637 err(s, _("No hunk matches the given pattern"));
1638 break;
1640 hunk_index = i;
1641 } else if (s->answer.buf[0] == 's') {
1642 size_t splittable_into = hunk->splittable_into;
1643 if (!(permitted & ALLOW_SPLIT))
1644 err(s, _("Sorry, cannot split this hunk"));
1645 else if (!split_hunk(s, file_diff,
1646 hunk - file_diff->hunk))
1647 color_fprintf_ln(stdout, s->s.header_color,
1648 _("Split into %d hunks."),
1649 (int)splittable_into);
1650 } else if (s->answer.buf[0] == 'e') {
1651 if (!(permitted & ALLOW_EDIT))
1652 err(s, _("Sorry, cannot edit this hunk"));
1653 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1654 hunk->use = USE_HUNK;
1655 goto soft_increment;
1657 } else {
1658 const char *p = _(help_patch_remainder), *eol = p;
1660 color_fprintf(stdout, s->s.help_color, "%s",
1661 _(s->mode->help_patch_text));
1664 * Show only those lines of the remainder that are
1665 * actually applicable with the current hunk.
1667 for (; *p; p = eol + (*eol == '\n')) {
1668 eol = strchrnul(p, '\n');
1671 * `s->buf` still contains the part of the
1672 * commands shown in the prompt that are not
1673 * always available.
1675 if (*p != '?' && !strchr(s->buf.buf, *p))
1676 continue;
1678 color_fprintf_ln(stdout, s->s.help_color,
1679 "%.*s", (int)(eol - p), p);
1684 /* Any hunk to be used? */
1685 for (i = 0; i < file_diff->hunk_nr; i++)
1686 if (file_diff->hunk[i].use == USE_HUNK)
1687 break;
1689 if (i < file_diff->hunk_nr ||
1690 (!file_diff->hunk_nr && file_diff->head.use == USE_HUNK)) {
1691 /* At least one hunk selected: apply */
1692 strbuf_reset(&s->buf);
1693 reassemble_patch(s, file_diff, 0, &s->buf);
1695 discard_index(s->s.r->index);
1696 if (s->mode->apply_for_checkout)
1697 apply_for_checkout(s, &s->buf,
1698 s->mode->is_reverse);
1699 else {
1700 setup_child_process(s, &cp, "apply", NULL);
1701 strvec_pushv(&cp.args, s->mode->apply_args);
1702 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1703 NULL, 0, NULL, 0))
1704 error(_("'git apply' failed"));
1706 if (repo_read_index(s->s.r) >= 0)
1707 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
1708 1, NULL, NULL, NULL);
1711 putchar('\n');
1712 return quit;
1715 int run_add_p(struct repository *r, enum add_p_mode mode,
1716 const char *revision, const struct pathspec *ps)
1718 struct add_p_state s = {
1719 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1721 size_t i, binary_count = 0;
1723 init_add_i_state(&s.s, r);
1725 if (mode == ADD_P_STASH)
1726 s.mode = &patch_mode_stash;
1727 else if (mode == ADD_P_RESET) {
1729 * NEEDSWORK: Instead of comparing to the literal "HEAD",
1730 * compare the commit objects instead so that other ways of
1731 * saying the same thing (such as "@") are also handled
1732 * appropriately.
1734 * This applies to the cases below too.
1736 if (!revision || !strcmp(revision, "HEAD"))
1737 s.mode = &patch_mode_reset_head;
1738 else
1739 s.mode = &patch_mode_reset_nothead;
1740 } else if (mode == ADD_P_CHECKOUT) {
1741 if (!revision)
1742 s.mode = &patch_mode_checkout_index;
1743 else if (!strcmp(revision, "HEAD"))
1744 s.mode = &patch_mode_checkout_head;
1745 else
1746 s.mode = &patch_mode_checkout_nothead;
1747 } else if (mode == ADD_P_WORKTREE) {
1748 if (!revision)
1749 s.mode = &patch_mode_checkout_index;
1750 else if (!strcmp(revision, "HEAD"))
1751 s.mode = &patch_mode_worktree_head;
1752 else
1753 s.mode = &patch_mode_worktree_nothead;
1754 } else
1755 s.mode = &patch_mode_add;
1756 s.revision = revision;
1758 discard_index(r->index);
1759 if (repo_read_index(r) < 0 ||
1760 (!s.mode->index_only &&
1761 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1762 NULL, NULL, NULL) < 0) ||
1763 parse_diff(&s, ps) < 0) {
1764 add_p_state_clear(&s);
1765 return -1;
1768 for (i = 0; i < s.file_diff_nr; i++)
1769 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1770 binary_count++;
1771 else if (patch_update_file(&s, s.file_diff + i))
1772 break;
1774 if (s.file_diff_nr == 0)
1775 fprintf(stderr, _("No changes.\n"));
1776 else if (binary_count == s.file_diff_nr)
1777 fprintf(stderr, _("Only binary files changed.\n"));
1779 add_p_state_clear(&s);
1780 return 0;