Merge branch 'jk/ci-linux32-update' into maint-2.46
[git/gitster.git] / add-patch.c
blob46f6bddfe5cb75922fece4c9319899377cf2b7fb
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 /* Empty context lines may omit the leading ' ' */
406 static int normalize_marker(const char *p)
408 return p[0] == '\n' || (p[0] == '\r' && p[1] == '\n') ? ' ' : p[0];
411 static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
413 struct strvec args = STRVEC_INIT;
414 const char *diff_algorithm = s->s.interactive_diff_algorithm;
415 struct strbuf *plain = &s->plain, *colored = NULL;
416 struct child_process cp = CHILD_PROCESS_INIT;
417 char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
418 size_t file_diff_alloc = 0, i, color_arg_index;
419 struct file_diff *file_diff = NULL;
420 struct hunk *hunk = NULL;
421 int res;
423 strvec_pushv(&args, s->mode->diff_cmd);
424 if (diff_algorithm)
425 strvec_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
426 if (s->revision) {
427 struct object_id oid;
428 strvec_push(&args,
429 /* could be on an unborn branch */
430 !strcmp("HEAD", s->revision) &&
431 repo_get_oid(the_repository, "HEAD", &oid) ?
432 empty_tree_oid_hex(the_repository->hash_algo) : s->revision);
434 color_arg_index = args.nr;
435 /* Use `--no-color` explicitly, just in case `diff.color = always`. */
436 strvec_pushl(&args, "--no-color", "--ignore-submodules=dirty", "-p",
437 "--", NULL);
438 for (i = 0; i < ps->nr; i++)
439 strvec_push(&args, ps->items[i].original);
441 setup_child_process(s, &cp, NULL);
442 strvec_pushv(&cp.args, args.v);
443 res = capture_command(&cp, plain, 0);
444 if (res) {
445 strvec_clear(&args);
446 return error(_("could not parse diff"));
448 if (!plain->len) {
449 strvec_clear(&args);
450 return 0;
452 strbuf_complete_line(plain);
454 if (want_color_fd(1, -1)) {
455 struct child_process colored_cp = CHILD_PROCESS_INIT;
456 const char *diff_filter = s->s.interactive_diff_filter;
458 setup_child_process(s, &colored_cp, NULL);
459 xsnprintf((char *)args.v[color_arg_index], 8, "--color");
460 strvec_pushv(&colored_cp.args, args.v);
461 colored = &s->colored;
462 res = capture_command(&colored_cp, colored, 0);
463 strvec_clear(&args);
464 if (res)
465 return error(_("could not parse colored diff"));
467 if (diff_filter) {
468 struct child_process filter_cp = CHILD_PROCESS_INIT;
470 setup_child_process(s, &filter_cp,
471 diff_filter, NULL);
472 filter_cp.git_cmd = 0;
473 filter_cp.use_shell = 1;
474 strbuf_reset(&s->buf);
475 if (pipe_command(&filter_cp,
476 colored->buf, colored->len,
477 &s->buf, colored->len,
478 NULL, 0) < 0)
479 return error(_("failed to run '%s'"),
480 diff_filter);
481 strbuf_swap(colored, &s->buf);
484 strbuf_complete_line(colored);
485 colored_p = colored->buf;
486 colored_pend = colored_p + colored->len;
488 strvec_clear(&args);
490 /* parse files and hunks */
491 p = plain->buf;
492 pend = p + plain->len;
493 while (p != pend) {
494 char *eol = memchr(p, '\n', pend - p);
495 const char *deleted = NULL, *mode_change = NULL;
496 char ch = normalize_marker(p);
498 if (!eol)
499 eol = pend;
501 if (starts_with(p, "diff ") ||
502 starts_with(p, "* Unmerged path ")) {
503 complete_file(marker, hunk);
504 ALLOC_GROW_BY(s->file_diff, s->file_diff_nr, 1,
505 file_diff_alloc);
506 file_diff = s->file_diff + s->file_diff_nr - 1;
507 hunk = &file_diff->head;
508 hunk->start = p - plain->buf;
509 if (colored_p)
510 hunk->colored_start = colored_p - colored->buf;
511 marker = '\0';
512 } else if (p == plain->buf)
513 BUG("diff starts with unexpected line:\n"
514 "%.*s\n", (int)(eol - p), p);
515 else if (file_diff->deleted)
516 ; /* keep the rest of the file in a single "hunk" */
517 else if (starts_with(p, "@@ ") ||
518 (hunk == &file_diff->head &&
519 (skip_prefix(p, "deleted file", &deleted)))) {
520 if (marker == '-' || marker == '+')
522 * Should not happen; previous hunk did not end
523 * in a context line? Handle it anyway.
525 hunk->splittable_into++;
527 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
528 file_diff->hunk_alloc);
529 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
531 hunk->start = p - plain->buf;
532 if (colored)
533 hunk->colored_start = colored_p - colored->buf;
535 if (deleted)
536 file_diff->deleted = 1;
537 else if (parse_hunk_header(s, hunk) < 0)
538 return -1;
541 * Start counting into how many hunks this one can be
542 * split
544 marker = ch;
545 } else if (hunk == &file_diff->head &&
546 starts_with(p, "new file")) {
547 file_diff->added = 1;
548 } else if (hunk == &file_diff->head &&
549 skip_prefix(p, "old mode ", &mode_change) &&
550 is_octal(mode_change, eol - mode_change)) {
551 if (file_diff->mode_change)
552 BUG("double mode change?\n\n%.*s",
553 (int)(eol - plain->buf), plain->buf);
554 if (file_diff->hunk_nr)
555 BUG("mode change in the middle?\n\n%.*s",
556 (int)(eol - plain->buf), plain->buf);
559 * Do *not* change `hunk`: the mode change pseudo-hunk
560 * is _part of_ the header "hunk".
562 file_diff->mode_change = 1;
563 ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
564 file_diff->hunk_alloc);
565 file_diff->hunk->start = p - plain->buf;
566 if (colored_p)
567 file_diff->hunk->colored_start =
568 colored_p - colored->buf;
569 } else if (hunk == &file_diff->head &&
570 skip_prefix(p, "new mode ", &mode_change) &&
571 is_octal(mode_change, eol - mode_change)) {
574 * Extend the "mode change" pseudo-hunk to include also
575 * the "new mode" line.
577 if (!file_diff->mode_change)
578 BUG("'new mode' without 'old mode'?\n\n%.*s",
579 (int)(eol - plain->buf), plain->buf);
580 if (file_diff->hunk_nr != 1)
581 BUG("mode change in the middle?\n\n%.*s",
582 (int)(eol - plain->buf), plain->buf);
583 if (p - plain->buf != file_diff->hunk->end)
584 BUG("'new mode' does not immediately follow "
585 "'old mode'?\n\n%.*s",
586 (int)(eol - plain->buf), plain->buf);
587 } else if (hunk == &file_diff->head &&
588 starts_with(p, "Binary files "))
589 file_diff->binary = 1;
591 if (!!file_diff->deleted + !!file_diff->added +
592 !!file_diff->mode_change > 1)
593 BUG("diff can only contain delete *or* add *or* a "
594 "mode change?!?\n%.*s",
595 (int)(eol - (plain->buf + file_diff->head.start)),
596 plain->buf + file_diff->head.start);
598 if ((marker == '-' || marker == '+') && ch == ' ')
599 hunk->splittable_into++;
600 if (marker && ch != '\\')
601 marker = ch;
603 p = eol == pend ? pend : eol + 1;
604 hunk->end = p - plain->buf;
606 if (colored) {
607 char *colored_eol = memchr(colored_p, '\n',
608 colored_pend - colored_p);
609 if (colored_eol)
610 colored_p = colored_eol + 1;
611 else if (p != pend)
612 /* non-colored has more lines? */
613 goto mismatched_output;
614 else if (colored_p == colored_pend)
615 /* last line has no matching colored one? */
616 goto mismatched_output;
617 else
618 colored_p = colored_pend;
620 hunk->colored_end = colored_p - colored->buf;
623 if (mode_change) {
624 if (file_diff->hunk_nr != 1)
625 BUG("mode change in hunk #%d???",
626 (int)file_diff->hunk_nr);
627 /* Adjust the end of the "mode change" pseudo-hunk */
628 file_diff->hunk->end = hunk->end;
629 if (colored)
630 file_diff->hunk->colored_end = hunk->colored_end;
633 complete_file(marker, hunk);
635 /* non-colored shorter than colored? */
636 if (colored_p != colored_pend) {
637 mismatched_output:
638 error(_("mismatched output from interactive.diffFilter"));
639 advise(_("Your filter must maintain a one-to-one correspondence\n"
640 "between its input and output lines."));
641 return -1;
644 return 0;
647 static size_t find_next_line(struct strbuf *sb, size_t offset)
649 char *eol;
651 if (offset >= sb->len)
652 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
653 (int)offset, (int)sb->len, sb->buf);
655 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
656 if (!eol)
657 return sb->len;
658 return eol - sb->buf + 1;
661 static void render_hunk(struct add_p_state *s, struct hunk *hunk,
662 ssize_t delta, int colored, struct strbuf *out)
664 struct hunk_header *header = &hunk->header;
666 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
668 * Generate the hunk header dynamically, except for special
669 * hunks (such as the diff header).
671 const char *p;
672 size_t len;
673 unsigned long old_offset = header->old_offset;
674 unsigned long new_offset = header->new_offset;
676 if (!colored) {
677 p = s->plain.buf + header->extra_start;
678 len = header->extra_end - header->extra_start;
679 } else if (header->suppress_colored_line_range) {
680 strbuf_add(out,
681 s->colored.buf + header->colored_extra_start,
682 header->colored_extra_end -
683 header->colored_extra_start);
685 strbuf_add(out, s->colored.buf + hunk->colored_start,
686 hunk->colored_end - hunk->colored_start);
687 return;
688 } else {
689 strbuf_addstr(out, s->s.fraginfo_color);
690 p = s->colored.buf + header->colored_extra_start;
691 len = header->colored_extra_end
692 - header->colored_extra_start;
695 if (s->mode->is_reverse)
696 old_offset -= delta;
697 else
698 new_offset += delta;
700 strbuf_addf(out, "@@ -%lu", old_offset);
701 if (header->old_count != 1)
702 strbuf_addf(out, ",%lu", header->old_count);
703 strbuf_addf(out, " +%lu", new_offset);
704 if (header->new_count != 1)
705 strbuf_addf(out, ",%lu", header->new_count);
706 strbuf_addstr(out, " @@");
708 if (len)
709 strbuf_add(out, p, len);
710 else if (colored)
711 strbuf_addf(out, "%s\n", s->s.reset_color);
712 else
713 strbuf_addch(out, '\n');
716 if (colored)
717 strbuf_add(out, s->colored.buf + hunk->colored_start,
718 hunk->colored_end - hunk->colored_start);
719 else
720 strbuf_add(out, s->plain.buf + hunk->start,
721 hunk->end - hunk->start);
724 static void render_diff_header(struct add_p_state *s,
725 struct file_diff *file_diff, int colored,
726 struct strbuf *out)
729 * If there was a mode change, the first hunk is a pseudo hunk that
730 * corresponds to the mode line in the header. If the user did not want
731 * to stage that "hunk", we actually have to cut it out from the header.
733 int skip_mode_change =
734 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
735 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
737 if (!skip_mode_change) {
738 render_hunk(s, head, 0, colored, out);
739 return;
742 if (colored) {
743 const char *p = s->colored.buf;
745 strbuf_add(out, p + head->colored_start,
746 first->colored_start - head->colored_start);
747 strbuf_add(out, p + first->colored_end,
748 head->colored_end - first->colored_end);
749 } else {
750 const char *p = s->plain.buf;
752 strbuf_add(out, p + head->start, first->start - head->start);
753 strbuf_add(out, p + first->end, head->end - first->end);
757 /* Coalesce hunks again that were split */
758 static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
759 size_t *hunk_index, int use_all, struct hunk *merged)
761 size_t i = *hunk_index, delta;
762 struct hunk *hunk = file_diff->hunk + i;
763 /* `header` corresponds to the merged hunk */
764 struct hunk_header *header = &merged->header, *next;
766 if (!use_all && hunk->use != USE_HUNK)
767 return 0;
769 *merged = *hunk;
770 /* We simply skip the colored part (if any) when merging hunks */
771 merged->colored_start = merged->colored_end = 0;
773 for (; i + 1 < file_diff->hunk_nr; i++) {
774 hunk++;
775 next = &hunk->header;
778 * Stop merging hunks when:
780 * - the hunk is not selected for use, or
781 * - the hunk does not overlap with the already-merged hunk(s)
783 if ((!use_all && hunk->use != USE_HUNK) ||
784 header->new_offset >= next->new_offset + merged->delta ||
785 header->new_offset + header->new_count
786 < next->new_offset + merged->delta)
787 break;
790 * If the hunks were not edited, and overlap, we can simply
791 * extend the line range.
793 if (merged->start < hunk->start && merged->end > hunk->start) {
794 merged->end = hunk->end;
795 merged->colored_end = hunk->colored_end;
796 delta = 0;
797 } else {
798 const char *plain = s->plain.buf;
799 size_t overlapping_line_count = header->new_offset
800 + header->new_count - merged->delta
801 - next->new_offset;
802 size_t overlap_end = hunk->start;
803 size_t overlap_start = overlap_end;
804 size_t overlap_next, len, j;
807 * One of the hunks was edited: the modified hunk was
808 * appended to the strbuf `s->plain`.
810 * Let's ensure that at least the last context line of
811 * the first hunk overlaps with the corresponding line
812 * of the second hunk, and then merge.
814 for (j = 0; j < overlapping_line_count; j++) {
815 overlap_next = find_next_line(&s->plain,
816 overlap_end);
818 if (overlap_next > hunk->end)
819 BUG("failed to find %d context lines "
820 "in:\n%.*s",
821 (int)overlapping_line_count,
822 (int)(hunk->end - hunk->start),
823 plain + hunk->start);
825 if (normalize_marker(&plain[overlap_end]) != ' ')
826 return error(_("expected context line "
827 "#%d in\n%.*s"),
828 (int)(j + 1),
829 (int)(hunk->end
830 - hunk->start),
831 plain + hunk->start);
833 overlap_start = overlap_end;
834 overlap_end = overlap_next;
836 len = overlap_end - overlap_start;
838 if (len > merged->end - merged->start ||
839 memcmp(plain + merged->end - len,
840 plain + overlap_start, len))
841 return error(_("hunks do not overlap:\n%.*s\n"
842 "\tdoes not end with:\n%.*s"),
843 (int)(merged->end - merged->start),
844 plain + merged->start,
845 (int)len, plain + overlap_start);
848 * Since the start-end ranges are not adjacent, we
849 * cannot simply take the union of the ranges. To
850 * address that, we temporarily append the union of the
851 * lines to the `plain` strbuf.
853 if (merged->end != s->plain.len) {
854 size_t start = s->plain.len;
856 strbuf_add(&s->plain, plain + merged->start,
857 merged->end - merged->start);
858 plain = s->plain.buf;
859 merged->start = start;
860 merged->end = s->plain.len;
863 strbuf_add(&s->plain,
864 plain + overlap_end,
865 hunk->end - overlap_end);
866 merged->end = s->plain.len;
867 merged->splittable_into += hunk->splittable_into;
868 delta = merged->delta;
869 merged->delta += hunk->delta;
872 header->old_count = next->old_offset + next->old_count
873 - header->old_offset;
874 header->new_count = next->new_offset + delta
875 + next->new_count - header->new_offset;
878 if (i == *hunk_index)
879 return 0;
881 *hunk_index = i;
882 return 1;
885 static void reassemble_patch(struct add_p_state *s,
886 struct file_diff *file_diff, int use_all,
887 struct strbuf *out)
889 struct hunk *hunk;
890 size_t save_len = s->plain.len, i;
891 ssize_t delta = 0;
893 render_diff_header(s, file_diff, 0, out);
895 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
896 struct hunk merged = { 0 };
898 hunk = file_diff->hunk + i;
899 if (!use_all && hunk->use != USE_HUNK)
900 delta += hunk->header.old_count
901 - hunk->header.new_count;
902 else {
903 /* merge overlapping hunks into a temporary hunk */
904 if (merge_hunks(s, file_diff, &i, use_all, &merged))
905 hunk = &merged;
907 render_hunk(s, hunk, delta, 0, out);
910 * In case `merge_hunks()` used `plain` as a scratch
911 * pad (this happens when an edited hunk had to be
912 * coalesced with another hunk).
914 strbuf_setlen(&s->plain, save_len);
916 delta += hunk->delta;
921 static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
922 size_t hunk_index)
924 int colored = !!s->colored.len, first = 1;
925 struct hunk *hunk = file_diff->hunk + hunk_index;
926 size_t splittable_into;
927 size_t end, colored_end, current, colored_current = 0, context_line_count;
928 struct hunk_header remaining, *header;
929 char marker, ch;
931 if (hunk_index >= file_diff->hunk_nr)
932 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
933 (int)hunk_index, (int)file_diff->hunk_nr);
935 if (hunk->splittable_into < 2)
936 return 0;
937 splittable_into = hunk->splittable_into;
939 end = hunk->end;
940 colored_end = hunk->colored_end;
942 remaining = hunk->header;
944 file_diff->hunk_nr += splittable_into - 1;
945 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
946 if (hunk_index + splittable_into < file_diff->hunk_nr)
947 memmove(file_diff->hunk + hunk_index + splittable_into,
948 file_diff->hunk + hunk_index + 1,
949 (file_diff->hunk_nr - hunk_index - splittable_into)
950 * sizeof(*hunk));
951 hunk = file_diff->hunk + hunk_index;
952 hunk->splittable_into = 1;
953 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
955 header = &hunk->header;
956 header->old_count = header->new_count = 0;
958 current = hunk->start;
959 if (colored)
960 colored_current = hunk->colored_start;
961 marker = '\0';
962 context_line_count = 0;
964 while (splittable_into > 1) {
965 ch = normalize_marker(&s->plain.buf[current]);
967 if (!ch)
968 BUG("buffer overrun while splitting hunks");
971 * Is this the first context line after a chain of +/- lines?
972 * Then record the start of the next split hunk.
974 if ((marker == '-' || marker == '+') && ch == ' ') {
975 first = 0;
976 hunk[1].start = current;
977 if (colored)
978 hunk[1].colored_start = colored_current;
979 context_line_count = 0;
983 * Was the previous line a +/- one? Alternatively, is this the
984 * first line (and not a +/- one)?
986 * Then just increment the appropriate counter and continue
987 * with the next line.
989 if (marker != ' ' || (ch != '-' && ch != '+')) {
990 next_hunk_line:
991 /* Comment lines are attached to the previous line */
992 if (ch == '\\')
993 ch = marker ? marker : ' ';
995 /* current hunk not done yet */
996 if (ch == ' ')
997 context_line_count++;
998 else if (ch == '-')
999 header->old_count++;
1000 else if (ch == '+')
1001 header->new_count++;
1002 else
1003 BUG("unhandled diff marker: '%c'", ch);
1004 marker = ch;
1005 current = find_next_line(&s->plain, current);
1006 if (colored)
1007 colored_current =
1008 find_next_line(&s->colored,
1009 colored_current);
1010 continue;
1014 * We got us the start of a new hunk!
1016 * This is a context line, so it is shared with the previous
1017 * hunk, if any.
1020 if (first) {
1021 if (header->old_count || header->new_count)
1022 BUG("counts are off: %d/%d",
1023 (int)header->old_count,
1024 (int)header->new_count);
1026 header->old_count = context_line_count;
1027 header->new_count = context_line_count;
1028 context_line_count = 0;
1029 first = 0;
1030 goto next_hunk_line;
1033 remaining.old_offset += header->old_count;
1034 remaining.old_count -= header->old_count;
1035 remaining.new_offset += header->new_count;
1036 remaining.new_count -= header->new_count;
1038 /* initialize next hunk header's offsets */
1039 hunk[1].header.old_offset =
1040 header->old_offset + header->old_count;
1041 hunk[1].header.new_offset =
1042 header->new_offset + header->new_count;
1044 /* add one split hunk */
1045 header->old_count += context_line_count;
1046 header->new_count += context_line_count;
1048 hunk->end = current;
1049 if (colored)
1050 hunk->colored_end = colored_current;
1052 hunk++;
1053 hunk->splittable_into = 1;
1054 hunk->use = hunk[-1].use;
1055 header = &hunk->header;
1057 header->old_count = header->new_count = context_line_count;
1058 context_line_count = 0;
1060 splittable_into--;
1061 marker = ch;
1064 /* last hunk simply gets the rest */
1065 if (header->old_offset != remaining.old_offset)
1066 BUG("miscounted old_offset: %lu != %lu",
1067 header->old_offset, remaining.old_offset);
1068 if (header->new_offset != remaining.new_offset)
1069 BUG("miscounted new_offset: %lu != %lu",
1070 header->new_offset, remaining.new_offset);
1071 header->old_count = remaining.old_count;
1072 header->new_count = remaining.new_count;
1073 hunk->end = end;
1074 if (colored)
1075 hunk->colored_end = colored_end;
1077 return 0;
1080 static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1082 const char *plain = s->plain.buf;
1083 size_t current, eol, next;
1085 if (!s->colored.len)
1086 return;
1088 hunk->colored_start = s->colored.len;
1089 for (current = hunk->start; current < hunk->end; ) {
1090 for (eol = current; eol < hunk->end; eol++)
1091 if (plain[eol] == '\n')
1092 break;
1093 next = eol + (eol < hunk->end);
1094 if (eol > current && plain[eol - 1] == '\r')
1095 eol--;
1097 strbuf_addstr(&s->colored,
1098 plain[current] == '-' ?
1099 s->s.file_old_color :
1100 plain[current] == '+' ?
1101 s->s.file_new_color :
1102 s->s.context_color);
1103 strbuf_add(&s->colored, plain + current, eol - current);
1104 strbuf_addstr(&s->colored, s->s.reset_color);
1105 if (next > eol)
1106 strbuf_add(&s->colored, plain + eol, next - eol);
1107 current = next;
1109 hunk->colored_end = s->colored.len;
1112 static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1114 size_t i;
1116 strbuf_reset(&s->buf);
1117 strbuf_commented_addf(&s->buf, comment_line_str,
1118 _("Manual hunk edit mode -- see bottom for "
1119 "a quick guide.\n"));
1120 render_hunk(s, hunk, 0, 0, &s->buf);
1121 strbuf_commented_addf(&s->buf, comment_line_str,
1122 _("---\n"
1123 "To remove '%c' lines, make them ' ' lines "
1124 "(context).\n"
1125 "To remove '%c' lines, delete them.\n"
1126 "Lines starting with %s will be removed.\n"),
1127 s->mode->is_reverse ? '+' : '-',
1128 s->mode->is_reverse ? '-' : '+',
1129 comment_line_str);
1130 strbuf_commented_addf(&s->buf, comment_line_str, "%s",
1131 _(s->mode->edit_hunk_hint));
1133 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1134 * messages.
1136 strbuf_commented_addf(&s->buf, comment_line_str,
1137 _("If it does not apply cleanly, you will be "
1138 "given an opportunity to\n"
1139 "edit again. If all lines of the hunk are "
1140 "removed, then the edit is\n"
1141 "aborted and the hunk is left unchanged.\n"));
1143 if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1144 return -1;
1146 /* strip out commented lines */
1147 hunk->start = s->plain.len;
1148 for (i = 0; i < s->buf.len; ) {
1149 size_t next = find_next_line(&s->buf, i);
1151 if (!starts_with(s->buf.buf + i, comment_line_str))
1152 strbuf_add(&s->plain, s->buf.buf + i, next - i);
1153 i = next;
1156 hunk->end = s->plain.len;
1157 if (hunk->end == hunk->start)
1158 /* The user aborted editing by deleting everything */
1159 return 0;
1161 recolor_hunk(s, hunk);
1164 * If the hunk header is intact, parse it, otherwise simply use the
1165 * hunk header prior to editing (which will adjust `hunk->start` to
1166 * skip the hunk header).
1168 if (s->plain.buf[hunk->start] == '@' &&
1169 parse_hunk_header(s, hunk) < 0)
1170 return error(_("could not parse hunk header"));
1172 return 1;
1175 static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1176 size_t orig_old_count, size_t orig_new_count)
1178 struct hunk_header *header = &hunk->header;
1179 size_t i;
1181 header->old_count = header->new_count = 0;
1182 for (i = hunk->start; i < hunk->end; ) {
1183 switch(normalize_marker(&s->plain.buf[i])) {
1184 case '-':
1185 header->old_count++;
1186 break;
1187 case '+':
1188 header->new_count++;
1189 break;
1190 case ' ':
1191 header->old_count++;
1192 header->new_count++;
1193 break;
1196 i = find_next_line(&s->plain, i);
1199 return orig_old_count - orig_new_count
1200 - header->old_count + header->new_count;
1203 static int run_apply_check(struct add_p_state *s,
1204 struct file_diff *file_diff)
1206 struct child_process cp = CHILD_PROCESS_INIT;
1208 strbuf_reset(&s->buf);
1209 reassemble_patch(s, file_diff, 1, &s->buf);
1211 setup_child_process(s, &cp,
1212 "apply", "--check", NULL);
1213 strvec_pushv(&cp.args, s->mode->apply_check_args);
1214 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1215 return error(_("'git apply --cached' failed"));
1217 return 0;
1220 static int read_single_character(struct add_p_state *s)
1222 if (s->s.use_single_key) {
1223 int res = read_key_without_echo(&s->answer);
1224 printf("%s\n", res == EOF ? "" : s->answer.buf);
1225 return res;
1228 if (git_read_line_interactively(&s->answer) == EOF)
1229 return EOF;
1230 return 0;
1233 static int prompt_yesno(struct add_p_state *s, const char *prompt)
1235 for (;;) {
1236 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1237 fflush(stdout);
1238 if (read_single_character(s) == EOF)
1239 return -1;
1240 /* do not limit to 1-byte input to allow 'no' etc. */
1241 switch (tolower(s->answer.buf[0])) {
1242 case 'n': return 0;
1243 case 'y': return 1;
1248 static int edit_hunk_loop(struct add_p_state *s,
1249 struct file_diff *file_diff, struct hunk *hunk)
1251 size_t plain_len = s->plain.len, colored_len = s->colored.len;
1252 struct hunk backup;
1254 backup = *hunk;
1256 for (;;) {
1257 int res = edit_hunk_manually(s, hunk);
1258 if (res == 0) {
1259 /* abandoned */
1260 *hunk = backup;
1261 return -1;
1264 if (res > 0) {
1265 hunk->delta +=
1266 recount_edited_hunk(s, hunk,
1267 backup.header.old_count,
1268 backup.header.new_count);
1269 if (!run_apply_check(s, file_diff))
1270 return 0;
1273 /* Drop edits (they were appended to s->plain) */
1274 strbuf_setlen(&s->plain, plain_len);
1275 strbuf_setlen(&s->colored, colored_len);
1276 *hunk = backup;
1279 * TRANSLATORS: do not translate [y/n]
1280 * The program will only accept that input at this point.
1281 * Consider translating (saying "no" discards!) as
1282 * (saying "n" for "no" discards!) if the translation
1283 * of the word "no" does not start with n.
1285 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1286 "Edit again (saying \"no\" discards!) "
1287 "[y/n]? "));
1288 if (res < 1)
1289 return -1;
1293 static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1294 int is_reverse)
1296 const char *reverse = is_reverse ? "-R" : NULL;
1297 struct child_process check_index = CHILD_PROCESS_INIT;
1298 struct child_process check_worktree = CHILD_PROCESS_INIT;
1299 struct child_process apply_index = CHILD_PROCESS_INIT;
1300 struct child_process apply_worktree = CHILD_PROCESS_INIT;
1301 int applies_index, applies_worktree;
1303 setup_child_process(s, &check_index,
1304 "apply", "--cached", "--check", reverse, NULL);
1305 applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1306 NULL, 0, NULL, 0);
1308 setup_child_process(s, &check_worktree,
1309 "apply", "--check", reverse, NULL);
1310 applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1311 NULL, 0, NULL, 0);
1313 if (applies_worktree && applies_index) {
1314 setup_child_process(s, &apply_index,
1315 "apply", "--cached", reverse, NULL);
1316 pipe_command(&apply_index, diff->buf, diff->len,
1317 NULL, 0, NULL, 0);
1319 setup_child_process(s, &apply_worktree,
1320 "apply", reverse, NULL);
1321 pipe_command(&apply_worktree, diff->buf, diff->len,
1322 NULL, 0, NULL, 0);
1324 return 1;
1327 if (!applies_index) {
1328 err(s, _("The selected hunks do not apply to the index!"));
1329 if (prompt_yesno(s, _("Apply them to the worktree "
1330 "anyway? ")) > 0) {
1331 setup_child_process(s, &apply_worktree,
1332 "apply", reverse, NULL);
1333 return pipe_command(&apply_worktree, diff->buf,
1334 diff->len, NULL, 0, NULL, 0);
1336 err(s, _("Nothing was applied.\n"));
1337 } else
1338 /* As a last resort, show the diff to the user */
1339 fwrite(diff->buf, diff->len, 1, stdout);
1341 return 0;
1344 #define SUMMARY_HEADER_WIDTH 20
1345 #define SUMMARY_LINE_WIDTH 80
1346 static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1347 struct strbuf *out)
1349 struct hunk_header *header = &hunk->header;
1350 struct strbuf *plain = &s->plain;
1351 size_t len = out->len, i;
1353 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1354 header->old_offset, header->old_count,
1355 header->new_offset, header->new_count);
1356 if (out->len - len < SUMMARY_HEADER_WIDTH)
1357 strbuf_addchars(out, ' ',
1358 SUMMARY_HEADER_WIDTH + len - out->len);
1359 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1360 if (plain->buf[i] != ' ')
1361 break;
1362 if (i < hunk->end)
1363 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1364 if (out->len - len > SUMMARY_LINE_WIDTH)
1365 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1366 strbuf_complete_line(out);
1369 #define DISPLAY_HUNKS_LINES 20
1370 static size_t display_hunks(struct add_p_state *s,
1371 struct file_diff *file_diff, size_t start_index)
1373 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1375 if (end_index > file_diff->hunk_nr)
1376 end_index = file_diff->hunk_nr;
1378 while (start_index < end_index) {
1379 struct hunk *hunk = file_diff->hunk + start_index++;
1381 strbuf_reset(&s->buf);
1382 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1383 : hunk->use == SKIP_HUNK ? '-' : ' ',
1384 (int)start_index);
1385 summarize_hunk(s, hunk, &s->buf);
1386 fputs(s->buf.buf, stdout);
1389 return end_index;
1392 static const char help_patch_remainder[] =
1393 N_("j - leave this hunk undecided, see next undecided hunk\n"
1394 "J - leave this hunk undecided, see next hunk\n"
1395 "k - leave this hunk undecided, see previous undecided hunk\n"
1396 "K - leave this hunk undecided, see previous hunk\n"
1397 "g - select a hunk to go to\n"
1398 "/ - search for a hunk matching the given regex\n"
1399 "s - split the current hunk into smaller hunks\n"
1400 "e - manually edit the current hunk\n"
1401 "p - print the current hunk\n"
1402 "? - print help\n");
1404 static int patch_update_file(struct add_p_state *s,
1405 struct file_diff *file_diff)
1407 size_t hunk_index = 0;
1408 ssize_t i, undecided_previous, undecided_next, rendered_hunk_index = -1;
1409 struct hunk *hunk;
1410 char ch;
1411 struct child_process cp = CHILD_PROCESS_INIT;
1412 int colored = !!s->colored.len, quit = 0;
1413 enum prompt_mode_type prompt_mode_type;
1414 enum {
1415 ALLOW_GOTO_PREVIOUS_HUNK = 1 << 0,
1416 ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK = 1 << 1,
1417 ALLOW_GOTO_NEXT_HUNK = 1 << 2,
1418 ALLOW_GOTO_NEXT_UNDECIDED_HUNK = 1 << 3,
1419 ALLOW_SEARCH_AND_GOTO = 1 << 4,
1420 ALLOW_SPLIT = 1 << 5,
1421 ALLOW_EDIT = 1 << 6
1422 } permitted = 0;
1424 /* Empty added files have no hunks */
1425 if (!file_diff->hunk_nr && !file_diff->added)
1426 return 0;
1428 strbuf_reset(&s->buf);
1429 render_diff_header(s, file_diff, colored, &s->buf);
1430 fputs(s->buf.buf, stdout);
1431 for (;;) {
1432 if (hunk_index >= file_diff->hunk_nr)
1433 hunk_index = 0;
1434 hunk = file_diff->hunk_nr
1435 ? file_diff->hunk + hunk_index
1436 : &file_diff->head;
1437 undecided_previous = -1;
1438 undecided_next = -1;
1440 if (file_diff->hunk_nr) {
1441 for (i = hunk_index - 1; i >= 0; i--)
1442 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1443 undecided_previous = i;
1444 break;
1447 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1448 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1449 undecided_next = i;
1450 break;
1454 /* Everything decided? */
1455 if (undecided_previous < 0 && undecided_next < 0 &&
1456 hunk->use != UNDECIDED_HUNK)
1457 break;
1459 strbuf_reset(&s->buf);
1460 if (file_diff->hunk_nr) {
1461 if (rendered_hunk_index != hunk_index) {
1462 render_hunk(s, hunk, 0, colored, &s->buf);
1463 fputs(s->buf.buf, stdout);
1464 rendered_hunk_index = hunk_index;
1467 strbuf_reset(&s->buf);
1468 if (undecided_previous >= 0) {
1469 permitted |= ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK;
1470 strbuf_addstr(&s->buf, ",k");
1472 if (hunk_index) {
1473 permitted |= ALLOW_GOTO_PREVIOUS_HUNK;
1474 strbuf_addstr(&s->buf, ",K");
1476 if (undecided_next >= 0) {
1477 permitted |= ALLOW_GOTO_NEXT_UNDECIDED_HUNK;
1478 strbuf_addstr(&s->buf, ",j");
1480 if (hunk_index + 1 < file_diff->hunk_nr) {
1481 permitted |= ALLOW_GOTO_NEXT_HUNK;
1482 strbuf_addstr(&s->buf, ",J");
1484 if (file_diff->hunk_nr > 1) {
1485 permitted |= ALLOW_SEARCH_AND_GOTO;
1486 strbuf_addstr(&s->buf, ",g,/");
1488 if (hunk->splittable_into > 1) {
1489 permitted |= ALLOW_SPLIT;
1490 strbuf_addstr(&s->buf, ",s");
1492 if (hunk_index + 1 > file_diff->mode_change &&
1493 !file_diff->deleted) {
1494 permitted |= ALLOW_EDIT;
1495 strbuf_addstr(&s->buf, ",e");
1497 strbuf_addstr(&s->buf, ",p");
1499 if (file_diff->deleted)
1500 prompt_mode_type = PROMPT_DELETION;
1501 else if (file_diff->added)
1502 prompt_mode_type = PROMPT_ADDITION;
1503 else if (file_diff->mode_change && !hunk_index)
1504 prompt_mode_type = PROMPT_MODE_CHANGE;
1505 else
1506 prompt_mode_type = PROMPT_HUNK;
1508 printf("%s(%"PRIuMAX"/%"PRIuMAX") ", s->s.prompt_color,
1509 (uintmax_t)hunk_index + 1,
1510 (uintmax_t)(file_diff->hunk_nr
1511 ? file_diff->hunk_nr
1512 : 1));
1513 printf(_(s->mode->prompt_mode[prompt_mode_type]),
1514 s->buf.buf);
1515 if (*s->s.reset_color)
1516 fputs(s->s.reset_color, stdout);
1517 fflush(stdout);
1518 if (read_single_character(s) == EOF)
1519 break;
1521 if (!s->answer.len)
1522 continue;
1523 ch = tolower(s->answer.buf[0]);
1525 /* 'g' takes a hunk number and '/' takes a regexp */
1526 if (s->answer.len != 1 && (ch != 'g' && ch != '/')) {
1527 err(s, _("Only one letter is expected, got '%s'"), s->answer.buf);
1528 continue;
1530 if (ch == 'y') {
1531 hunk->use = USE_HUNK;
1532 soft_increment:
1533 hunk_index = undecided_next < 0 ?
1534 file_diff->hunk_nr : undecided_next;
1535 } else if (ch == 'n') {
1536 hunk->use = SKIP_HUNK;
1537 goto soft_increment;
1538 } else if (ch == 'a') {
1539 if (file_diff->hunk_nr) {
1540 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1541 hunk = file_diff->hunk + hunk_index;
1542 if (hunk->use == UNDECIDED_HUNK)
1543 hunk->use = USE_HUNK;
1545 } else if (hunk->use == UNDECIDED_HUNK) {
1546 hunk->use = USE_HUNK;
1548 } else if (ch == 'd' || ch == 'q') {
1549 if (file_diff->hunk_nr) {
1550 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1551 hunk = file_diff->hunk + hunk_index;
1552 if (hunk->use == UNDECIDED_HUNK)
1553 hunk->use = SKIP_HUNK;
1555 } else if (hunk->use == UNDECIDED_HUNK) {
1556 hunk->use = SKIP_HUNK;
1558 if (ch == 'q') {
1559 quit = 1;
1560 break;
1562 } else if (s->answer.buf[0] == 'K') {
1563 if (permitted & ALLOW_GOTO_PREVIOUS_HUNK)
1564 hunk_index--;
1565 else
1566 err(s, _("No previous hunk"));
1567 } else if (s->answer.buf[0] == 'J') {
1568 if (permitted & ALLOW_GOTO_NEXT_HUNK)
1569 hunk_index++;
1570 else
1571 err(s, _("No next hunk"));
1572 } else if (s->answer.buf[0] == 'k') {
1573 if (permitted & ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK)
1574 hunk_index = undecided_previous;
1575 else
1576 err(s, _("No previous hunk"));
1577 } else if (s->answer.buf[0] == 'j') {
1578 if (permitted & ALLOW_GOTO_NEXT_UNDECIDED_HUNK)
1579 hunk_index = undecided_next;
1580 else
1581 err(s, _("No next hunk"));
1582 } else if (s->answer.buf[0] == 'g') {
1583 char *pend;
1584 unsigned long response;
1586 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1587 err(s, _("No other hunks to goto"));
1588 continue;
1590 strbuf_remove(&s->answer, 0, 1);
1591 strbuf_trim(&s->answer);
1592 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1593 if (i < (int)file_diff->mode_change)
1594 i = file_diff->mode_change;
1595 while (s->answer.len == 0) {
1596 i = display_hunks(s, file_diff, i);
1597 printf("%s", i < file_diff->hunk_nr ?
1598 _("go to which hunk (<ret> to see "
1599 "more)? ") : _("go to which hunk? "));
1600 fflush(stdout);
1601 if (strbuf_getline(&s->answer,
1602 stdin) == EOF)
1603 break;
1604 strbuf_trim_trailing_newline(&s->answer);
1607 strbuf_trim(&s->answer);
1608 response = strtoul(s->answer.buf, &pend, 10);
1609 if (*pend || pend == s->answer.buf)
1610 err(s, _("Invalid number: '%s'"),
1611 s->answer.buf);
1612 else if (0 < response && response <= file_diff->hunk_nr)
1613 hunk_index = response - 1;
1614 else
1615 err(s, Q_("Sorry, only %d hunk available.",
1616 "Sorry, only %d hunks available.",
1617 file_diff->hunk_nr),
1618 (int)file_diff->hunk_nr);
1619 } else if (s->answer.buf[0] == '/') {
1620 regex_t regex;
1621 int ret;
1623 if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1624 err(s, _("No other hunks to search"));
1625 continue;
1627 strbuf_remove(&s->answer, 0, 1);
1628 strbuf_trim_trailing_newline(&s->answer);
1629 if (s->answer.len == 0) {
1630 printf("%s", _("search for regex? "));
1631 fflush(stdout);
1632 if (strbuf_getline(&s->answer,
1633 stdin) == EOF)
1634 break;
1635 strbuf_trim_trailing_newline(&s->answer);
1636 if (s->answer.len == 0)
1637 continue;
1639 ret = regcomp(&regex, s->answer.buf,
1640 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1641 if (ret) {
1642 char errbuf[1024];
1644 regerror(ret, &regex, errbuf, sizeof(errbuf));
1645 err(s, _("Malformed search regexp %s: %s"),
1646 s->answer.buf, errbuf);
1647 continue;
1649 i = hunk_index;
1650 for (;;) {
1651 /* render the hunk into a scratch buffer */
1652 render_hunk(s, file_diff->hunk + i, 0, 0,
1653 &s->buf);
1654 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1655 != REG_NOMATCH)
1656 break;
1657 i++;
1658 if (i == file_diff->hunk_nr)
1659 i = 0;
1660 if (i != hunk_index)
1661 continue;
1662 err(s, _("No hunk matches the given pattern"));
1663 break;
1665 regfree(&regex);
1666 hunk_index = i;
1667 } else if (s->answer.buf[0] == 's') {
1668 size_t splittable_into = hunk->splittable_into;
1669 if (!(permitted & ALLOW_SPLIT)) {
1670 err(s, _("Sorry, cannot split this hunk"));
1671 } else if (!split_hunk(s, file_diff,
1672 hunk - file_diff->hunk)) {
1673 color_fprintf_ln(stdout, s->s.header_color,
1674 _("Split into %d hunks."),
1675 (int)splittable_into);
1676 rendered_hunk_index = -1;
1678 } else if (s->answer.buf[0] == 'e') {
1679 if (!(permitted & ALLOW_EDIT))
1680 err(s, _("Sorry, cannot edit this hunk"));
1681 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1682 hunk->use = USE_HUNK;
1683 goto soft_increment;
1685 } else if (s->answer.buf[0] == 'p') {
1686 rendered_hunk_index = -1;
1687 } else if (s->answer.buf[0] == '?') {
1688 const char *p = _(help_patch_remainder), *eol = p;
1690 color_fprintf(stdout, s->s.help_color, "%s",
1691 _(s->mode->help_patch_text));
1694 * Show only those lines of the remainder that are
1695 * actually applicable with the current hunk.
1697 for (; *p; p = eol + (*eol == '\n')) {
1698 eol = strchrnul(p, '\n');
1701 * `s->buf` still contains the part of the
1702 * commands shown in the prompt that are not
1703 * always available.
1705 if (*p != '?' && !strchr(s->buf.buf, *p))
1706 continue;
1708 color_fprintf_ln(stdout, s->s.help_color,
1709 "%.*s", (int)(eol - p), p);
1711 } else {
1712 err(s, _("Unknown command '%s' (use '?' for help)"),
1713 s->answer.buf);
1717 /* Any hunk to be used? */
1718 for (i = 0; i < file_diff->hunk_nr; i++)
1719 if (file_diff->hunk[i].use == USE_HUNK)
1720 break;
1722 if (i < file_diff->hunk_nr ||
1723 (!file_diff->hunk_nr && file_diff->head.use == USE_HUNK)) {
1724 /* At least one hunk selected: apply */
1725 strbuf_reset(&s->buf);
1726 reassemble_patch(s, file_diff, 0, &s->buf);
1728 discard_index(s->s.r->index);
1729 if (s->mode->apply_for_checkout)
1730 apply_for_checkout(s, &s->buf,
1731 s->mode->is_reverse);
1732 else {
1733 setup_child_process(s, &cp, "apply", NULL);
1734 strvec_pushv(&cp.args, s->mode->apply_args);
1735 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1736 NULL, 0, NULL, 0))
1737 error(_("'git apply' failed"));
1739 if (repo_read_index(s->s.r) >= 0)
1740 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
1741 1, NULL, NULL, NULL);
1744 putchar('\n');
1745 return quit;
1748 int run_add_p(struct repository *r, enum add_p_mode mode,
1749 const char *revision, const struct pathspec *ps)
1751 struct add_p_state s = {
1752 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1754 size_t i, binary_count = 0;
1756 init_add_i_state(&s.s, r);
1758 if (mode == ADD_P_STASH)
1759 s.mode = &patch_mode_stash;
1760 else if (mode == ADD_P_RESET) {
1761 if (!revision || !strcmp(revision, "HEAD"))
1762 s.mode = &patch_mode_reset_head;
1763 else
1764 s.mode = &patch_mode_reset_nothead;
1765 } else if (mode == ADD_P_CHECKOUT) {
1766 if (!revision)
1767 s.mode = &patch_mode_checkout_index;
1768 else if (!strcmp(revision, "HEAD"))
1769 s.mode = &patch_mode_checkout_head;
1770 else
1771 s.mode = &patch_mode_checkout_nothead;
1772 } else if (mode == ADD_P_WORKTREE) {
1773 if (!revision)
1774 s.mode = &patch_mode_checkout_index;
1775 else if (!strcmp(revision, "HEAD"))
1776 s.mode = &patch_mode_worktree_head;
1777 else
1778 s.mode = &patch_mode_worktree_nothead;
1779 } else
1780 s.mode = &patch_mode_add;
1781 s.revision = revision;
1783 discard_index(r->index);
1784 if (repo_read_index(r) < 0 ||
1785 (!s.mode->index_only &&
1786 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1787 NULL, NULL, NULL) < 0) ||
1788 parse_diff(&s, ps) < 0) {
1789 add_p_state_clear(&s);
1790 return -1;
1793 for (i = 0; i < s.file_diff_nr; i++)
1794 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1795 binary_count++;
1796 else if (patch_update_file(&s, s.file_diff + i))
1797 break;
1799 if (s.file_diff_nr == 0)
1800 err(&s, _("No changes."));
1801 else if (binary_count == s.file_diff_nr)
1802 err(&s, _("Only binary files changed."));
1804 add_p_state_clear(&s);
1805 return 0;