Merge branch 'ds/line-log-asan-fix'
[git/gitster.git] / add-patch.c
blob557903310deb23b2b8362bb4688b3d0cd2a1577b
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 "pager.h"
11 #include "read-cache-ll.h"
12 #include "repository.h"
13 #include "strbuf.h"
14 #include "sigchain.h"
15 #include "run-command.h"
16 #include "strvec.h"
17 #include "pathspec.h"
18 #include "color.h"
19 #include "compat/terminal.h"
20 #include "prompt.h"
22 enum prompt_mode_type {
23 PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_ADDITION, PROMPT_HUNK,
24 PROMPT_MODE_MAX, /* must be last */
27 struct patch_mode {
29 * The magic constant 4 is chosen such that all patch modes
30 * provide enough space for three command-line arguments followed by a
31 * trailing `NULL`.
33 const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
34 unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
35 const char *prompt_mode[PROMPT_MODE_MAX];
36 const char *edit_hunk_hint, *help_patch_text;
39 static struct patch_mode patch_mode_add = {
40 .diff_cmd = { "diff-files", NULL },
41 .apply_args = { "--cached", NULL },
42 .apply_check_args = { "--cached", NULL },
43 .prompt_mode = {
44 N_("Stage mode change [y,n,q,a,d%s,?]? "),
45 N_("Stage deletion [y,n,q,a,d%s,?]? "),
46 N_("Stage addition [y,n,q,a,d%s,?]? "),
47 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
49 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
50 "will immediately be marked for staging."),
51 .help_patch_text =
52 N_("y - stage this hunk\n"
53 "n - do not stage this hunk\n"
54 "q - quit; do not stage this hunk or any of the remaining "
55 "ones\n"
56 "a - stage this hunk and all later hunks in the file\n"
57 "d - do not stage this hunk or any of the later hunks in "
58 "the file\n")
61 static struct patch_mode patch_mode_stash = {
62 .diff_cmd = { "diff-index", "HEAD", NULL },
63 .apply_args = { "--cached", NULL },
64 .apply_check_args = { "--cached", NULL },
65 .prompt_mode = {
66 N_("Stash mode change [y,n,q,a,d%s,?]? "),
67 N_("Stash deletion [y,n,q,a,d%s,?]? "),
68 N_("Stash addition [y,n,q,a,d%s,?]? "),
69 N_("Stash this hunk [y,n,q,a,d%s,?]? "),
71 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
72 "will immediately be marked for stashing."),
73 .help_patch_text =
74 N_("y - stash this hunk\n"
75 "n - do not stash this hunk\n"
76 "q - quit; do not stash this hunk or any of the remaining "
77 "ones\n"
78 "a - stash this hunk and all later hunks in the file\n"
79 "d - do not stash this hunk or any of the later hunks in "
80 "the file\n"),
83 static struct patch_mode patch_mode_reset_head = {
84 .diff_cmd = { "diff-index", "--cached", NULL },
85 .apply_args = { "-R", "--cached", NULL },
86 .apply_check_args = { "-R", "--cached", NULL },
87 .is_reverse = 1,
88 .index_only = 1,
89 .prompt_mode = {
90 N_("Unstage mode change [y,n,q,a,d%s,?]? "),
91 N_("Unstage deletion [y,n,q,a,d%s,?]? "),
92 N_("Unstage addition [y,n,q,a,d%s,?]? "),
93 N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
95 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
96 "will immediately be marked for unstaging."),
97 .help_patch_text =
98 N_("y - unstage this hunk\n"
99 "n - do not unstage this hunk\n"
100 "q - quit; do not unstage this hunk or any of the remaining "
101 "ones\n"
102 "a - unstage this hunk and all later hunks in the file\n"
103 "d - do not unstage this hunk or any of the later hunks in "
104 "the file\n"),
107 static struct patch_mode patch_mode_reset_nothead = {
108 .diff_cmd = { "diff-index", "-R", "--cached", NULL },
109 .apply_args = { "--cached", NULL },
110 .apply_check_args = { "--cached", NULL },
111 .index_only = 1,
112 .prompt_mode = {
113 N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
114 N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
115 N_("Apply addition to index [y,n,q,a,d%s,?]? "),
116 N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
118 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
119 "will immediately be marked for applying."),
120 .help_patch_text =
121 N_("y - apply this hunk to index\n"
122 "n - do not apply this hunk to index\n"
123 "q - quit; do not apply this hunk or any of the remaining "
124 "ones\n"
125 "a - apply this hunk and all later hunks in the file\n"
126 "d - do not apply this hunk or any of the later hunks in "
127 "the file\n"),
130 static struct patch_mode patch_mode_checkout_index = {
131 .diff_cmd = { "diff-files", NULL },
132 .apply_args = { "-R", NULL },
133 .apply_check_args = { "-R", NULL },
134 .is_reverse = 1,
135 .prompt_mode = {
136 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
137 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
138 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
139 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
141 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
142 "will immediately be marked for discarding."),
143 .help_patch_text =
144 N_("y - discard this hunk from worktree\n"
145 "n - do not discard this hunk from worktree\n"
146 "q - quit; do not discard this hunk or any of the remaining "
147 "ones\n"
148 "a - discard this hunk and all later hunks in the file\n"
149 "d - do not discard this hunk or any of the later hunks in "
150 "the file\n"),
153 static struct patch_mode patch_mode_checkout_head = {
154 .diff_cmd = { "diff-index", NULL },
155 .apply_for_checkout = 1,
156 .apply_check_args = { "-R", NULL },
157 .is_reverse = 1,
158 .prompt_mode = {
159 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
160 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
161 N_("Discard addition from index and worktree [y,n,q,a,d%s,?]? "),
162 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
164 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
165 "will immediately be marked for discarding."),
166 .help_patch_text =
167 N_("y - discard this hunk from index and worktree\n"
168 "n - do not discard this hunk from index and worktree\n"
169 "q - quit; do not discard this hunk or any of the remaining "
170 "ones\n"
171 "a - discard this hunk and all later hunks in the file\n"
172 "d - do not discard this hunk or any of the later hunks in "
173 "the file\n"),
176 static struct patch_mode patch_mode_checkout_nothead = {
177 .diff_cmd = { "diff-index", "-R", NULL },
178 .apply_for_checkout = 1,
179 .apply_check_args = { NULL },
180 .prompt_mode = {
181 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
182 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
183 N_("Apply addition to index and worktree [y,n,q,a,d%s,?]? "),
184 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
186 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
187 "will immediately be marked for applying."),
188 .help_patch_text =
189 N_("y - apply this hunk to index and worktree\n"
190 "n - do not apply this hunk to index and worktree\n"
191 "q - quit; do not apply this hunk or any of the remaining "
192 "ones\n"
193 "a - apply this hunk and all later hunks in the file\n"
194 "d - do not apply this hunk or any of the later hunks in "
195 "the file\n"),
198 static struct patch_mode patch_mode_worktree_head = {
199 .diff_cmd = { "diff-index", NULL },
200 .apply_args = { "-R", NULL },
201 .apply_check_args = { "-R", NULL },
202 .is_reverse = 1,
203 .prompt_mode = {
204 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
205 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
206 N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
207 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
209 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
210 "will immediately be marked for discarding."),
211 .help_patch_text =
212 N_("y - discard this hunk from worktree\n"
213 "n - do not discard this hunk from worktree\n"
214 "q - quit; do not discard this hunk or any of the remaining "
215 "ones\n"
216 "a - discard this hunk and all later hunks in the file\n"
217 "d - do not discard this hunk or any of the later hunks in "
218 "the file\n"),
221 static struct patch_mode patch_mode_worktree_nothead = {
222 .diff_cmd = { "diff-index", "-R", NULL },
223 .apply_args = { NULL },
224 .apply_check_args = { NULL },
225 .prompt_mode = {
226 N_("Apply mode change to worktree [y,n,q,a,d%s,?]? "),
227 N_("Apply deletion to worktree [y,n,q,a,d%s,?]? "),
228 N_("Apply addition to worktree [y,n,q,a,d%s,?]? "),
229 N_("Apply this hunk to worktree [y,n,q,a,d%s,?]? "),
231 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
232 "will immediately be marked for applying."),
233 .help_patch_text =
234 N_("y - apply this hunk to worktree\n"
235 "n - do not apply this hunk to worktree\n"
236 "q - quit; do not apply this hunk or any of the remaining "
237 "ones\n"
238 "a - apply this hunk and all later hunks in the file\n"
239 "d - do not apply this hunk or any of the later hunks in "
240 "the file\n"),
243 struct hunk_header {
244 unsigned long old_offset, old_count, new_offset, new_count;
246 * Start/end offsets to the extra text after the second `@@` in the
247 * hunk header, e.g. the function signature. This is expected to
248 * include the newline.
250 size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
251 unsigned suppress_colored_line_range:1;
254 struct hunk {
255 size_t start, end, colored_start, colored_end, splittable_into;
256 ssize_t delta;
257 enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
258 struct hunk_header header;
261 struct add_p_state {
262 struct add_i_state s;
263 struct strbuf answer, buf;
265 /* parsed diff */
266 struct strbuf plain, colored;
267 struct file_diff {
268 struct hunk head;
269 struct hunk *hunk;
270 size_t hunk_nr, hunk_alloc;
271 unsigned deleted:1, added:1, mode_change:1,binary:1;
272 } *file_diff;
273 size_t file_diff_nr;
275 /* patch mode */
276 struct patch_mode *mode;
277 const char *revision;
280 static void add_p_state_clear(struct add_p_state *s)
282 size_t i;
284 strbuf_release(&s->answer);
285 strbuf_release(&s->buf);
286 strbuf_release(&s->plain);
287 strbuf_release(&s->colored);
288 for (i = 0; i < s->file_diff_nr; i++)
289 free(s->file_diff[i].hunk);
290 free(s->file_diff);
291 clear_add_i_state(&s->s);
294 __attribute__((format (printf, 2, 3)))
295 static void err(struct add_p_state *s, const char *fmt, ...)
297 va_list args;
299 va_start(args, fmt);
300 fputs(s->s.error_color, stdout);
301 vprintf(fmt, args);
302 puts(s->s.reset_color);
303 va_end(args);
306 LAST_ARG_MUST_BE_NULL
307 static void setup_child_process(struct add_p_state *s,
308 struct child_process *cp, ...)
310 va_list ap;
311 const char *arg;
313 va_start(ap, cp);
314 while ((arg = va_arg(ap, const char *)))
315 strvec_push(&cp->args, arg);
316 va_end(ap);
318 cp->git_cmd = 1;
319 strvec_pushf(&cp->env,
320 INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
323 static int parse_range(const char **p,
324 unsigned long *offset, unsigned long *count)
326 char *pend;
328 *offset = strtoul(*p, &pend, 10);
329 if (pend == *p)
330 return -1;
331 if (*pend != ',') {
332 *count = 1;
333 *p = pend;
334 return 0;
336 *count = strtoul(pend + 1, (char **)p, 10);
337 return *p == pend + 1 ? -1 : 0;
340 static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
342 struct hunk_header *header = &hunk->header;
343 const char *line = s->plain.buf + hunk->start, *p = line;
344 char *eol = memchr(p, '\n', s->plain.len - hunk->start);
346 if (!eol)
347 eol = s->plain.buf + s->plain.len;
349 if (!skip_prefix(p, "@@ -", &p) ||
350 parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
351 !skip_prefix(p, " +", &p) ||
352 parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
353 !skip_prefix(p, " @@", &p))
354 return error(_("could not parse hunk header '%.*s'"),
355 (int)(eol - line), line);
357 hunk->start = eol - s->plain.buf + (*eol == '\n');
358 header->extra_start = p - s->plain.buf;
359 header->extra_end = hunk->start;
361 if (!s->colored.len) {
362 header->colored_extra_start = header->colored_extra_end = 0;
363 return 0;
366 /* Now find the extra text in the colored diff */
367 line = s->colored.buf + hunk->colored_start;
368 eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
369 if (!eol)
370 eol = s->colored.buf + s->colored.len;
371 p = memmem(line, eol - line, "@@ -", 4);
372 if (p && (p = memmem(p + 4, eol - p - 4, " @@", 3))) {
373 header->colored_extra_start = p + 3 - s->colored.buf;
374 } else {
375 /* could not parse colored hunk header, leave as-is */
376 header->colored_extra_start = hunk->colored_start;
377 header->suppress_colored_line_range = 1;
379 hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
380 header->colored_extra_end = hunk->colored_start;
382 return 0;
385 static int is_octal(const char *p, size_t len)
387 if (!len)
388 return 0;
390 while (len--)
391 if (*p < '0' || *(p++) > '7')
392 return 0;
393 return 1;
396 static void complete_file(char marker, struct hunk *hunk)
398 if (marker == '-' || marker == '+')
400 * Last hunk ended in non-context line (i.e. it
401 * appended lines to the file, so there are no
402 * trailing context lines).
404 hunk->splittable_into++;
407 /* Empty context lines may omit the leading ' ' */
408 static int normalize_marker(const char *p)
410 return p[0] == '\n' || (p[0] == '\r' && p[1] == '\n') ? ' ' : p[0];
413 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
415 struct strvec args = STRVEC_INIT;
416 const char *diff_algorithm = s->s.interactive_diff_algorithm;
417 struct strbuf *plain = &s->plain, *colored = NULL;
418 struct child_process cp = CHILD_PROCESS_INIT;
419 char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
420 size_t file_diff_alloc = 0, i, color_arg_index;
421 struct file_diff *file_diff = NULL;
422 struct hunk *hunk = NULL;
423 int res;
425 strvec_pushv(&args, s->mode->diff_cmd);
426 if (diff_algorithm)
427 strvec_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
428 if (s->revision) {
429 struct object_id oid;
430 strvec_push(&args,
431 /* could be on an unborn branch */
432 !strcmp("HEAD", s->revision) &&
433 repo_get_oid(the_repository, "HEAD", &oid) ?
434 empty_tree_oid_hex(the_repository->hash_algo) : s->revision);
436 color_arg_index = args.nr;
437 /* Use `--no-color` explicitly, just in case `diff.color = always`. */
438 strvec_pushl(&args, "--no-color", "--ignore-submodules=dirty", "-p",
439 "--", NULL);
440 for (i = 0; i < ps->nr; i++)
441 strvec_push(&args, ps->items[i].original);
443 setup_child_process(s, &cp, NULL);
444 strvec_pushv(&cp.args, args.v);
445 res = capture_command(&cp, plain, 0);
446 if (res) {
447 strvec_clear(&args);
448 return error(_("could not parse diff"));
450 if (!plain->len) {
451 strvec_clear(&args);
452 return 0;
454 strbuf_complete_line(plain);
456 if (want_color_fd(1, -1)) {
457 struct child_process colored_cp = CHILD_PROCESS_INIT;
458 const char *diff_filter = s->s.interactive_diff_filter;
460 setup_child_process(s, &colored_cp, NULL);
461 xsnprintf((char *)args.v[color_arg_index], 8, "--color");
462 strvec_pushv(&colored_cp.args, args.v);
463 colored = &s->colored;
464 res = capture_command(&colored_cp, colored, 0);
465 strvec_clear(&args);
466 if (res)
467 return error(_("could not parse colored diff"));
469 if (diff_filter) {
470 struct child_process filter_cp = CHILD_PROCESS_INIT;
472 setup_child_process(s, &filter_cp,
473 diff_filter, NULL);
474 filter_cp.git_cmd = 0;
475 filter_cp.use_shell = 1;
476 strbuf_reset(&s->buf);
477 if (pipe_command(&filter_cp,
478 colored->buf, colored->len,
479 &s->buf, colored->len,
480 NULL, 0) < 0)
481 return error(_("failed to run '%s'"),
482 diff_filter);
483 strbuf_swap(colored, &s->buf);
486 strbuf_complete_line(colored);
487 colored_p = colored->buf;
488 colored_pend = colored_p + colored->len;
490 strvec_clear(&args);
492 /* parse files and hunks */
493 p = plain->buf;
494 pend = p + plain->len;
495 while (p != pend) {
496 char *eol = memchr(p, '\n', pend - p);
497 const char *deleted = NULL, *mode_change = NULL;
498 char ch = normalize_marker(p);
500 if (!eol)
501 eol = pend;
503 if (starts_with(p, "diff ") ||
504 starts_with(p, "* Unmerged path ")) {
505 complete_file(marker, hunk);
506 ALLOC_GROW_BY(s->file_diff, s->file_diff_nr, 1,
507 file_diff_alloc);
508 file_diff = s->file_diff + s->file_diff_nr - 1;
509 hunk = &file_diff->head;
510 hunk->start = p - plain->buf;
511 if (colored_p)
512 hunk->colored_start = colored_p - colored->buf;
513 marker = '\0';
514 } else if (p == plain->buf)
515 BUG("diff starts with unexpected line:\n"
516 "%.*s\n", (int)(eol - p), p);
517 else if (file_diff->deleted)
518 ; /* keep the rest of the file in a single "hunk" */
519 else if (starts_with(p, "@@ ") ||
520 (hunk == &file_diff->head &&
521 (skip_prefix(p, "deleted file", &deleted)))) {
522 if (marker == '-' || marker == '+')
524 * Should not happen; previous hunk did not end
525 * in a context line? Handle it anyway.
527 hunk->splittable_into++;
529 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
530 file_diff->hunk_alloc);
531 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
533 hunk->start = p - plain->buf;
534 if (colored)
535 hunk->colored_start = colored_p - colored->buf;
537 if (deleted)
538 file_diff->deleted = 1;
539 else if (parse_hunk_header(s, hunk) < 0)
540 return -1;
543 * Start counting into how many hunks this one can be
544 * split
546 marker = ch;
547 } else if (hunk == &file_diff->head &&
548 starts_with(p, "new file")) {
549 file_diff->added = 1;
550 } else if (hunk == &file_diff->head &&
551 skip_prefix(p, "old mode ", &mode_change) &&
552 is_octal(mode_change, eol - mode_change)) {
553 if (file_diff->mode_change)
554 BUG("double mode change?\n\n%.*s",
555 (int)(eol - plain->buf), plain->buf);
556 if (file_diff->hunk_nr)
557 BUG("mode change in the middle?\n\n%.*s",
558 (int)(eol - plain->buf), plain->buf);
561 * Do *not* change `hunk`: the mode change pseudo-hunk
562 * is _part of_ the header "hunk".
564 file_diff->mode_change = 1;
565 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
566 file_diff->hunk_alloc);
567 file_diff->hunk->start = p - plain->buf;
568 if (colored_p)
569 file_diff->hunk->colored_start =
570 colored_p - colored->buf;
571 } else if (hunk == &file_diff->head &&
572 skip_prefix(p, "new mode ", &mode_change) &&
573 is_octal(mode_change, eol - mode_change)) {
576 * Extend the "mode change" pseudo-hunk to include also
577 * the "new mode" line.
579 if (!file_diff->mode_change)
580 BUG("'new mode' without 'old mode'?\n\n%.*s",
581 (int)(eol - plain->buf), plain->buf);
582 if (file_diff->hunk_nr != 1)
583 BUG("mode change in the middle?\n\n%.*s",
584 (int)(eol - plain->buf), plain->buf);
585 if (p - plain->buf != file_diff->hunk->end)
586 BUG("'new mode' does not immediately follow "
587 "'old mode'?\n\n%.*s",
588 (int)(eol - plain->buf), plain->buf);
589 } else if (hunk == &file_diff->head &&
590 starts_with(p, "Binary files "))
591 file_diff->binary = 1;
593 if (!!file_diff->deleted + !!file_diff->added +
594 !!file_diff->mode_change > 1)
595 BUG("diff can only contain delete *or* add *or* a "
596 "mode change?!?\n%.*s",
597 (int)(eol - (plain->buf + file_diff->head.start)),
598 plain->buf + file_diff->head.start);
600 if ((marker == '-' || marker == '+') && ch == ' ')
601 hunk->splittable_into++;
602 if (marker && ch != '\\')
603 marker = ch;
605 p = eol == pend ? pend : eol + 1;
606 hunk->end = p - plain->buf;
608 if (colored) {
609 char *colored_eol = memchr(colored_p, '\n',
610 colored_pend - colored_p);
611 if (colored_eol)
612 colored_p = colored_eol + 1;
613 else if (p != pend)
614 /* non-colored has more lines? */
615 goto mismatched_output;
616 else if (colored_p == colored_pend)
617 /* last line has no matching colored one? */
618 goto mismatched_output;
619 else
620 colored_p = colored_pend;
622 hunk->colored_end = colored_p - colored->buf;
625 if (mode_change) {
626 if (file_diff->hunk_nr != 1)
627 BUG("mode change in hunk #%d???",
628 (int)file_diff->hunk_nr);
629 /* Adjust the end of the "mode change" pseudo-hunk */
630 file_diff->hunk->end = hunk->end;
631 if (colored)
632 file_diff->hunk->colored_end = hunk->colored_end;
635 complete_file(marker, hunk);
637 /* non-colored shorter than colored? */
638 if (colored_p != colored_pend) {
639 mismatched_output:
640 error(_("mismatched output from interactive.diffFilter"));
641 advise(_("Your filter must maintain a one-to-one correspondence\n"
642 "between its input and output lines."));
643 return -1;
646 return 0;
649 static size_t find_next_line(struct strbuf *sb, size_t offset)
651 char *eol;
653 if (offset >= sb->len)
654 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
655 (int)offset, (int)sb->len, sb->buf);
657 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
658 if (!eol)
659 return sb->len;
660 return eol - sb->buf + 1;
663 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
664 ssize_t delta, int colored, struct strbuf *out)
666 struct hunk_header *header = &hunk->header;
668 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
670 * Generate the hunk header dynamically, except for special
671 * hunks (such as the diff header).
673 const char *p;
674 size_t len;
675 unsigned long old_offset = header->old_offset;
676 unsigned long new_offset = header->new_offset;
678 if (!colored) {
679 p = s->plain.buf + header->extra_start;
680 len = header->extra_end - header->extra_start;
681 } else if (header->suppress_colored_line_range) {
682 strbuf_add(out,
683 s->colored.buf + header->colored_extra_start,
684 header->colored_extra_end -
685 header->colored_extra_start);
687 strbuf_add(out, s->colored.buf + hunk->colored_start,
688 hunk->colored_end - hunk->colored_start);
689 return;
690 } else {
691 strbuf_addstr(out, s->s.fraginfo_color);
692 p = s->colored.buf + header->colored_extra_start;
693 len = header->colored_extra_end
694 - header->colored_extra_start;
697 if (s->mode->is_reverse)
698 old_offset -= delta;
699 else
700 new_offset += delta;
702 strbuf_addf(out, "@@ -%lu", old_offset);
703 if (header->old_count != 1)
704 strbuf_addf(out, ",%lu", header->old_count);
705 strbuf_addf(out, " +%lu", new_offset);
706 if (header->new_count != 1)
707 strbuf_addf(out, ",%lu", header->new_count);
708 strbuf_addstr(out, " @@");
710 if (len)
711 strbuf_add(out, p, len);
712 else if (colored)
713 strbuf_addf(out, "%s\n", s->s.reset_color);
714 else
715 strbuf_addch(out, '\n');
718 if (colored)
719 strbuf_add(out, s->colored.buf + hunk->colored_start,
720 hunk->colored_end - hunk->colored_start);
721 else
722 strbuf_add(out, s->plain.buf + hunk->start,
723 hunk->end - hunk->start);
726 static void render_diff_header(struct add_p_state *s,
727 struct file_diff *file_diff, int colored,
728 struct strbuf *out)
731 * If there was a mode change, the first hunk is a pseudo hunk that
732 * corresponds to the mode line in the header. If the user did not want
733 * to stage that "hunk", we actually have to cut it out from the header.
735 int skip_mode_change =
736 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
737 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
739 if (!skip_mode_change) {
740 render_hunk(s, head, 0, colored, out);
741 return;
744 if (colored) {
745 const char *p = s->colored.buf;
747 strbuf_add(out, p + head->colored_start,
748 first->colored_start - head->colored_start);
749 strbuf_add(out, p + first->colored_end,
750 head->colored_end - first->colored_end);
751 } else {
752 const char *p = s->plain.buf;
754 strbuf_add(out, p + head->start, first->start - head->start);
755 strbuf_add(out, p + first->end, head->end - first->end);
759 /* Coalesce hunks again that were split */
760 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
761 size_t *hunk_index, int use_all, struct hunk *merged)
763 size_t i = *hunk_index, delta;
764 struct hunk *hunk = file_diff->hunk + i;
765 /* `header` corresponds to the merged hunk */
766 struct hunk_header *header = &merged->header, *next;
768 if (!use_all && hunk->use != USE_HUNK)
769 return 0;
771 *merged = *hunk;
772 /* We simply skip the colored part (if any) when merging hunks */
773 merged->colored_start = merged->colored_end = 0;
775 for (; i + 1 < file_diff->hunk_nr; i++) {
776 hunk++;
777 next = &hunk->header;
780 * Stop merging hunks when:
782 * - the hunk is not selected for use, or
783 * - the hunk does not overlap with the already-merged hunk(s)
785 if ((!use_all && hunk->use != USE_HUNK) ||
786 header->new_offset >= next->new_offset + merged->delta ||
787 header->new_offset + header->new_count
788 < next->new_offset + merged->delta)
789 break;
792 * If the hunks were not edited, and overlap, we can simply
793 * extend the line range.
795 if (merged->start < hunk->start && merged->end > hunk->start) {
796 merged->end = hunk->end;
797 merged->colored_end = hunk->colored_end;
798 delta = 0;
799 } else {
800 const char *plain = s->plain.buf;
801 size_t overlapping_line_count = header->new_offset
802 + header->new_count - merged->delta
803 - next->new_offset;
804 size_t overlap_end = hunk->start;
805 size_t overlap_start = overlap_end;
806 size_t overlap_next, len, j;
809 * One of the hunks was edited: the modified hunk was
810 * appended to the strbuf `s->plain`.
812 * Let's ensure that at least the last context line of
813 * the first hunk overlaps with the corresponding line
814 * of the second hunk, and then merge.
816 for (j = 0; j < overlapping_line_count; j++) {
817 overlap_next = find_next_line(&s->plain,
818 overlap_end);
820 if (overlap_next > hunk->end)
821 BUG("failed to find %d context lines "
822 "in:\n%.*s",
823 (int)overlapping_line_count,
824 (int)(hunk->end - hunk->start),
825 plain + hunk->start);
827 if (normalize_marker(&plain[overlap_end]) != ' ')
828 return error(_("expected context line "
829 "#%d in\n%.*s"),
830 (int)(j + 1),
831 (int)(hunk->end
832 - hunk->start),
833 plain + hunk->start);
835 overlap_start = overlap_end;
836 overlap_end = overlap_next;
838 len = overlap_end - overlap_start;
840 if (len > merged->end - merged->start ||
841 memcmp(plain + merged->end - len,
842 plain + overlap_start, len))
843 return error(_("hunks do not overlap:\n%.*s\n"
844 "\tdoes not end with:\n%.*s"),
845 (int)(merged->end - merged->start),
846 plain + merged->start,
847 (int)len, plain + overlap_start);
850 * Since the start-end ranges are not adjacent, we
851 * cannot simply take the union of the ranges. To
852 * address that, we temporarily append the union of the
853 * lines to the `plain` strbuf.
855 if (merged->end != s->plain.len) {
856 size_t start = s->plain.len;
858 strbuf_add(&s->plain, plain + merged->start,
859 merged->end - merged->start);
860 plain = s->plain.buf;
861 merged->start = start;
862 merged->end = s->plain.len;
865 strbuf_add(&s->plain,
866 plain + overlap_end,
867 hunk->end - overlap_end);
868 merged->end = s->plain.len;
869 merged->splittable_into += hunk->splittable_into;
870 delta = merged->delta;
871 merged->delta += hunk->delta;
874 header->old_count = next->old_offset + next->old_count
875 - header->old_offset;
876 header->new_count = next->new_offset + delta
877 + next->new_count - header->new_offset;
880 if (i == *hunk_index)
881 return 0;
883 *hunk_index = i;
884 return 1;
887 static void reassemble_patch(struct add_p_state *s,
888 struct file_diff *file_diff, int use_all,
889 struct strbuf *out)
891 struct hunk *hunk;
892 size_t save_len = s->plain.len, i;
893 ssize_t delta = 0;
895 render_diff_header(s, file_diff, 0, out);
897 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
898 struct hunk merged = { 0 };
900 hunk = file_diff->hunk + i;
901 if (!use_all && hunk->use != USE_HUNK)
902 delta += hunk->header.old_count
903 - hunk->header.new_count;
904 else {
905 /* merge overlapping hunks into a temporary hunk */
906 if (merge_hunks(s, file_diff, &i, use_all, &merged))
907 hunk = &merged;
909 render_hunk(s, hunk, delta, 0, out);
912 * In case `merge_hunks()` used `plain` as a scratch
913 * pad (this happens when an edited hunk had to be
914 * coalesced with another hunk).
916 strbuf_setlen(&s->plain, save_len);
918 delta += hunk->delta;
923 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
924 size_t hunk_index)
926 int colored = !!s->colored.len, first = 1;
927 struct hunk *hunk = file_diff->hunk + hunk_index;
928 size_t splittable_into;
929 size_t end, colored_end, current, colored_current = 0, context_line_count;
930 struct hunk_header remaining, *header;
931 char marker, ch;
933 if (hunk_index >= file_diff->hunk_nr)
934 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
935 (int)hunk_index, (int)file_diff->hunk_nr);
937 if (hunk->splittable_into < 2)
938 return 0;
939 splittable_into = hunk->splittable_into;
941 end = hunk->end;
942 colored_end = hunk->colored_end;
944 remaining = hunk->header;
946 file_diff->hunk_nr += splittable_into - 1;
947 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
948 if (hunk_index + splittable_into < file_diff->hunk_nr)
949 memmove(file_diff->hunk + hunk_index + splittable_into,
950 file_diff->hunk + hunk_index + 1,
951 (file_diff->hunk_nr - hunk_index - splittable_into)
952 * sizeof(*hunk));
953 hunk = file_diff->hunk + hunk_index;
954 hunk->splittable_into = 1;
955 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
957 header = &hunk->header;
958 header->old_count = header->new_count = 0;
960 current = hunk->start;
961 if (colored)
962 colored_current = hunk->colored_start;
963 marker = '\0';
964 context_line_count = 0;
966 while (splittable_into > 1) {
967 ch = normalize_marker(&s->plain.buf[current]);
969 if (!ch)
970 BUG("buffer overrun while splitting hunks");
973 * Is this the first context line after a chain of +/- lines?
974 * Then record the start of the next split hunk.
976 if ((marker == '-' || marker == '+') && ch == ' ') {
977 first = 0;
978 hunk[1].start = current;
979 if (colored)
980 hunk[1].colored_start = colored_current;
981 context_line_count = 0;
985 * Was the previous line a +/- one? Alternatively, is this the
986 * first line (and not a +/- one)?
988 * Then just increment the appropriate counter and continue
989 * with the next line.
991 if (marker != ' ' || (ch != '-' && ch != '+')) {
992 next_hunk_line:
993 /* Comment lines are attached to the previous line */
994 if (ch == '\\')
995 ch = marker ? marker : ' ';
997 /* current hunk not done yet */
998 if (ch == ' ')
999 context_line_count++;
1000 else if (ch == '-')
1001 header->old_count++;
1002 else if (ch == '+')
1003 header->new_count++;
1004 else
1005 BUG("unhandled diff marker: '%c'", ch);
1006 marker = ch;
1007 current = find_next_line(&s->plain, current);
1008 if (colored)
1009 colored_current =
1010 find_next_line(&s->colored,
1011 colored_current);
1012 continue;
1016 * We got us the start of a new hunk!
1018 * This is a context line, so it is shared with the previous
1019 * hunk, if any.
1022 if (first) {
1023 if (header->old_count || header->new_count)
1024 BUG("counts are off: %d/%d",
1025 (int)header->old_count,
1026 (int)header->new_count);
1028 header->old_count = context_line_count;
1029 header->new_count = context_line_count;
1030 context_line_count = 0;
1031 first = 0;
1032 goto next_hunk_line;
1035 remaining.old_offset += header->old_count;
1036 remaining.old_count -= header->old_count;
1037 remaining.new_offset += header->new_count;
1038 remaining.new_count -= header->new_count;
1040 /* initialize next hunk header's offsets */
1041 hunk[1].header.old_offset =
1042 header->old_offset + header->old_count;
1043 hunk[1].header.new_offset =
1044 header->new_offset + header->new_count;
1046 /* add one split hunk */
1047 header->old_count += context_line_count;
1048 header->new_count += context_line_count;
1050 hunk->end = current;
1051 if (colored)
1052 hunk->colored_end = colored_current;
1054 hunk++;
1055 hunk->splittable_into = 1;
1056 hunk->use = hunk[-1].use;
1057 header = &hunk->header;
1059 header->old_count = header->new_count = context_line_count;
1060 context_line_count = 0;
1062 splittable_into--;
1063 marker = ch;
1066 /* last hunk simply gets the rest */
1067 if (header->old_offset != remaining.old_offset)
1068 BUG("miscounted old_offset: %lu != %lu",
1069 header->old_offset, remaining.old_offset);
1070 if (header->new_offset != remaining.new_offset)
1071 BUG("miscounted new_offset: %lu != %lu",
1072 header->new_offset, remaining.new_offset);
1073 header->old_count = remaining.old_count;
1074 header->new_count = remaining.new_count;
1075 hunk->end = end;
1076 if (colored)
1077 hunk->colored_end = colored_end;
1079 return 0;
1082 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1084 const char *plain = s->plain.buf;
1085 size_t current, eol, next;
1087 if (!s->colored.len)
1088 return;
1090 hunk->colored_start = s->colored.len;
1091 for (current = hunk->start; current < hunk->end; ) {
1092 for (eol = current; eol < hunk->end; eol++)
1093 if (plain[eol] == '\n')
1094 break;
1095 next = eol + (eol < hunk->end);
1096 if (eol > current && plain[eol - 1] == '\r')
1097 eol--;
1099 strbuf_addstr(&s->colored,
1100 plain[current] == '-' ?
1101 s->s.file_old_color :
1102 plain[current] == '+' ?
1103 s->s.file_new_color :
1104 s->s.context_color);
1105 strbuf_add(&s->colored, plain + current, eol - current);
1106 strbuf_addstr(&s->colored, s->s.reset_color);
1107 if (next > eol)
1108 strbuf_add(&s->colored, plain + eol, next - eol);
1109 current = next;
1111 hunk->colored_end = s->colored.len;
1114 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1116 size_t i;
1118 strbuf_reset(&s->buf);
1119 strbuf_commented_addf(&s->buf, comment_line_str,
1120 _("Manual hunk edit mode -- see bottom for "
1121 "a quick guide.\n"));
1122 render_hunk(s, hunk, 0, 0, &s->buf);
1123 strbuf_commented_addf(&s->buf, comment_line_str,
1124 _("---\n"
1125 "To remove '%c' lines, make them ' ' lines "
1126 "(context).\n"
1127 "To remove '%c' lines, delete them.\n"
1128 "Lines starting with %s will be removed.\n"),
1129 s->mode->is_reverse ? '+' : '-',
1130 s->mode->is_reverse ? '-' : '+',
1131 comment_line_str);
1132 strbuf_commented_addf(&s->buf, comment_line_str, "%s",
1133 _(s->mode->edit_hunk_hint));
1135 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1136 * messages.
1138 strbuf_commented_addf(&s->buf, comment_line_str,
1139 _("If it does not apply cleanly, you will be "
1140 "given an opportunity to\n"
1141 "edit again. If all lines of the hunk are "
1142 "removed, then the edit is\n"
1143 "aborted and the hunk is left unchanged.\n"));
1145 if (strbuf_edit_interactively(the_repository, &s->buf,
1146 "addp-hunk-edit.diff", NULL) < 0)
1147 return -1;
1149 /* strip out commented lines */
1150 hunk->start = s->plain.len;
1151 for (i = 0; i < s->buf.len; ) {
1152 size_t next = find_next_line(&s->buf, i);
1154 if (!starts_with(s->buf.buf + i, comment_line_str))
1155 strbuf_add(&s->plain, s->buf.buf + i, next - i);
1156 i = next;
1159 hunk->end = s->plain.len;
1160 if (hunk->end == hunk->start)
1161 /* The user aborted editing by deleting everything */
1162 return 0;
1164 recolor_hunk(s, hunk);
1167 * If the hunk header is intact, parse it, otherwise simply use the
1168 * hunk header prior to editing (which will adjust `hunk->start` to
1169 * skip the hunk header).
1171 if (s->plain.buf[hunk->start] == '@' &&
1172 parse_hunk_header(s, hunk) < 0)
1173 return error(_("could not parse hunk header"));
1175 return 1;
1178 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1179 size_t orig_old_count, size_t orig_new_count)
1181 struct hunk_header *header = &hunk->header;
1182 size_t i;
1184 header->old_count = header->new_count = 0;
1185 for (i = hunk->start; i < hunk->end; ) {
1186 switch(normalize_marker(&s->plain.buf[i])) {
1187 case '-':
1188 header->old_count++;
1189 break;
1190 case '+':
1191 header->new_count++;
1192 break;
1193 case ' ':
1194 header->old_count++;
1195 header->new_count++;
1196 break;
1199 i = find_next_line(&s->plain, i);
1202 return orig_old_count - orig_new_count
1203 - header->old_count + header->new_count;
1206 static int run_apply_check(struct add_p_state *s,
1207 struct file_diff *file_diff)
1209 struct child_process cp = CHILD_PROCESS_INIT;
1211 strbuf_reset(&s->buf);
1212 reassemble_patch(s, file_diff, 1, &s->buf);
1214 setup_child_process(s, &cp,
1215 "apply", "--check", NULL);
1216 strvec_pushv(&cp.args, s->mode->apply_check_args);
1217 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1218 return error(_("'git apply --cached' failed"));
1220 return 0;
1223 static int read_single_character(struct add_p_state *s)
1225 if (s->s.use_single_key) {
1226 int res = read_key_without_echo(&s->answer);
1227 printf("%s\n", res == EOF ? "" : s->answer.buf);
1228 return res;
1231 if (git_read_line_interactively(&s->answer) == EOF)
1232 return EOF;
1233 return 0;
1236 static int prompt_yesno(struct add_p_state *s, const char *prompt)
1238 for (;;) {
1239 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1240 fflush(stdout);
1241 if (read_single_character(s) == EOF)
1242 return -1;
1243 /* do not limit to 1-byte input to allow 'no' etc. */
1244 switch (tolower(s->answer.buf[0])) {
1245 case 'n': return 0;
1246 case 'y': return 1;
1251 static int edit_hunk_loop(struct add_p_state *s,
1252 struct file_diff *file_diff, struct hunk *hunk)
1254 size_t plain_len = s->plain.len, colored_len = s->colored.len;
1255 struct hunk backup;
1257 backup = *hunk;
1259 for (;;) {
1260 int res = edit_hunk_manually(s, hunk);
1261 if (res == 0) {
1262 /* abandoned */
1263 *hunk = backup;
1264 return -1;
1267 if (res > 0) {
1268 hunk->delta +=
1269 recount_edited_hunk(s, hunk,
1270 backup.header.old_count,
1271 backup.header.new_count);
1272 if (!run_apply_check(s, file_diff))
1273 return 0;
1276 /* Drop edits (they were appended to s->plain) */
1277 strbuf_setlen(&s->plain, plain_len);
1278 strbuf_setlen(&s->colored, colored_len);
1279 *hunk = backup;
1282 * TRANSLATORS: do not translate [y/n]
1283 * The program will only accept that input at this point.
1284 * Consider translating (saying "no" discards!) as
1285 * (saying "n" for "no" discards!) if the translation
1286 * of the word "no" does not start with n.
1288 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1289 "Edit again (saying \"no\" discards!) "
1290 "[y/n]? "));
1291 if (res < 1)
1292 return -1;
1296 static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1297 int is_reverse)
1299 const char *reverse = is_reverse ? "-R" : NULL;
1300 struct child_process check_index = CHILD_PROCESS_INIT;
1301 struct child_process check_worktree = CHILD_PROCESS_INIT;
1302 struct child_process apply_index = CHILD_PROCESS_INIT;
1303 struct child_process apply_worktree = CHILD_PROCESS_INIT;
1304 int applies_index, applies_worktree;
1306 setup_child_process(s, &check_index,
1307 "apply", "--cached", "--check", reverse, NULL);
1308 applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1309 NULL, 0, NULL, 0);
1311 setup_child_process(s, &check_worktree,
1312 "apply", "--check", reverse, NULL);
1313 applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1314 NULL, 0, NULL, 0);
1316 if (applies_worktree && applies_index) {
1317 setup_child_process(s, &apply_index,
1318 "apply", "--cached", reverse, NULL);
1319 pipe_command(&apply_index, diff->buf, diff->len,
1320 NULL, 0, NULL, 0);
1322 setup_child_process(s, &apply_worktree,
1323 "apply", reverse, NULL);
1324 pipe_command(&apply_worktree, diff->buf, diff->len,
1325 NULL, 0, NULL, 0);
1327 return 1;
1330 if (!applies_index) {
1331 err(s, _("The selected hunks do not apply to the index!"));
1332 if (prompt_yesno(s, _("Apply them to the worktree "
1333 "anyway? ")) > 0) {
1334 setup_child_process(s, &apply_worktree,
1335 "apply", reverse, NULL);
1336 return pipe_command(&apply_worktree, diff->buf,
1337 diff->len, NULL, 0, NULL, 0);
1339 err(s, _("Nothing was applied.\n"));
1340 } else
1341 /* As a last resort, show the diff to the user */
1342 fwrite(diff->buf, diff->len, 1, stdout);
1344 return 0;
1347 #define SUMMARY_HEADER_WIDTH 20
1348 #define SUMMARY_LINE_WIDTH 80
1349 static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1350 struct strbuf *out)
1352 struct hunk_header *header = &hunk->header;
1353 struct strbuf *plain = &s->plain;
1354 size_t len = out->len, i;
1356 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1357 header->old_offset, header->old_count,
1358 header->new_offset, header->new_count);
1359 if (out->len - len < SUMMARY_HEADER_WIDTH)
1360 strbuf_addchars(out, ' ',
1361 SUMMARY_HEADER_WIDTH + len - out->len);
1362 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1363 if (plain->buf[i] != ' ')
1364 break;
1365 if (i < hunk->end)
1366 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1367 if (out->len - len > SUMMARY_LINE_WIDTH)
1368 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1369 strbuf_complete_line(out);
1372 #define DISPLAY_HUNKS_LINES 20
1373 static size_t display_hunks(struct add_p_state *s,
1374 struct file_diff *file_diff, size_t start_index)
1376 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1378 if (end_index > file_diff->hunk_nr)
1379 end_index = file_diff->hunk_nr;
1381 while (start_index < end_index) {
1382 struct hunk *hunk = file_diff->hunk + start_index++;
1384 strbuf_reset(&s->buf);
1385 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1386 : hunk->use == SKIP_HUNK ? '-' : ' ',
1387 (int)start_index);
1388 summarize_hunk(s, hunk, &s->buf);
1389 fputs(s->buf.buf, stdout);
1392 return end_index;
1395 static const char help_patch_remainder[] =
1396 N_("j - leave this hunk undecided, see next undecided hunk\n"
1397 "J - leave this hunk undecided, see next hunk\n"
1398 "k - leave this hunk undecided, see previous undecided hunk\n"
1399 "K - leave this hunk undecided, see previous hunk\n"
1400 "g - select a hunk to go to\n"
1401 "/ - search for a hunk matching the given regex\n"
1402 "s - split the current hunk into smaller hunks\n"
1403 "e - manually edit the current hunk\n"
1404 "p - print the current hunk, 'P' to use the pager\n"
1405 "? - print help\n");
1407 static int patch_update_file(struct add_p_state *s,
1408 struct file_diff *file_diff)
1410 size_t hunk_index = 0;
1411 ssize_t i, undecided_previous, undecided_next, rendered_hunk_index = -1;
1412 struct hunk *hunk;
1413 char ch;
1414 struct child_process cp = CHILD_PROCESS_INIT;
1415 int colored = !!s->colored.len, quit = 0, use_pager = 0;
1416 enum prompt_mode_type prompt_mode_type;
1417 enum {
1418 ALLOW_GOTO_PREVIOUS_HUNK = 1 << 0,
1419 ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK = 1 << 1,
1420 ALLOW_GOTO_NEXT_HUNK = 1 << 2,
1421 ALLOW_GOTO_NEXT_UNDECIDED_HUNK = 1 << 3,
1422 ALLOW_SEARCH_AND_GOTO = 1 << 4,
1423 ALLOW_SPLIT = 1 << 5,
1424 ALLOW_EDIT = 1 << 6
1425 } permitted = 0;
1427 /* Empty added files have no hunks */
1428 if (!file_diff->hunk_nr && !file_diff->added)
1429 return 0;
1431 strbuf_reset(&s->buf);
1432 render_diff_header(s, file_diff, colored, &s->buf);
1433 fputs(s->buf.buf, stdout);
1434 for (;;) {
1435 if (hunk_index >= file_diff->hunk_nr)
1436 hunk_index = 0;
1437 hunk = file_diff->hunk_nr
1438 ? file_diff->hunk + hunk_index
1439 : &file_diff->head;
1440 undecided_previous = -1;
1441 undecided_next = -1;
1443 if (file_diff->hunk_nr) {
1444 for (i = hunk_index - 1; i >= 0; i--)
1445 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1446 undecided_previous = i;
1447 break;
1450 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1451 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1452 undecided_next = i;
1453 break;
1457 /* Everything decided? */
1458 if (undecided_previous < 0 && undecided_next < 0 &&
1459 hunk->use != UNDECIDED_HUNK)
1460 break;
1462 strbuf_reset(&s->buf);
1463 if (file_diff->hunk_nr) {
1464 if (rendered_hunk_index != hunk_index) {
1465 if (use_pager) {
1466 setup_pager();
1467 sigchain_push(SIGPIPE, SIG_IGN);
1469 render_hunk(s, hunk, 0, colored, &s->buf);
1470 fputs(s->buf.buf, stdout);
1471 rendered_hunk_index = hunk_index;
1472 if (use_pager) {
1473 sigchain_pop(SIGPIPE);
1474 wait_for_pager();
1475 use_pager = 0;
1479 strbuf_reset(&s->buf);
1480 if (undecided_previous >= 0) {
1481 permitted |= ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK;
1482 strbuf_addstr(&s->buf, ",k");
1484 if (hunk_index) {
1485 permitted |= ALLOW_GOTO_PREVIOUS_HUNK;
1486 strbuf_addstr(&s->buf, ",K");
1488 if (undecided_next >= 0) {
1489 permitted |= ALLOW_GOTO_NEXT_UNDECIDED_HUNK;
1490 strbuf_addstr(&s->buf, ",j");
1492 if (hunk_index + 1 < file_diff->hunk_nr) {
1493 permitted |= ALLOW_GOTO_NEXT_HUNK;
1494 strbuf_addstr(&s->buf, ",J");
1496 if (file_diff->hunk_nr > 1) {
1497 permitted |= ALLOW_SEARCH_AND_GOTO;
1498 strbuf_addstr(&s->buf, ",g,/");
1500 if (hunk->splittable_into > 1) {
1501 permitted |= ALLOW_SPLIT;
1502 strbuf_addstr(&s->buf, ",s");
1504 if (hunk_index + 1 > file_diff->mode_change &&
1505 !file_diff->deleted) {
1506 permitted |= ALLOW_EDIT;
1507 strbuf_addstr(&s->buf, ",e");
1509 strbuf_addstr(&s->buf, ",p");
1511 if (file_diff->deleted)
1512 prompt_mode_type = PROMPT_DELETION;
1513 else if (file_diff->added)
1514 prompt_mode_type = PROMPT_ADDITION;
1515 else if (file_diff->mode_change && !hunk_index)
1516 prompt_mode_type = PROMPT_MODE_CHANGE;
1517 else
1518 prompt_mode_type = PROMPT_HUNK;
1520 printf("%s(%"PRIuMAX"/%"PRIuMAX") ", s->s.prompt_color,
1521 (uintmax_t)hunk_index + 1,
1522 (uintmax_t)(file_diff->hunk_nr
1523 ? file_diff->hunk_nr
1524 : 1));
1525 printf(_(s->mode->prompt_mode[prompt_mode_type]),
1526 s->buf.buf);
1527 if (*s->s.reset_color)
1528 fputs(s->s.reset_color, stdout);
1529 fflush(stdout);
1530 if (read_single_character(s) == EOF)
1531 break;
1533 if (!s->answer.len)
1534 continue;
1535 ch = tolower(s->answer.buf[0]);
1537 /* 'g' takes a hunk number and '/' takes a regexp */
1538 if (s->answer.len != 1 && (ch != 'g' && ch != '/')) {
1539 err(s, _("Only one letter is expected, got '%s'"), s->answer.buf);
1540 continue;
1542 if (ch == 'y') {
1543 hunk->use = USE_HUNK;
1544 soft_increment:
1545 hunk_index = undecided_next < 0 ?
1546 file_diff->hunk_nr : undecided_next;
1547 } else if (ch == 'n') {
1548 hunk->use = SKIP_HUNK;
1549 goto soft_increment;
1550 } else if (ch == 'a') {
1551 if (file_diff->hunk_nr) {
1552 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1553 hunk = file_diff->hunk + hunk_index;
1554 if (hunk->use == UNDECIDED_HUNK)
1555 hunk->use = USE_HUNK;
1557 } else if (hunk->use == UNDECIDED_HUNK) {
1558 hunk->use = USE_HUNK;
1560 } else if (ch == 'd' || ch == 'q') {
1561 if (file_diff->hunk_nr) {
1562 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1563 hunk = file_diff->hunk + hunk_index;
1564 if (hunk->use == UNDECIDED_HUNK)
1565 hunk->use = SKIP_HUNK;
1567 } else if (hunk->use == UNDECIDED_HUNK) {
1568 hunk->use = SKIP_HUNK;
1570 if (ch == 'q') {
1571 quit = 1;
1572 break;
1574 } else if (s->answer.buf[0] == 'K') {
1575 if (permitted & ALLOW_GOTO_PREVIOUS_HUNK)
1576 hunk_index--;
1577 else
1578 err(s, _("No previous hunk"));
1579 } else if (s->answer.buf[0] == 'J') {
1580 if (permitted & ALLOW_GOTO_NEXT_HUNK)
1581 hunk_index++;
1582 else
1583 err(s, _("No next hunk"));
1584 } else if (s->answer.buf[0] == 'k') {
1585 if (permitted & ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK)
1586 hunk_index = undecided_previous;
1587 else
1588 err(s, _("No previous hunk"));
1589 } else if (s->answer.buf[0] == 'j') {
1590 if (permitted & ALLOW_GOTO_NEXT_UNDECIDED_HUNK)
1591 hunk_index = undecided_next;
1592 else
1593 err(s, _("No next hunk"));
1594 } else if (s->answer.buf[0] == 'g') {
1595 char *pend;
1596 unsigned long response;
1598 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1599 err(s, _("No other hunks to goto"));
1600 continue;
1602 strbuf_remove(&s->answer, 0, 1);
1603 strbuf_trim(&s->answer);
1604 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1605 if (i < (int)file_diff->mode_change)
1606 i = file_diff->mode_change;
1607 while (s->answer.len == 0) {
1608 i = display_hunks(s, file_diff, i);
1609 printf("%s", i < file_diff->hunk_nr ?
1610 _("go to which hunk (<ret> to see "
1611 "more)? ") : _("go to which hunk? "));
1612 fflush(stdout);
1613 if (strbuf_getline(&s->answer,
1614 stdin) == EOF)
1615 break;
1616 strbuf_trim_trailing_newline(&s->answer);
1619 strbuf_trim(&s->answer);
1620 response = strtoul(s->answer.buf, &pend, 10);
1621 if (*pend || pend == s->answer.buf)
1622 err(s, _("Invalid number: '%s'"),
1623 s->answer.buf);
1624 else if (0 < response && response <= file_diff->hunk_nr)
1625 hunk_index = response - 1;
1626 else
1627 err(s, Q_("Sorry, only %d hunk available.",
1628 "Sorry, only %d hunks available.",
1629 file_diff->hunk_nr),
1630 (int)file_diff->hunk_nr);
1631 } else if (s->answer.buf[0] == '/') {
1632 regex_t regex;
1633 int ret;
1635 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1636 err(s, _("No other hunks to search"));
1637 continue;
1639 strbuf_remove(&s->answer, 0, 1);
1640 strbuf_trim_trailing_newline(&s->answer);
1641 if (s->answer.len == 0) {
1642 printf("%s", _("search for regex? "));
1643 fflush(stdout);
1644 if (strbuf_getline(&s->answer,
1645 stdin) == EOF)
1646 break;
1647 strbuf_trim_trailing_newline(&s->answer);
1648 if (s->answer.len == 0)
1649 continue;
1651 ret = regcomp(&regex, s->answer.buf,
1652 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1653 if (ret) {
1654 char errbuf[1024];
1656 regerror(ret, &regex, errbuf, sizeof(errbuf));
1657 err(s, _("Malformed search regexp %s: %s"),
1658 s->answer.buf, errbuf);
1659 continue;
1661 i = hunk_index;
1662 for (;;) {
1663 /* render the hunk into a scratch buffer */
1664 render_hunk(s, file_diff->hunk + i, 0, 0,
1665 &s->buf);
1666 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1667 != REG_NOMATCH)
1668 break;
1669 i++;
1670 if (i == file_diff->hunk_nr)
1671 i = 0;
1672 if (i != hunk_index)
1673 continue;
1674 err(s, _("No hunk matches the given pattern"));
1675 break;
1677 regfree(&regex);
1678 hunk_index = i;
1679 } else if (s->answer.buf[0] == 's') {
1680 size_t splittable_into = hunk->splittable_into;
1681 if (!(permitted & ALLOW_SPLIT)) {
1682 err(s, _("Sorry, cannot split this hunk"));
1683 } else if (!split_hunk(s, file_diff,
1684 hunk - file_diff->hunk)) {
1685 color_fprintf_ln(stdout, s->s.header_color,
1686 _("Split into %d hunks."),
1687 (int)splittable_into);
1688 rendered_hunk_index = -1;
1690 } else if (s->answer.buf[0] == 'e') {
1691 if (!(permitted & ALLOW_EDIT))
1692 err(s, _("Sorry, cannot edit this hunk"));
1693 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1694 hunk->use = USE_HUNK;
1695 goto soft_increment;
1697 } else if (ch == 'p') {
1698 rendered_hunk_index = -1;
1699 use_pager = (s->answer.buf[0] == 'P') ? 1 : 0;
1700 } else if (s->answer.buf[0] == '?') {
1701 const char *p = _(help_patch_remainder), *eol = p;
1703 color_fprintf(stdout, s->s.help_color, "%s",
1704 _(s->mode->help_patch_text));
1707 * Show only those lines of the remainder that are
1708 * actually applicable with the current hunk.
1710 for (; *p; p = eol + (*eol == '\n')) {
1711 eol = strchrnul(p, '\n');
1714 * `s->buf` still contains the part of the
1715 * commands shown in the prompt that are not
1716 * always available.
1718 if (*p != '?' && !strchr(s->buf.buf, *p))
1719 continue;
1721 color_fprintf_ln(stdout, s->s.help_color,
1722 "%.*s", (int)(eol - p), p);
1724 } else {
1725 err(s, _("Unknown command '%s' (use '?' for help)"),
1726 s->answer.buf);
1730 /* Any hunk to be used? */
1731 for (i = 0; i < file_diff->hunk_nr; i++)
1732 if (file_diff->hunk[i].use == USE_HUNK)
1733 break;
1735 if (i < file_diff->hunk_nr ||
1736 (!file_diff->hunk_nr && file_diff->head.use == USE_HUNK)) {
1737 /* At least one hunk selected: apply */
1738 strbuf_reset(&s->buf);
1739 reassemble_patch(s, file_diff, 0, &s->buf);
1741 discard_index(s->s.r->index);
1742 if (s->mode->apply_for_checkout)
1743 apply_for_checkout(s, &s->buf,
1744 s->mode->is_reverse);
1745 else {
1746 setup_child_process(s, &cp, "apply", NULL);
1747 strvec_pushv(&cp.args, s->mode->apply_args);
1748 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1749 NULL, 0, NULL, 0))
1750 error(_("'git apply' failed"));
1752 if (repo_read_index(s->s.r) >= 0)
1753 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
1754 1, NULL, NULL, NULL);
1757 putchar('\n');
1758 return quit;
1761 int run_add_p(struct repository *r, enum add_p_mode mode,
1762 const char *revision, const struct pathspec *ps)
1764 struct add_p_state s = {
1765 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1767 size_t i, binary_count = 0;
1769 init_add_i_state(&s.s, r);
1771 if (mode == ADD_P_STASH)
1772 s.mode = &patch_mode_stash;
1773 else if (mode == ADD_P_RESET) {
1774 if (!revision || !strcmp(revision, "HEAD"))
1775 s.mode = &patch_mode_reset_head;
1776 else
1777 s.mode = &patch_mode_reset_nothead;
1778 } else if (mode == ADD_P_CHECKOUT) {
1779 if (!revision)
1780 s.mode = &patch_mode_checkout_index;
1781 else if (!strcmp(revision, "HEAD"))
1782 s.mode = &patch_mode_checkout_head;
1783 else
1784 s.mode = &patch_mode_checkout_nothead;
1785 } else if (mode == ADD_P_WORKTREE) {
1786 if (!revision)
1787 s.mode = &patch_mode_checkout_index;
1788 else if (!strcmp(revision, "HEAD"))
1789 s.mode = &patch_mode_worktree_head;
1790 else
1791 s.mode = &patch_mode_worktree_nothead;
1792 } else
1793 s.mode = &patch_mode_add;
1794 s.revision = revision;
1796 discard_index(r->index);
1797 if (repo_read_index(r) < 0 ||
1798 (!s.mode->index_only &&
1799 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1800 NULL, NULL, NULL) < 0) ||
1801 parse_diff(&s, ps) < 0) {
1802 add_p_state_clear(&s);
1803 return -1;
1806 for (i = 0; i < s.file_diff_nr; i++)
1807 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1808 binary_count++;
1809 else if (patch_update_file(&s, s.file_diff + i))
1810 break;
1812 if (s.file_diff_nr == 0)
1813 err(&s, _("No changes."));
1814 else if (binary_count == s.file_diff_nr)
1815 err(&s, _("Only binary files changed."));
1817 add_p_state_clear(&s);
1818 return 0;