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