]> git.ipfire.org Git - thirdparty/git.git/blame - add-patch.c
built-in add -p: implement the "worktree" patch modes
[thirdparty/git.git] / add-patch.c
CommitLineData
f6aa7ecc
JS
1#include "cache.h"
2#include "add-interactive.h"
3#include "strbuf.h"
4#include "run-command.h"
5#include "argv-array.h"
6#include "pathspec.h"
e3bd11b4 7#include "color.h"
25ea47af
JS
8#include "diff.h"
9
0ecd9d27 10enum prompt_mode_type {
d2a233cb
JS
11 PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_HUNK,
12 PROMPT_MODE_MAX, /* must be last */
0ecd9d27
JS
13};
14
d2a233cb
JS
15struct patch_mode {
16 /*
17 * The magic constant 4 is chosen such that all patch modes
18 * provide enough space for three command-line arguments followed by a
19 * trailing `NULL`.
20 */
21 const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
36bae1dc 22 unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
d2a233cb
JS
23 const char *prompt_mode[PROMPT_MODE_MAX];
24 const char *edit_hunk_hint, *help_patch_text;
25};
26
27static struct patch_mode patch_mode_add = {
28 .diff_cmd = { "diff-files", NULL },
29 .apply_args = { "--cached", NULL },
30 .apply_check_args = { "--cached", NULL },
31 .prompt_mode = {
32 N_("Stage mode change [y,n,q,a,d%s,?]? "),
33 N_("Stage deletion [y,n,q,a,d%s,?]? "),
34 N_("Stage this hunk [y,n,q,a,d%s,?]? ")
35 },
36 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
37 "will immediately be marked for staging."),
38 .help_patch_text =
39 N_("y - stage this hunk\n"
40 "n - do not stage this hunk\n"
41 "q - quit; do not stage this hunk or any of the remaining "
42 "ones\n"
43 "a - stage this hunk and all later hunks in the file\n"
44 "d - do not stage this hunk or any of the later hunks in "
45 "the file\n")
0ecd9d27
JS
46};
47
36bae1dc
JS
48static struct patch_mode patch_mode_stash = {
49 .diff_cmd = { "diff-index", "HEAD", NULL },
50 .apply_args = { "--cached", NULL },
51 .apply_check_args = { "--cached", NULL },
52 .prompt_mode = {
53 N_("Stash mode change [y,n,q,a,d%s,?]? "),
54 N_("Stash deletion [y,n,q,a,d%s,?]? "),
55 N_("Stash this hunk [y,n,q,a,d%s,?]? "),
56 },
57 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
58 "will immediately be marked for stashing."),
59 .help_patch_text =
60 N_("y - stash this hunk\n"
61 "n - do not stash this hunk\n"
62 "q - quit; do not stash this hunk or any of the remaining "
63 "ones\n"
64 "a - stash this hunk and all later hunks in the file\n"
65 "d - do not stash this hunk or any of the later hunks in "
66 "the file\n"),
67};
68
69static struct patch_mode patch_mode_reset_head = {
70 .diff_cmd = { "diff-index", "--cached", NULL },
71 .apply_args = { "-R", "--cached", NULL },
72 .apply_check_args = { "-R", "--cached", NULL },
73 .is_reverse = 1,
74 .index_only = 1,
75 .prompt_mode = {
76 N_("Unstage mode change [y,n,q,a,d%s,?]? "),
77 N_("Unstage deletion [y,n,q,a,d%s,?]? "),
78 N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
79 },
80 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
81 "will immediately be marked for unstaging."),
82 .help_patch_text =
83 N_("y - unstage this hunk\n"
84 "n - do not unstage this hunk\n"
85 "q - quit; do not unstage this hunk or any of the remaining "
86 "ones\n"
87 "a - unstage this hunk and all later hunks in the file\n"
88 "d - do not unstage this hunk or any of the later hunks in "
89 "the file\n"),
90};
91
92static struct patch_mode patch_mode_reset_nothead = {
93 .diff_cmd = { "diff-index", "-R", "--cached", NULL },
94 .apply_args = { "--cached", NULL },
95 .apply_check_args = { "--cached", NULL },
96 .index_only = 1,
97 .prompt_mode = {
98 N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
99 N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
100 N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
101 },
102 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
103 "will immediately be marked for applying."),
104 .help_patch_text =
105 N_("y - apply this hunk to index\n"
106 "n - do not apply this hunk to index\n"
107 "q - quit; do not apply this hunk or any of the remaining "
108 "ones\n"
109 "a - apply this hunk and all later hunks in the file\n"
110 "d - do not apply this hunk or any of the later hunks in "
111 "the file\n"),
112};
113
52628f94
JS
114static struct patch_mode patch_mode_checkout_index = {
115 .diff_cmd = { "diff-files", NULL },
116 .apply_args = { "-R", NULL },
117 .apply_check_args = { "-R", NULL },
118 .is_reverse = 1,
119 .prompt_mode = {
120 N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
121 N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
122 N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
123 },
124 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
125 "will immediately be marked for discarding."),
126 .help_patch_text =
127 N_("y - discard this hunk from worktree\n"
128 "n - do not discard this hunk from worktree\n"
129 "q - quit; do not discard this hunk or any of the remaining "
130 "ones\n"
131 "a - discard this hunk and all later hunks in the file\n"
132 "d - do not discard this hunk or any of the later hunks in "
133 "the file\n"),
134};
135
136static struct patch_mode patch_mode_checkout_head = {
137 .diff_cmd = { "diff-index", NULL },
138 .apply_for_checkout = 1,
139 .apply_check_args = { "-R", NULL },
140 .is_reverse = 1,
141 .prompt_mode = {
142 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
143 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
144 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
145 },
146 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
147 "will immediately be marked for discarding."),
148 .help_patch_text =
149 N_("y - discard this hunk from index and worktree\n"
150 "n - do not discard this hunk from index and worktree\n"
151 "q - quit; do not discard this hunk or any of the remaining "
152 "ones\n"
153 "a - discard this hunk and all later hunks in the file\n"
154 "d - do not discard this hunk or any of the later hunks in "
155 "the file\n"),
156};
157
158static struct patch_mode patch_mode_checkout_nothead = {
159 .diff_cmd = { "diff-index", "-R", NULL },
160 .apply_for_checkout = 1,
161 .apply_check_args = { NULL },
162 .prompt_mode = {
163 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
164 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
165 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
166 },
167 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
168 "will immediately be marked for applying."),
169 .help_patch_text =
170 N_("y - apply this hunk to index and worktree\n"
171 "n - do not apply this hunk to index and worktree\n"
172 "q - quit; do not apply this hunk or any of the remaining "
173 "ones\n"
174 "a - apply this hunk and all later hunks in the file\n"
175 "d - do not apply this hunk or any of the later hunks in "
176 "the file\n"),
177};
178
cee6cb73
JS
179static struct patch_mode patch_mode_worktree_head = {
180 .diff_cmd = { "diff-index", NULL },
181 .apply_args = { "-R", NULL },
182 .apply_check_args = { "-R", NULL },
183 .is_reverse = 1,
184 .prompt_mode = {
185 N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
186 N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
187 N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
188 },
189 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
190 "will immediately be marked for discarding."),
191 .help_patch_text =
192 N_("y - discard this hunk from worktree\n"
193 "n - do not discard this hunk from worktree\n"
194 "q - quit; do not discard this hunk or any of the remaining "
195 "ones\n"
196 "a - discard this hunk and all later hunks in the file\n"
197 "d - do not discard this hunk or any of the later hunks in "
198 "the file\n"),
199};
200
201static struct patch_mode patch_mode_worktree_nothead = {
202 .diff_cmd = { "diff-index", "-R", NULL },
203 .apply_args = { NULL },
204 .apply_check_args = { NULL },
205 .prompt_mode = {
206 N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
207 N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
208 N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
209 },
210 .edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
211 "will immediately be marked for applying."),
212 .help_patch_text =
213 N_("y - apply this hunk to worktree\n"
214 "n - do not apply this hunk to worktree\n"
215 "q - quit; do not apply this hunk or any of the remaining "
216 "ones\n"
217 "a - apply this hunk and all later hunks in the file\n"
218 "d - do not apply this hunk or any of the later hunks in "
219 "the file\n"),
220};
221
25ea47af
JS
222struct hunk_header {
223 unsigned long old_offset, old_count, new_offset, new_count;
224 /*
225 * Start/end offsets to the extra text after the second `@@` in the
226 * hunk header, e.g. the function signature. This is expected to
227 * include the newline.
228 */
229 size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
230};
f6aa7ecc
JS
231
232struct hunk {
510aeca1 233 size_t start, end, colored_start, colored_end, splittable_into;
bcdd297b 234 ssize_t delta;
f6aa7ecc 235 enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
25ea47af 236 struct hunk_header header;
f6aa7ecc
JS
237};
238
239struct add_p_state {
25ea47af 240 struct add_i_state s;
f6aa7ecc
JS
241 struct strbuf answer, buf;
242
243 /* parsed diff */
e3bd11b4 244 struct strbuf plain, colored;
80399aec
JS
245 struct file_diff {
246 struct hunk head;
247 struct hunk *hunk;
248 size_t hunk_nr, hunk_alloc;
2e408319 249 unsigned deleted:1, mode_change:1,binary:1;
80399aec
JS
250 } *file_diff;
251 size_t file_diff_nr;
d2a233cb
JS
252
253 /* patch mode */
254 struct patch_mode *mode;
255 const char *revision;
f6aa7ecc
JS
256};
257
7584dd3c
JS
258static void err(struct add_p_state *s, const char *fmt, ...)
259{
260 va_list args;
261
262 va_start(args, fmt);
263 fputs(s->s.error_color, stderr);
264 vfprintf(stderr, fmt, args);
265 fputs(s->s.reset_color, stderr);
266 fputc('\n', stderr);
267 va_end(args);
268}
269
f6aa7ecc
JS
270static void setup_child_process(struct add_p_state *s,
271 struct child_process *cp, ...)
272{
273 va_list ap;
274 const char *arg;
275
276 va_start(ap, cp);
277 while ((arg = va_arg(ap, const char *)))
278 argv_array_push(&cp->args, arg);
279 va_end(ap);
280
281 cp->git_cmd = 1;
282 argv_array_pushf(&cp->env_array,
25ea47af
JS
283 INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
284}
285
286static int parse_range(const char **p,
287 unsigned long *offset, unsigned long *count)
288{
289 char *pend;
290
291 *offset = strtoul(*p, &pend, 10);
292 if (pend == *p)
293 return -1;
294 if (*pend != ',') {
295 *count = 1;
296 *p = pend;
297 return 0;
298 }
299 *count = strtoul(pend + 1, (char **)p, 10);
300 return *p == pend + 1 ? -1 : 0;
301}
302
303static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
304{
305 struct hunk_header *header = &hunk->header;
306 const char *line = s->plain.buf + hunk->start, *p = line;
307 char *eol = memchr(p, '\n', s->plain.len - hunk->start);
308
309 if (!eol)
310 eol = s->plain.buf + s->plain.len;
311
312 if (!skip_prefix(p, "@@ -", &p) ||
313 parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
314 !skip_prefix(p, " +", &p) ||
315 parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
316 !skip_prefix(p, " @@", &p))
317 return error(_("could not parse hunk header '%.*s'"),
318 (int)(eol - line), line);
319
320 hunk->start = eol - s->plain.buf + (*eol == '\n');
321 header->extra_start = p - s->plain.buf;
322 header->extra_end = hunk->start;
323
324 if (!s->colored.len) {
325 header->colored_extra_start = header->colored_extra_end = 0;
326 return 0;
327 }
328
329 /* Now find the extra text in the colored diff */
330 line = s->colored.buf + hunk->colored_start;
331 eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
332 if (!eol)
333 eol = s->colored.buf + s->colored.len;
334 p = memmem(line, eol - line, "@@ -", 4);
335 if (!p)
336 return error(_("could not parse colored hunk header '%.*s'"),
337 (int)(eol - line), line);
338 p = memmem(p + 4, eol - p - 4, " @@", 3);
339 if (!p)
340 return error(_("could not parse colored hunk header '%.*s'"),
341 (int)(eol - line), line);
342 hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
343 header->colored_extra_start = p + 3 - s->colored.buf;
344 header->colored_extra_end = hunk->colored_start;
345
346 return 0;
f6aa7ecc
JS
347}
348
5906d5de
JS
349static int is_octal(const char *p, size_t len)
350{
351 if (!len)
352 return 0;
353
354 while (len--)
355 if (*p < '0' || *(p++) > '7')
356 return 0;
357 return 1;
358}
359
f6aa7ecc
JS
360static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
361{
e3bd11b4
JS
362 struct argv_array args = ARGV_ARRAY_INIT;
363 struct strbuf *plain = &s->plain, *colored = NULL;
f6aa7ecc 364 struct child_process cp = CHILD_PROCESS_INIT;
510aeca1 365 char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
80399aec
JS
366 size_t file_diff_alloc = 0, i, color_arg_index;
367 struct file_diff *file_diff = NULL;
f6aa7ecc
JS
368 struct hunk *hunk = NULL;
369 int res;
370
d2a233cb
JS
371 argv_array_pushv(&args, s->mode->diff_cmd);
372 if (s->revision) {
373 struct object_id oid;
374 argv_array_push(&args,
375 /* could be on an unborn branch */
376 !strcmp("HEAD", s->revision) &&
377 get_oid("HEAD", &oid) ?
378 empty_tree_oid_hex() : s->revision);
379 }
380 color_arg_index = args.argc;
f6aa7ecc 381 /* Use `--no-color` explicitly, just in case `diff.color = always`. */
d2a233cb 382 argv_array_pushl(&args, "--no-color", "-p", "--", NULL);
f6aa7ecc 383 for (i = 0; i < ps->nr; i++)
e3bd11b4 384 argv_array_push(&args, ps->items[i].original);
f6aa7ecc 385
e3bd11b4
JS
386 setup_child_process(s, &cp, NULL);
387 cp.argv = args.argv;
f6aa7ecc 388 res = capture_command(&cp, plain, 0);
e3bd11b4
JS
389 if (res) {
390 argv_array_clear(&args);
f6aa7ecc 391 return error(_("could not parse diff"));
e3bd11b4
JS
392 }
393 if (!plain->len) {
394 argv_array_clear(&args);
f6aa7ecc 395 return 0;
e3bd11b4 396 }
f6aa7ecc
JS
397 strbuf_complete_line(plain);
398
e3bd11b4
JS
399 if (want_color_fd(1, -1)) {
400 struct child_process colored_cp = CHILD_PROCESS_INIT;
401
402 setup_child_process(s, &colored_cp, NULL);
403 xsnprintf((char *)args.argv[color_arg_index], 8, "--color");
404 colored_cp.argv = args.argv;
405 colored = &s->colored;
406 res = capture_command(&colored_cp, colored, 0);
407 argv_array_clear(&args);
408 if (res)
409 return error(_("could not parse colored diff"));
410 strbuf_complete_line(colored);
411 colored_p = colored->buf;
412 colored_pend = colored_p + colored->len;
413 }
414 argv_array_clear(&args);
415
80399aec 416 /* parse files and hunks */
f6aa7ecc
JS
417 p = plain->buf;
418 pend = p + plain->len;
419 while (p != pend) {
420 char *eol = memchr(p, '\n', pend - p);
5906d5de 421 const char *deleted = NULL, *mode_change = NULL;
47dc4fd5 422
f6aa7ecc
JS
423 if (!eol)
424 eol = pend;
425
426 if (starts_with(p, "diff ")) {
80399aec
JS
427 s->file_diff_nr++;
428 ALLOC_GROW(s->file_diff, s->file_diff_nr,
429 file_diff_alloc);
430 file_diff = s->file_diff + s->file_diff_nr - 1;
431 memset(file_diff, 0, sizeof(*file_diff));
432 hunk = &file_diff->head;
433 hunk->start = p - plain->buf;
434 if (colored_p)
435 hunk->colored_start = colored_p - colored->buf;
510aeca1 436 marker = '\0';
f6aa7ecc
JS
437 } else if (p == plain->buf)
438 BUG("diff starts with unexpected line:\n"
439 "%.*s\n", (int)(eol - p), p);
47dc4fd5
JS
440 else if (file_diff->deleted)
441 ; /* keep the rest of the file in a single "hunk" */
442 else if (starts_with(p, "@@ ") ||
443 (hunk == &file_diff->head &&
444 skip_prefix(p, "deleted file", &deleted))) {
510aeca1
JS
445 if (marker == '-' || marker == '+')
446 /*
447 * Should not happen; previous hunk did not end
448 * in a context line? Handle it anyway.
449 */
450 hunk->splittable_into++;
451
80399aec
JS
452 file_diff->hunk_nr++;
453 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
454 file_diff->hunk_alloc);
455 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
f6aa7ecc
JS
456 memset(hunk, 0, sizeof(*hunk));
457
458 hunk->start = p - plain->buf;
e3bd11b4
JS
459 if (colored)
460 hunk->colored_start = colored_p - colored->buf;
25ea47af 461
47dc4fd5
JS
462 if (deleted)
463 file_diff->deleted = 1;
464 else if (parse_hunk_header(s, hunk) < 0)
25ea47af 465 return -1;
510aeca1
JS
466
467 /*
468 * Start counting into how many hunks this one can be
469 * split
470 */
471 marker = *p;
5906d5de
JS
472 } else if (hunk == &file_diff->head &&
473 skip_prefix(p, "old mode ", &mode_change) &&
474 is_octal(mode_change, eol - mode_change)) {
475 if (file_diff->mode_change)
476 BUG("double mode change?\n\n%.*s",
477 (int)(eol - plain->buf), plain->buf);
478 if (file_diff->hunk_nr++)
479 BUG("mode change in the middle?\n\n%.*s",
480 (int)(eol - plain->buf), plain->buf);
481
482 /*
483 * Do *not* change `hunk`: the mode change pseudo-hunk
484 * is _part of_ the header "hunk".
485 */
486 file_diff->mode_change = 1;
487 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
488 file_diff->hunk_alloc);
489 memset(file_diff->hunk, 0, sizeof(struct hunk));
490 file_diff->hunk->start = p - plain->buf;
491 if (colored_p)
492 file_diff->hunk->colored_start =
493 colored_p - colored->buf;
494 } else if (hunk == &file_diff->head &&
495 skip_prefix(p, "new mode ", &mode_change) &&
496 is_octal(mode_change, eol - mode_change)) {
497
498 /*
499 * Extend the "mode change" pseudo-hunk to include also
500 * the "new mode" line.
501 */
502 if (!file_diff->mode_change)
503 BUG("'new mode' without 'old mode'?\n\n%.*s",
504 (int)(eol - plain->buf), plain->buf);
505 if (file_diff->hunk_nr != 1)
506 BUG("mode change in the middle?\n\n%.*s",
507 (int)(eol - plain->buf), plain->buf);
508 if (p - plain->buf != file_diff->hunk->end)
509 BUG("'new mode' does not immediately follow "
510 "'old mode'?\n\n%.*s",
511 (int)(eol - plain->buf), plain->buf);
2e408319
JS
512 } else if (hunk == &file_diff->head &&
513 starts_with(p, "Binary files "))
514 file_diff->binary = 1;
f6aa7ecc 515
5906d5de
JS
516 if (file_diff->deleted && file_diff->mode_change)
517 BUG("diff contains delete *and* a mode change?!?\n%.*s",
518 (int)(eol - (plain->buf + file_diff->head.start)),
519 plain->buf + file_diff->head.start);
520
510aeca1
JS
521 if ((marker == '-' || marker == '+') && *p == ' ')
522 hunk->splittable_into++;
523 if (marker && *p != '\\')
524 marker = *p;
525
f6aa7ecc
JS
526 p = eol == pend ? pend : eol + 1;
527 hunk->end = p - plain->buf;
e3bd11b4
JS
528
529 if (colored) {
530 char *colored_eol = memchr(colored_p, '\n',
531 colored_pend - colored_p);
532 if (colored_eol)
533 colored_p = colored_eol + 1;
534 else
535 colored_p = colored_pend;
536
537 hunk->colored_end = colored_p - colored->buf;
538 }
5906d5de
JS
539
540 if (mode_change) {
541 if (file_diff->hunk_nr != 1)
542 BUG("mode change in hunk #%d???",
543 (int)file_diff->hunk_nr);
544 /* Adjust the end of the "mode change" pseudo-hunk */
545 file_diff->hunk->end = hunk->end;
546 if (colored)
547 file_diff->hunk->colored_end = hunk->colored_end;
548 }
f6aa7ecc
JS
549 }
550
510aeca1
JS
551 if (marker == '-' || marker == '+')
552 /*
553 * Last hunk ended in non-context line (i.e. it appended lines
554 * to the file, so there are no trailing context lines).
555 */
556 hunk->splittable_into++;
557
f6aa7ecc
JS
558 return 0;
559}
560
510aeca1
JS
561static size_t find_next_line(struct strbuf *sb, size_t offset)
562{
563 char *eol;
564
565 if (offset >= sb->len)
566 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
567 (int)offset, (int)sb->len, sb->buf);
568
569 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
570 if (!eol)
571 return sb->len;
572 return eol - sb->buf + 1;
573}
574
f6aa7ecc 575static void render_hunk(struct add_p_state *s, struct hunk *hunk,
25ea47af 576 ssize_t delta, int colored, struct strbuf *out)
f6aa7ecc 577{
25ea47af
JS
578 struct hunk_header *header = &hunk->header;
579
580 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
581 /*
582 * Generate the hunk header dynamically, except for special
583 * hunks (such as the diff header).
584 */
585 const char *p;
586 size_t len;
587 unsigned long old_offset = header->old_offset;
588 unsigned long new_offset = header->new_offset;
589
590 if (!colored) {
591 p = s->plain.buf + header->extra_start;
592 len = header->extra_end - header->extra_start;
593 } else {
594 strbuf_addstr(out, s->s.fraginfo_color);
595 p = s->colored.buf + header->colored_extra_start;
596 len = header->colored_extra_end
597 - header->colored_extra_start;
598 }
599
d2a233cb
JS
600 if (s->mode->is_reverse)
601 old_offset -= delta;
602 else
603 new_offset += delta;
25ea47af
JS
604
605 strbuf_addf(out, "@@ -%lu,%lu +%lu,%lu @@",
606 old_offset, header->old_count,
607 new_offset, header->new_count);
608 if (len)
609 strbuf_add(out, p, len);
610 else if (colored)
611 strbuf_addf(out, "%s\n", GIT_COLOR_RESET);
612 else
613 strbuf_addch(out, '\n');
614 }
615
e3bd11b4
JS
616 if (colored)
617 strbuf_add(out, s->colored.buf + hunk->colored_start,
618 hunk->colored_end - hunk->colored_start);
619 else
620 strbuf_add(out, s->plain.buf + hunk->start,
621 hunk->end - hunk->start);
f6aa7ecc
JS
622}
623
5906d5de
JS
624static void render_diff_header(struct add_p_state *s,
625 struct file_diff *file_diff, int colored,
626 struct strbuf *out)
627{
628 /*
629 * If there was a mode change, the first hunk is a pseudo hunk that
630 * corresponds to the mode line in the header. If the user did not want
631 * to stage that "hunk", we actually have to cut it out from the header.
632 */
633 int skip_mode_change =
634 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
635 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
636
637 if (!skip_mode_change) {
638 render_hunk(s, head, 0, colored, out);
639 return;
640 }
641
642 if (colored) {
643 const char *p = s->colored.buf;
644
645 strbuf_add(out, p + head->colored_start,
646 first->colored_start - head->colored_start);
647 strbuf_add(out, p + first->colored_end,
648 head->colored_end - first->colored_end);
649 } else {
650 const char *p = s->plain.buf;
651
652 strbuf_add(out, p + head->start, first->start - head->start);
653 strbuf_add(out, p + first->end, head->end - first->end);
654 }
655}
656
11f2c0da
JS
657/* Coalesce hunks again that were split */
658static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
bcdd297b 659 size_t *hunk_index, int use_all, struct hunk *merged)
11f2c0da 660{
bcdd297b 661 size_t i = *hunk_index, delta;
11f2c0da
JS
662 struct hunk *hunk = file_diff->hunk + i;
663 /* `header` corresponds to the merged hunk */
664 struct hunk_header *header = &merged->header, *next;
665
bcdd297b 666 if (!use_all && hunk->use != USE_HUNK)
11f2c0da
JS
667 return 0;
668
669 *merged = *hunk;
670 /* We simply skip the colored part (if any) when merging hunks */
671 merged->colored_start = merged->colored_end = 0;
672
673 for (; i + 1 < file_diff->hunk_nr; i++) {
674 hunk++;
675 next = &hunk->header;
676
677 /*
678 * Stop merging hunks when:
679 *
680 * - the hunk is not selected for use, or
681 * - the hunk does not overlap with the already-merged hunk(s)
682 */
bcdd297b
JS
683 if ((!use_all && hunk->use != USE_HUNK) ||
684 header->new_offset >= next->new_offset + merged->delta ||
685 header->new_offset + header->new_count
686 < next->new_offset + merged->delta)
11f2c0da
JS
687 break;
688
bcdd297b
JS
689 /*
690 * If the hunks were not edited, and overlap, we can simply
691 * extend the line range.
692 */
693 if (merged->start < hunk->start && merged->end > hunk->start) {
694 merged->end = hunk->end;
695 merged->colored_end = hunk->colored_end;
696 delta = 0;
697 } else {
698 const char *plain = s->plain.buf;
699 size_t overlapping_line_count = header->new_offset
700 + header->new_count - merged->delta
701 - next->new_offset;
702 size_t overlap_end = hunk->start;
703 size_t overlap_start = overlap_end;
704 size_t overlap_next, len, j;
705
706 /*
707 * One of the hunks was edited: the modified hunk was
708 * appended to the strbuf `s->plain`.
709 *
710 * Let's ensure that at least the last context line of
711 * the first hunk overlaps with the corresponding line
712 * of the second hunk, and then merge.
713 */
714 for (j = 0; j < overlapping_line_count; j++) {
715 overlap_next = find_next_line(&s->plain,
716 overlap_end);
717
718 if (overlap_next > hunk->end)
719 BUG("failed to find %d context lines "
720 "in:\n%.*s",
721 (int)overlapping_line_count,
722 (int)(hunk->end - hunk->start),
723 plain + hunk->start);
724
725 if (plain[overlap_end] != ' ')
726 return error(_("expected context line "
727 "#%d in\n%.*s"),
728 (int)(j + 1),
729 (int)(hunk->end
730 - hunk->start),
731 plain + hunk->start);
732
733 overlap_start = overlap_end;
734 overlap_end = overlap_next;
735 }
736 len = overlap_end - overlap_start;
737
738 if (len > merged->end - merged->start ||
739 memcmp(plain + merged->end - len,
740 plain + overlap_start, len))
741 return error(_("hunks do not overlap:\n%.*s\n"
742 "\tdoes not end with:\n%.*s"),
743 (int)(merged->end - merged->start),
744 plain + merged->start,
745 (int)len, plain + overlap_start);
746
747 /*
748 * Since the start-end ranges are not adjacent, we
749 * cannot simply take the union of the ranges. To
750 * address that, we temporarily append the union of the
751 * lines to the `plain` strbuf.
752 */
753 if (merged->end != s->plain.len) {
754 size_t start = s->plain.len;
755
756 strbuf_add(&s->plain, plain + merged->start,
757 merged->end - merged->start);
758 plain = s->plain.buf;
759 merged->start = start;
760 merged->end = s->plain.len;
761 }
762
763 strbuf_add(&s->plain,
764 plain + overlap_end,
765 hunk->end - overlap_end);
766 merged->end = s->plain.len;
767 merged->splittable_into += hunk->splittable_into;
768 delta = merged->delta;
769 merged->delta += hunk->delta;
770 }
11f2c0da
JS
771
772 header->old_count = next->old_offset + next->old_count
773 - header->old_offset;
bcdd297b
JS
774 header->new_count = next->new_offset + delta
775 + next->new_count - header->new_offset;
11f2c0da
JS
776 }
777
778 if (i == *hunk_index)
779 return 0;
780
781 *hunk_index = i;
782 return 1;
783}
784
80399aec 785static void reassemble_patch(struct add_p_state *s,
bcdd297b
JS
786 struct file_diff *file_diff, int use_all,
787 struct strbuf *out)
f6aa7ecc
JS
788{
789 struct hunk *hunk;
bcdd297b 790 size_t save_len = s->plain.len, i;
25ea47af 791 ssize_t delta = 0;
f6aa7ecc 792
5906d5de 793 render_diff_header(s, file_diff, 0, out);
f6aa7ecc 794
5906d5de 795 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
11f2c0da
JS
796 struct hunk merged = { 0 };
797
80399aec 798 hunk = file_diff->hunk + i;
bcdd297b 799 if (!use_all && hunk->use != USE_HUNK)
25ea47af
JS
800 delta += hunk->header.old_count
801 - hunk->header.new_count;
11f2c0da
JS
802 else {
803 /* merge overlapping hunks into a temporary hunk */
bcdd297b 804 if (merge_hunks(s, file_diff, &i, use_all, &merged))
11f2c0da
JS
805 hunk = &merged;
806
25ea47af 807 render_hunk(s, hunk, delta, 0, out);
bcdd297b
JS
808
809 /*
810 * In case `merge_hunks()` used `plain` as a scratch
811 * pad (this happens when an edited hunk had to be
812 * coalesced with another hunk).
813 */
814 strbuf_setlen(&s->plain, save_len);
815
816 delta += hunk->delta;
11f2c0da 817 }
f6aa7ecc
JS
818 }
819}
820
510aeca1
JS
821static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
822 size_t hunk_index)
823{
824 int colored = !!s->colored.len, first = 1;
825 struct hunk *hunk = file_diff->hunk + hunk_index;
826 size_t splittable_into;
827 size_t end, colored_end, current, colored_current = 0, context_line_count;
828 struct hunk_header remaining, *header;
829 char marker, ch;
830
831 if (hunk_index >= file_diff->hunk_nr)
832 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
833 (int)hunk_index, (int)file_diff->hunk_nr);
834
835 if (hunk->splittable_into < 2)
836 return 0;
837 splittable_into = hunk->splittable_into;
838
839 end = hunk->end;
840 colored_end = hunk->colored_end;
841
842 remaining = hunk->header;
843
844 file_diff->hunk_nr += splittable_into - 1;
845 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
846 if (hunk_index + splittable_into < file_diff->hunk_nr)
847 memmove(file_diff->hunk + hunk_index + splittable_into,
848 file_diff->hunk + hunk_index + 1,
849 (file_diff->hunk_nr - hunk_index - splittable_into)
850 * sizeof(*hunk));
851 hunk = file_diff->hunk + hunk_index;
852 hunk->splittable_into = 1;
853 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
854
855 header = &hunk->header;
856 header->old_count = header->new_count = 0;
857
858 current = hunk->start;
859 if (colored)
860 colored_current = hunk->colored_start;
861 marker = '\0';
862 context_line_count = 0;
863
864 while (splittable_into > 1) {
865 ch = s->plain.buf[current];
866
867 if (!ch)
868 BUG("buffer overrun while splitting hunks");
869
870 /*
871 * Is this the first context line after a chain of +/- lines?
872 * Then record the start of the next split hunk.
873 */
874 if ((marker == '-' || marker == '+') && ch == ' ') {
875 first = 0;
876 hunk[1].start = current;
877 if (colored)
878 hunk[1].colored_start = colored_current;
879 context_line_count = 0;
880 }
881
882 /*
883 * Was the previous line a +/- one? Alternatively, is this the
884 * first line (and not a +/- one)?
885 *
886 * Then just increment the appropriate counter and continue
887 * with the next line.
888 */
889 if (marker != ' ' || (ch != '-' && ch != '+')) {
890next_hunk_line:
891 /* Comment lines are attached to the previous line */
892 if (ch == '\\')
893 ch = marker ? marker : ' ';
894
895 /* current hunk not done yet */
896 if (ch == ' ')
897 context_line_count++;
898 else if (ch == '-')
899 header->old_count++;
900 else if (ch == '+')
901 header->new_count++;
902 else
903 BUG("unhandled diff marker: '%c'", ch);
904 marker = ch;
905 current = find_next_line(&s->plain, current);
906 if (colored)
907 colored_current =
908 find_next_line(&s->colored,
909 colored_current);
910 continue;
911 }
912
913 /*
914 * We got us the start of a new hunk!
915 *
916 * This is a context line, so it is shared with the previous
917 * hunk, if any.
918 */
919
920 if (first) {
921 if (header->old_count || header->new_count)
922 BUG("counts are off: %d/%d",
923 (int)header->old_count,
924 (int)header->new_count);
925
926 header->old_count = context_line_count;
927 header->new_count = context_line_count;
928 context_line_count = 0;
929 first = 0;
930 goto next_hunk_line;
931 }
932
933 remaining.old_offset += header->old_count;
934 remaining.old_count -= header->old_count;
935 remaining.new_offset += header->new_count;
936 remaining.new_count -= header->new_count;
937
938 /* initialize next hunk header's offsets */
939 hunk[1].header.old_offset =
940 header->old_offset + header->old_count;
941 hunk[1].header.new_offset =
942 header->new_offset + header->new_count;
943
944 /* add one split hunk */
945 header->old_count += context_line_count;
946 header->new_count += context_line_count;
947
948 hunk->end = current;
949 if (colored)
950 hunk->colored_end = colored_current;
951
952 hunk++;
953 hunk->splittable_into = 1;
954 hunk->use = hunk[-1].use;
955 header = &hunk->header;
956
957 header->old_count = header->new_count = context_line_count;
958 context_line_count = 0;
959
960 splittable_into--;
961 marker = ch;
962 }
963
964 /* last hunk simply gets the rest */
965 if (header->old_offset != remaining.old_offset)
966 BUG("miscounted old_offset: %lu != %lu",
967 header->old_offset, remaining.old_offset);
968 if (header->new_offset != remaining.new_offset)
969 BUG("miscounted new_offset: %lu != %lu",
970 header->new_offset, remaining.new_offset);
971 header->old_count = remaining.old_count;
972 header->new_count = remaining.new_count;
973 hunk->end = end;
974 if (colored)
975 hunk->colored_end = colored_end;
976
977 return 0;
978}
979
bcdd297b
JS
980static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
981{
982 const char *plain = s->plain.buf;
983 size_t current, eol, next;
984
985 if (!s->colored.len)
986 return;
987
988 hunk->colored_start = s->colored.len;
989 for (current = hunk->start; current < hunk->end; ) {
990 for (eol = current; eol < hunk->end; eol++)
991 if (plain[eol] == '\n')
992 break;
993 next = eol + (eol < hunk->end);
994 if (eol > current && plain[eol - 1] == '\r')
995 eol--;
996
997 strbuf_addstr(&s->colored,
998 plain[current] == '-' ?
999 s->s.file_old_color :
1000 plain[current] == '+' ?
1001 s->s.file_new_color :
1002 s->s.context_color);
1003 strbuf_add(&s->colored, plain + current, eol - current);
1004 strbuf_addstr(&s->colored, GIT_COLOR_RESET);
1005 if (next > eol)
1006 strbuf_add(&s->colored, plain + eol, next - eol);
1007 current = next;
1008 }
1009 hunk->colored_end = s->colored.len;
1010}
1011
1012static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1013{
1014 size_t i;
1015
1016 strbuf_reset(&s->buf);
1017 strbuf_commented_addf(&s->buf, _("Manual hunk edit mode -- see bottom for "
1018 "a quick guide.\n"));
1019 render_hunk(s, hunk, 0, 0, &s->buf);
1020 strbuf_commented_addf(&s->buf,
1021 _("---\n"
1022 "To remove '%c' lines, make them ' ' lines "
1023 "(context).\n"
1024 "To remove '%c' lines, delete them.\n"
1025 "Lines starting with %c will be removed.\n"),
d2a233cb
JS
1026 s->mode->is_reverse ? '+' : '-',
1027 s->mode->is_reverse ? '-' : '+',
1028 comment_line_char);
1029 strbuf_commented_addf(&s->buf, "%s", _(s->mode->edit_hunk_hint));
bcdd297b
JS
1030 /*
1031 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1032 * messages.
1033 */
1034 strbuf_commented_addf(&s->buf,
1035 _("If it does not apply cleanly, you will be "
1036 "given an opportunity to\n"
1037 "edit again. If all lines of the hunk are "
1038 "removed, then the edit is\n"
1039 "aborted and the hunk is left unchanged.\n"));
1040
1041 if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1042 return -1;
1043
1044 /* strip out commented lines */
1045 hunk->start = s->plain.len;
1046 for (i = 0; i < s->buf.len; ) {
1047 size_t next = find_next_line(&s->buf, i);
1048
1049 if (s->buf.buf[i] != comment_line_char)
1050 strbuf_add(&s->plain, s->buf.buf + i, next - i);
1051 i = next;
1052 }
1053
1054 hunk->end = s->plain.len;
1055 if (hunk->end == hunk->start)
1056 /* The user aborted editing by deleting everything */
1057 return 0;
1058
1059 recolor_hunk(s, hunk);
1060
1061 /*
1062 * If the hunk header is intact, parse it, otherwise simply use the
1063 * hunk header prior to editing (which will adjust `hunk->start` to
1064 * skip the hunk header).
1065 */
1066 if (s->plain.buf[hunk->start] == '@' &&
1067 parse_hunk_header(s, hunk) < 0)
1068 return error(_("could not parse hunk header"));
1069
1070 return 1;
1071}
1072
1073static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1074 size_t orig_old_count, size_t orig_new_count)
1075{
1076 struct hunk_header *header = &hunk->header;
1077 size_t i;
1078
1079 header->old_count = header->new_count = 0;
1080 for (i = hunk->start; i < hunk->end; ) {
1081 switch (s->plain.buf[i]) {
1082 case '-':
1083 header->old_count++;
1084 break;
1085 case '+':
1086 header->new_count++;
1087 break;
1088 case ' ': case '\r': case '\n':
1089 header->old_count++;
1090 header->new_count++;
1091 break;
1092 }
1093
1094 i = find_next_line(&s->plain, i);
1095 }
1096
1097 return orig_old_count - orig_new_count
1098 - header->old_count + header->new_count;
1099}
1100
1101static int run_apply_check(struct add_p_state *s,
1102 struct file_diff *file_diff)
1103{
1104 struct child_process cp = CHILD_PROCESS_INIT;
1105
1106 strbuf_reset(&s->buf);
1107 reassemble_patch(s, file_diff, 1, &s->buf);
1108
1109 setup_child_process(s, &cp,
d2a233cb
JS
1110 "apply", "--check", NULL);
1111 argv_array_pushv(&cp.args, s->mode->apply_check_args);
bcdd297b
JS
1112 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1113 return error(_("'git apply --cached' failed"));
1114
1115 return 0;
1116}
1117
1118static int prompt_yesno(struct add_p_state *s, const char *prompt)
1119{
1120 for (;;) {
1121 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1122 fflush(stdout);
1123 if (strbuf_getline(&s->answer, stdin) == EOF)
1124 return -1;
1125 strbuf_trim_trailing_newline(&s->answer);
1126 switch (tolower(s->answer.buf[0])) {
1127 case 'n': return 0;
1128 case 'y': return 1;
1129 }
1130 }
1131}
1132
1133static int edit_hunk_loop(struct add_p_state *s,
1134 struct file_diff *file_diff, struct hunk *hunk)
1135{
1136 size_t plain_len = s->plain.len, colored_len = s->colored.len;
1137 struct hunk backup;
1138
1139 backup = *hunk;
1140
1141 for (;;) {
1142 int res = edit_hunk_manually(s, hunk);
1143 if (res == 0) {
1144 /* abandonded */
1145 *hunk = backup;
1146 return -1;
1147 }
1148
1149 if (res > 0) {
1150 hunk->delta +=
1151 recount_edited_hunk(s, hunk,
1152 backup.header.old_count,
1153 backup.header.new_count);
1154 if (!run_apply_check(s, file_diff))
1155 return 0;
1156 }
1157
1158 /* Drop edits (they were appended to s->plain) */
1159 strbuf_setlen(&s->plain, plain_len);
1160 strbuf_setlen(&s->colored, colored_len);
1161 *hunk = backup;
1162
1163 /*
1164 * TRANSLATORS: do not translate [y/n]
1165 * The program will only accept that input at this point.
1166 * Consider translating (saying "no" discards!) as
1167 * (saying "n" for "no" discards!) if the translation
1168 * of the word "no" does not start with n.
1169 */
1170 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1171 "Edit again (saying \"no\" discards!) "
1172 "[y/n]? "));
1173 if (res < 1)
1174 return -1;
1175 }
1176}
1177
52628f94
JS
1178static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1179 int is_reverse)
1180{
1181 const char *reverse = is_reverse ? "-R" : NULL;
1182 struct child_process check_index = CHILD_PROCESS_INIT;
1183 struct child_process check_worktree = CHILD_PROCESS_INIT;
1184 struct child_process apply_index = CHILD_PROCESS_INIT;
1185 struct child_process apply_worktree = CHILD_PROCESS_INIT;
1186 int applies_index, applies_worktree;
1187
1188 setup_child_process(s, &check_index,
1189 "apply", "--cached", "--check", reverse, NULL);
1190 applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1191 NULL, 0, NULL, 0);
1192
1193 setup_child_process(s, &check_worktree,
1194 "apply", "--check", reverse, NULL);
1195 applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1196 NULL, 0, NULL, 0);
1197
1198 if (applies_worktree && applies_index) {
1199 setup_child_process(s, &apply_index,
1200 "apply", "--cached", reverse, NULL);
1201 pipe_command(&apply_index, diff->buf, diff->len,
1202 NULL, 0, NULL, 0);
1203
1204 setup_child_process(s, &apply_worktree,
1205 "apply", reverse, NULL);
1206 pipe_command(&apply_worktree, diff->buf, diff->len,
1207 NULL, 0, NULL, 0);
1208
1209 return 1;
1210 }
1211
1212 if (!applies_index) {
1213 err(s, _("The selected hunks do not apply to the index!"));
1214 if (prompt_yesno(s, _("Apply them to the worktree "
1215 "anyway? ")) > 0) {
1216 setup_child_process(s, &apply_worktree,
1217 "apply", reverse, NULL);
1218 return pipe_command(&apply_worktree, diff->buf,
1219 diff->len, NULL, 0, NULL, 0);
1220 }
1221 err(s, _("Nothing was applied.\n"));
1222 } else
1223 /* As a last resort, show the diff to the user */
1224 fwrite(diff->buf, diff->len, 1, stderr);
1225
1226 return 0;
1227}
1228
9254bdfb
JS
1229#define SUMMARY_HEADER_WIDTH 20
1230#define SUMMARY_LINE_WIDTH 80
1231static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1232 struct strbuf *out)
1233{
1234 struct hunk_header *header = &hunk->header;
1235 struct strbuf *plain = &s->plain;
1236 size_t len = out->len, i;
1237
1238 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1239 header->old_offset, header->old_count,
1240 header->new_offset, header->new_count);
1241 if (out->len - len < SUMMARY_HEADER_WIDTH)
1242 strbuf_addchars(out, ' ',
1243 SUMMARY_HEADER_WIDTH + len - out->len);
1244 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1245 if (plain->buf[i] != ' ')
1246 break;
1247 if (i < hunk->end)
1248 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1249 if (out->len - len > SUMMARY_LINE_WIDTH)
1250 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1251 strbuf_complete_line(out);
1252}
1253
1254#define DISPLAY_HUNKS_LINES 20
1255static size_t display_hunks(struct add_p_state *s,
1256 struct file_diff *file_diff, size_t start_index)
1257{
1258 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1259
1260 if (end_index > file_diff->hunk_nr)
1261 end_index = file_diff->hunk_nr;
1262
1263 while (start_index < end_index) {
1264 struct hunk *hunk = file_diff->hunk + start_index++;
1265
1266 strbuf_reset(&s->buf);
1267 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1268 : hunk->use == SKIP_HUNK ? '-' : ' ',
1269 (int)start_index);
1270 summarize_hunk(s, hunk, &s->buf);
1271 fputs(s->buf.buf, stdout);
1272 }
1273
1274 return end_index;
1275}
1276
54d9d9b2
JS
1277static const char help_patch_remainder[] =
1278N_("j - leave this hunk undecided, see next undecided hunk\n"
f6aa7ecc
JS
1279 "J - leave this hunk undecided, see next hunk\n"
1280 "k - leave this hunk undecided, see previous undecided hunk\n"
1281 "K - leave this hunk undecided, see previous hunk\n"
9254bdfb 1282 "g - select a hunk to go to\n"
d6cf8733 1283 "/ - search for a hunk matching the given regex\n"
510aeca1 1284 "s - split the current hunk into smaller hunks\n"
bcdd297b 1285 "e - manually edit the current hunk\n"
f6aa7ecc
JS
1286 "? - print help\n");
1287
80399aec
JS
1288static int patch_update_file(struct add_p_state *s,
1289 struct file_diff *file_diff)
f6aa7ecc
JS
1290{
1291 size_t hunk_index = 0;
1292 ssize_t i, undecided_previous, undecided_next;
1293 struct hunk *hunk;
1294 char ch;
1295 struct child_process cp = CHILD_PROCESS_INIT;
ade246ef 1296 int colored = !!s->colored.len, quit = 0;
0ecd9d27 1297 enum prompt_mode_type prompt_mode_type;
f6aa7ecc 1298
80399aec 1299 if (!file_diff->hunk_nr)
f6aa7ecc
JS
1300 return 0;
1301
1302 strbuf_reset(&s->buf);
5906d5de 1303 render_diff_header(s, file_diff, colored, &s->buf);
f6aa7ecc
JS
1304 fputs(s->buf.buf, stdout);
1305 for (;;) {
80399aec 1306 if (hunk_index >= file_diff->hunk_nr)
f6aa7ecc 1307 hunk_index = 0;
80399aec 1308 hunk = file_diff->hunk + hunk_index;
f6aa7ecc
JS
1309
1310 undecided_previous = -1;
1311 for (i = hunk_index - 1; i >= 0; i--)
80399aec 1312 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
f6aa7ecc
JS
1313 undecided_previous = i;
1314 break;
1315 }
1316
1317 undecided_next = -1;
80399aec
JS
1318 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1319 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
f6aa7ecc
JS
1320 undecided_next = i;
1321 break;
1322 }
1323
1324 /* Everything decided? */
1325 if (undecided_previous < 0 && undecided_next < 0 &&
1326 hunk->use != UNDECIDED_HUNK)
1327 break;
1328
1329 strbuf_reset(&s->buf);
25ea47af 1330 render_hunk(s, hunk, 0, colored, &s->buf);
f6aa7ecc
JS
1331 fputs(s->buf.buf, stdout);
1332
1333 strbuf_reset(&s->buf);
1334 if (undecided_previous >= 0)
1335 strbuf_addstr(&s->buf, ",k");
1336 if (hunk_index)
1337 strbuf_addstr(&s->buf, ",K");
1338 if (undecided_next >= 0)
1339 strbuf_addstr(&s->buf, ",j");
80399aec 1340 if (hunk_index + 1 < file_diff->hunk_nr)
f6aa7ecc 1341 strbuf_addstr(&s->buf, ",J");
9254bdfb 1342 if (file_diff->hunk_nr > 1)
d6cf8733 1343 strbuf_addstr(&s->buf, ",g,/");
510aeca1
JS
1344 if (hunk->splittable_into > 1)
1345 strbuf_addstr(&s->buf, ",s");
bcdd297b
JS
1346 if (hunk_index + 1 > file_diff->mode_change &&
1347 !file_diff->deleted)
1348 strbuf_addstr(&s->buf, ",e");
0ecd9d27
JS
1349
1350 if (file_diff->deleted)
1351 prompt_mode_type = PROMPT_DELETION;
1352 else if (file_diff->mode_change && !hunk_index)
1353 prompt_mode_type = PROMPT_MODE_CHANGE;
1354 else
1355 prompt_mode_type = PROMPT_HUNK;
1356
12c24cf8
JS
1357 color_fprintf(stdout, s->s.prompt_color,
1358 "(%"PRIuMAX"/%"PRIuMAX") ",
80399aec
JS
1359 (uintmax_t)hunk_index + 1,
1360 (uintmax_t)file_diff->hunk_nr);
12c24cf8 1361 color_fprintf(stdout, s->s.prompt_color,
d2a233cb
JS
1362 _(s->mode->prompt_mode[prompt_mode_type]),
1363 s->buf.buf);
f6aa7ecc
JS
1364 fflush(stdout);
1365 if (strbuf_getline(&s->answer, stdin) == EOF)
1366 break;
1367 strbuf_trim_trailing_newline(&s->answer);
1368
1369 if (!s->answer.len)
1370 continue;
1371 ch = tolower(s->answer.buf[0]);
1372 if (ch == 'y') {
1373 hunk->use = USE_HUNK;
1374soft_increment:
1375 hunk_index = undecided_next < 0 ?
80399aec 1376 file_diff->hunk_nr : undecided_next;
f6aa7ecc
JS
1377 } else if (ch == 'n') {
1378 hunk->use = SKIP_HUNK;
1379 goto soft_increment;
1380 } else if (ch == 'a') {
80399aec
JS
1381 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1382 hunk = file_diff->hunk + hunk_index;
f6aa7ecc
JS
1383 if (hunk->use == UNDECIDED_HUNK)
1384 hunk->use = USE_HUNK;
1385 }
ade246ef 1386 } else if (ch == 'd' || ch == 'q') {
80399aec
JS
1387 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1388 hunk = file_diff->hunk + hunk_index;
f6aa7ecc
JS
1389 if (hunk->use == UNDECIDED_HUNK)
1390 hunk->use = SKIP_HUNK;
1391 }
ade246ef
JS
1392 if (ch == 'q') {
1393 quit = 1;
1394 break;
1395 }
7584dd3c
JS
1396 } else if (s->answer.buf[0] == 'K') {
1397 if (hunk_index)
1398 hunk_index--;
1399 else
1400 err(s, _("No previous hunk"));
1401 } else if (s->answer.buf[0] == 'J') {
80399aec 1402 if (hunk_index + 1 < file_diff->hunk_nr)
7584dd3c
JS
1403 hunk_index++;
1404 else
1405 err(s, _("No next hunk"));
1406 } else if (s->answer.buf[0] == 'k') {
1407 if (undecided_previous >= 0)
1408 hunk_index = undecided_previous;
1409 else
1410 err(s, _("No previous hunk"));
1411 } else if (s->answer.buf[0] == 'j') {
1412 if (undecided_next >= 0)
1413 hunk_index = undecided_next;
1414 else
1415 err(s, _("No next hunk"));
9254bdfb
JS
1416 } else if (s->answer.buf[0] == 'g') {
1417 char *pend;
1418 unsigned long response;
1419
1420 if (file_diff->hunk_nr < 2) {
1421 err(s, _("No other hunks to goto"));
1422 continue;
1423 }
1424 strbuf_remove(&s->answer, 0, 1);
1425 strbuf_trim(&s->answer);
1426 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1427 if (i < file_diff->mode_change)
1428 i = file_diff->mode_change;
1429 while (s->answer.len == 0) {
1430 i = display_hunks(s, file_diff, i);
1431 printf("%s", i < file_diff->hunk_nr ?
1432 _("go to which hunk (<ret> to see "
1433 "more)? ") : _("go to which hunk? "));
1434 fflush(stdout);
1435 if (strbuf_getline(&s->answer,
1436 stdin) == EOF)
1437 break;
1438 strbuf_trim_trailing_newline(&s->answer);
1439 }
1440
1441 strbuf_trim(&s->answer);
1442 response = strtoul(s->answer.buf, &pend, 10);
1443 if (*pend || pend == s->answer.buf)
1444 err(s, _("Invalid number: '%s'"),
1445 s->answer.buf);
1446 else if (0 < response && response <= file_diff->hunk_nr)
1447 hunk_index = response - 1;
1448 else
1449 err(s, Q_("Sorry, only %d hunk available.",
1450 "Sorry, only %d hunks available.",
1451 file_diff->hunk_nr),
1452 (int)file_diff->hunk_nr);
d6cf8733
JS
1453 } else if (s->answer.buf[0] == '/') {
1454 regex_t regex;
1455 int ret;
1456
1457 if (file_diff->hunk_nr < 2) {
1458 err(s, _("No other hunks to search"));
1459 continue;
1460 }
1461 strbuf_remove(&s->answer, 0, 1);
1462 strbuf_trim_trailing_newline(&s->answer);
1463 if (s->answer.len == 0) {
1464 printf("%s", _("search for regex? "));
1465 fflush(stdout);
1466 if (strbuf_getline(&s->answer,
1467 stdin) == EOF)
1468 break;
1469 strbuf_trim_trailing_newline(&s->answer);
1470 if (s->answer.len == 0)
1471 continue;
1472 }
1473 ret = regcomp(&regex, s->answer.buf,
1474 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1475 if (ret) {
1476 char errbuf[1024];
1477
1478 regerror(ret, &regex, errbuf, sizeof(errbuf));
1479 err(s, _("Malformed search regexp %s: %s"),
1480 s->answer.buf, errbuf);
1481 continue;
1482 }
1483 i = hunk_index;
1484 for (;;) {
1485 /* render the hunk into a scratch buffer */
1486 render_hunk(s, file_diff->hunk + i, 0, 0,
1487 &s->buf);
1488 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1489 != REG_NOMATCH)
1490 break;
1491 i++;
1492 if (i == file_diff->hunk_nr)
1493 i = 0;
1494 if (i != hunk_index)
1495 continue;
1496 err(s, _("No hunk matches the given pattern"));
1497 break;
1498 }
1499 hunk_index = i;
510aeca1
JS
1500 } else if (s->answer.buf[0] == 's') {
1501 size_t splittable_into = hunk->splittable_into;
1502 if (splittable_into < 2)
1503 err(s, _("Sorry, cannot split this hunk"));
1504 else if (!split_hunk(s, file_diff,
1505 hunk - file_diff->hunk))
1506 color_fprintf_ln(stdout, s->s.header_color,
1507 _("Split into %d hunks."),
1508 (int)splittable_into);
bcdd297b
JS
1509 } else if (s->answer.buf[0] == 'e') {
1510 if (hunk_index + 1 == file_diff->mode_change)
1511 err(s, _("Sorry, cannot edit this hunk"));
1512 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1513 hunk->use = USE_HUNK;
1514 goto soft_increment;
1515 }
54d9d9b2
JS
1516 } else {
1517 const char *p = _(help_patch_remainder), *eol = p;
1518
1519 color_fprintf(stdout, s->s.help_color, "%s",
d2a233cb 1520 _(s->mode->help_patch_text));
54d9d9b2
JS
1521
1522 /*
1523 * Show only those lines of the remainder that are
1524 * actually applicable with the current hunk.
1525 */
1526 for (; *p; p = eol + (*eol == '\n')) {
1527 eol = strchrnul(p, '\n');
1528
1529 /*
1530 * `s->buf` still contains the part of the
1531 * commands shown in the prompt that are not
1532 * always available.
1533 */
1534 if (*p != '?' && !strchr(s->buf.buf, *p))
1535 continue;
1536
1537 color_fprintf_ln(stdout, s->s.help_color,
1538 "%.*s", (int)(eol - p), p);
1539 }
1540 }
f6aa7ecc
JS
1541 }
1542
1543 /* Any hunk to be used? */
80399aec
JS
1544 for (i = 0; i < file_diff->hunk_nr; i++)
1545 if (file_diff->hunk[i].use == USE_HUNK)
f6aa7ecc
JS
1546 break;
1547
80399aec 1548 if (i < file_diff->hunk_nr) {
f6aa7ecc
JS
1549 /* At least one hunk selected: apply */
1550 strbuf_reset(&s->buf);
bcdd297b 1551 reassemble_patch(s, file_diff, 0, &s->buf);
f6aa7ecc 1552
25ea47af 1553 discard_index(s->s.r->index);
52628f94
JS
1554 if (s->mode->apply_for_checkout)
1555 apply_for_checkout(s, &s->buf,
1556 s->mode->is_reverse);
1557 else {
1558 setup_child_process(s, &cp, "apply", NULL);
1559 argv_array_pushv(&cp.args, s->mode->apply_args);
1560 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1561 NULL, 0, NULL, 0))
1562 error(_("'git apply' failed"));
1563 }
25ea47af
JS
1564 if (!repo_read_index(s->s.r))
1565 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
f6aa7ecc
JS
1566 1, NULL, NULL, NULL);
1567 }
1568
1569 putchar('\n');
ade246ef 1570 return quit;
f6aa7ecc
JS
1571}
1572
d2a233cb
JS
1573int run_add_p(struct repository *r, enum add_p_mode mode,
1574 const char *revision, const struct pathspec *ps)
f6aa7ecc 1575{
25ea47af
JS
1576 struct add_p_state s = {
1577 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1578 };
2e408319 1579 size_t i, binary_count = 0;
25ea47af
JS
1580
1581 init_add_i_state(&s.s, r);
f6aa7ecc 1582
36bae1dc
JS
1583 if (mode == ADD_P_STASH)
1584 s.mode = &patch_mode_stash;
1585 else if (mode == ADD_P_RESET) {
1586 if (!revision || !strcmp(revision, "HEAD"))
1587 s.mode = &patch_mode_reset_head;
1588 else
1589 s.mode = &patch_mode_reset_nothead;
52628f94
JS
1590 } else if (mode == ADD_P_CHECKOUT) {
1591 if (!revision)
1592 s.mode = &patch_mode_checkout_index;
1593 else if (!strcmp(revision, "HEAD"))
1594 s.mode = &patch_mode_checkout_head;
1595 else
1596 s.mode = &patch_mode_checkout_nothead;
cee6cb73
JS
1597 } else if (mode == ADD_P_WORKTREE) {
1598 if (!revision)
1599 s.mode = &patch_mode_checkout_index;
1600 else if (!strcmp(revision, "HEAD"))
1601 s.mode = &patch_mode_worktree_head;
1602 else
1603 s.mode = &patch_mode_worktree_nothead;
36bae1dc
JS
1604 } else
1605 s.mode = &patch_mode_add;
d2a233cb
JS
1606 s.revision = revision;
1607
f6aa7ecc 1608 if (discard_index(r->index) < 0 || repo_read_index(r) < 0 ||
36bae1dc
JS
1609 (!s.mode->index_only &&
1610 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1611 NULL, NULL, NULL) < 0) ||
f6aa7ecc
JS
1612 parse_diff(&s, ps) < 0) {
1613 strbuf_release(&s.plain);
e3bd11b4 1614 strbuf_release(&s.colored);
f6aa7ecc
JS
1615 return -1;
1616 }
1617
80399aec 1618 for (i = 0; i < s.file_diff_nr; i++)
2e408319
JS
1619 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1620 binary_count++;
1621 else if (patch_update_file(&s, s.file_diff + i))
80399aec 1622 break;
f6aa7ecc 1623
2e408319
JS
1624 if (s.file_diff_nr == 0)
1625 fprintf(stderr, _("No changes.\n"));
1626 else if (binary_count == s.file_diff_nr)
1627 fprintf(stderr, _("Only binary files changed.\n"));
1628
f6aa7ecc
JS
1629 strbuf_release(&s.answer);
1630 strbuf_release(&s.buf);
1631 strbuf_release(&s.plain);
e3bd11b4 1632 strbuf_release(&s.colored);
f6aa7ecc
JS
1633 return 0;
1634}