]> git.ipfire.org Git - thirdparty/git.git/blame - add-patch.c
built-in add -p: support interactive.diffFilter
[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;
180f48df 401 const char *diff_filter = s->s.interactive_diff_filter;
e3bd11b4
JS
402
403 setup_child_process(s, &colored_cp, NULL);
404 xsnprintf((char *)args.argv[color_arg_index], 8, "--color");
405 colored_cp.argv = args.argv;
406 colored = &s->colored;
407 res = capture_command(&colored_cp, colored, 0);
408 argv_array_clear(&args);
409 if (res)
410 return error(_("could not parse colored diff"));
180f48df
JS
411
412 if (diff_filter) {
413 struct child_process filter_cp = CHILD_PROCESS_INIT;
414
415 setup_child_process(s, &filter_cp,
416 diff_filter, NULL);
417 filter_cp.git_cmd = 0;
418 filter_cp.use_shell = 1;
419 strbuf_reset(&s->buf);
420 if (pipe_command(&filter_cp,
421 colored->buf, colored->len,
422 &s->buf, colored->len,
423 NULL, 0) < 0)
424 return error(_("failed to run '%s'"),
425 diff_filter);
426 strbuf_swap(colored, &s->buf);
427 }
428
e3bd11b4
JS
429 strbuf_complete_line(colored);
430 colored_p = colored->buf;
431 colored_pend = colored_p + colored->len;
432 }
433 argv_array_clear(&args);
434
80399aec 435 /* parse files and hunks */
f6aa7ecc
JS
436 p = plain->buf;
437 pend = p + plain->len;
438 while (p != pend) {
439 char *eol = memchr(p, '\n', pend - p);
5906d5de 440 const char *deleted = NULL, *mode_change = NULL;
47dc4fd5 441
f6aa7ecc
JS
442 if (!eol)
443 eol = pend;
444
445 if (starts_with(p, "diff ")) {
80399aec
JS
446 s->file_diff_nr++;
447 ALLOC_GROW(s->file_diff, s->file_diff_nr,
448 file_diff_alloc);
449 file_diff = s->file_diff + s->file_diff_nr - 1;
450 memset(file_diff, 0, sizeof(*file_diff));
451 hunk = &file_diff->head;
452 hunk->start = p - plain->buf;
453 if (colored_p)
454 hunk->colored_start = colored_p - colored->buf;
510aeca1 455 marker = '\0';
f6aa7ecc
JS
456 } else if (p == plain->buf)
457 BUG("diff starts with unexpected line:\n"
458 "%.*s\n", (int)(eol - p), p);
47dc4fd5
JS
459 else if (file_diff->deleted)
460 ; /* keep the rest of the file in a single "hunk" */
461 else if (starts_with(p, "@@ ") ||
462 (hunk == &file_diff->head &&
463 skip_prefix(p, "deleted file", &deleted))) {
510aeca1
JS
464 if (marker == '-' || marker == '+')
465 /*
466 * Should not happen; previous hunk did not end
467 * in a context line? Handle it anyway.
468 */
469 hunk->splittable_into++;
470
80399aec
JS
471 file_diff->hunk_nr++;
472 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
473 file_diff->hunk_alloc);
474 hunk = file_diff->hunk + file_diff->hunk_nr - 1;
f6aa7ecc
JS
475 memset(hunk, 0, sizeof(*hunk));
476
477 hunk->start = p - plain->buf;
e3bd11b4
JS
478 if (colored)
479 hunk->colored_start = colored_p - colored->buf;
25ea47af 480
47dc4fd5
JS
481 if (deleted)
482 file_diff->deleted = 1;
483 else if (parse_hunk_header(s, hunk) < 0)
25ea47af 484 return -1;
510aeca1
JS
485
486 /*
487 * Start counting into how many hunks this one can be
488 * split
489 */
490 marker = *p;
5906d5de
JS
491 } else if (hunk == &file_diff->head &&
492 skip_prefix(p, "old mode ", &mode_change) &&
493 is_octal(mode_change, eol - mode_change)) {
494 if (file_diff->mode_change)
495 BUG("double mode change?\n\n%.*s",
496 (int)(eol - plain->buf), plain->buf);
497 if (file_diff->hunk_nr++)
498 BUG("mode change in the middle?\n\n%.*s",
499 (int)(eol - plain->buf), plain->buf);
500
501 /*
502 * Do *not* change `hunk`: the mode change pseudo-hunk
503 * is _part of_ the header "hunk".
504 */
505 file_diff->mode_change = 1;
506 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr,
507 file_diff->hunk_alloc);
508 memset(file_diff->hunk, 0, sizeof(struct hunk));
509 file_diff->hunk->start = p - plain->buf;
510 if (colored_p)
511 file_diff->hunk->colored_start =
512 colored_p - colored->buf;
513 } else if (hunk == &file_diff->head &&
514 skip_prefix(p, "new mode ", &mode_change) &&
515 is_octal(mode_change, eol - mode_change)) {
516
517 /*
518 * Extend the "mode change" pseudo-hunk to include also
519 * the "new mode" line.
520 */
521 if (!file_diff->mode_change)
522 BUG("'new mode' without 'old mode'?\n\n%.*s",
523 (int)(eol - plain->buf), plain->buf);
524 if (file_diff->hunk_nr != 1)
525 BUG("mode change in the middle?\n\n%.*s",
526 (int)(eol - plain->buf), plain->buf);
527 if (p - plain->buf != file_diff->hunk->end)
528 BUG("'new mode' does not immediately follow "
529 "'old mode'?\n\n%.*s",
530 (int)(eol - plain->buf), plain->buf);
2e408319
JS
531 } else if (hunk == &file_diff->head &&
532 starts_with(p, "Binary files "))
533 file_diff->binary = 1;
f6aa7ecc 534
5906d5de
JS
535 if (file_diff->deleted && file_diff->mode_change)
536 BUG("diff contains delete *and* a mode change?!?\n%.*s",
537 (int)(eol - (plain->buf + file_diff->head.start)),
538 plain->buf + file_diff->head.start);
539
510aeca1
JS
540 if ((marker == '-' || marker == '+') && *p == ' ')
541 hunk->splittable_into++;
542 if (marker && *p != '\\')
543 marker = *p;
544
f6aa7ecc
JS
545 p = eol == pend ? pend : eol + 1;
546 hunk->end = p - plain->buf;
e3bd11b4
JS
547
548 if (colored) {
549 char *colored_eol = memchr(colored_p, '\n',
550 colored_pend - colored_p);
551 if (colored_eol)
552 colored_p = colored_eol + 1;
180f48df
JS
553 else if (p != pend)
554 /* colored shorter than non-colored? */
555 goto mismatched_output;
e3bd11b4
JS
556 else
557 colored_p = colored_pend;
558
559 hunk->colored_end = colored_p - colored->buf;
560 }
5906d5de
JS
561
562 if (mode_change) {
563 if (file_diff->hunk_nr != 1)
564 BUG("mode change in hunk #%d???",
565 (int)file_diff->hunk_nr);
566 /* Adjust the end of the "mode change" pseudo-hunk */
567 file_diff->hunk->end = hunk->end;
568 if (colored)
569 file_diff->hunk->colored_end = hunk->colored_end;
570 }
f6aa7ecc
JS
571 }
572
510aeca1
JS
573 if (marker == '-' || marker == '+')
574 /*
575 * Last hunk ended in non-context line (i.e. it appended lines
576 * to the file, so there are no trailing context lines).
577 */
578 hunk->splittable_into++;
579
180f48df
JS
580 /* non-colored shorter than colored? */
581 if (colored_p != colored_pend) {
582mismatched_output:
583 error(_("mismatched output from interactive.diffFilter"));
584 advise(_("Your filter must maintain a one-to-one correspondence\n"
585 "between its input and output lines."));
586 return -1;
587 }
588
f6aa7ecc
JS
589 return 0;
590}
591
510aeca1
JS
592static size_t find_next_line(struct strbuf *sb, size_t offset)
593{
594 char *eol;
595
596 if (offset >= sb->len)
597 BUG("looking for next line beyond buffer (%d >= %d)\n%s",
598 (int)offset, (int)sb->len, sb->buf);
599
600 eol = memchr(sb->buf + offset, '\n', sb->len - offset);
601 if (!eol)
602 return sb->len;
603 return eol - sb->buf + 1;
604}
605
f6aa7ecc 606static void render_hunk(struct add_p_state *s, struct hunk *hunk,
25ea47af 607 ssize_t delta, int colored, struct strbuf *out)
f6aa7ecc 608{
25ea47af
JS
609 struct hunk_header *header = &hunk->header;
610
611 if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
612 /*
613 * Generate the hunk header dynamically, except for special
614 * hunks (such as the diff header).
615 */
616 const char *p;
617 size_t len;
618 unsigned long old_offset = header->old_offset;
619 unsigned long new_offset = header->new_offset;
620
621 if (!colored) {
622 p = s->plain.buf + header->extra_start;
623 len = header->extra_end - header->extra_start;
624 } else {
625 strbuf_addstr(out, s->s.fraginfo_color);
626 p = s->colored.buf + header->colored_extra_start;
627 len = header->colored_extra_end
628 - header->colored_extra_start;
629 }
630
d2a233cb
JS
631 if (s->mode->is_reverse)
632 old_offset -= delta;
633 else
634 new_offset += delta;
25ea47af
JS
635
636 strbuf_addf(out, "@@ -%lu,%lu +%lu,%lu @@",
637 old_offset, header->old_count,
638 new_offset, header->new_count);
639 if (len)
640 strbuf_add(out, p, len);
641 else if (colored)
642 strbuf_addf(out, "%s\n", GIT_COLOR_RESET);
643 else
644 strbuf_addch(out, '\n');
645 }
646
e3bd11b4
JS
647 if (colored)
648 strbuf_add(out, s->colored.buf + hunk->colored_start,
649 hunk->colored_end - hunk->colored_start);
650 else
651 strbuf_add(out, s->plain.buf + hunk->start,
652 hunk->end - hunk->start);
f6aa7ecc
JS
653}
654
5906d5de
JS
655static void render_diff_header(struct add_p_state *s,
656 struct file_diff *file_diff, int colored,
657 struct strbuf *out)
658{
659 /*
660 * If there was a mode change, the first hunk is a pseudo hunk that
661 * corresponds to the mode line in the header. If the user did not want
662 * to stage that "hunk", we actually have to cut it out from the header.
663 */
664 int skip_mode_change =
665 file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
666 struct hunk *head = &file_diff->head, *first = file_diff->hunk;
667
668 if (!skip_mode_change) {
669 render_hunk(s, head, 0, colored, out);
670 return;
671 }
672
673 if (colored) {
674 const char *p = s->colored.buf;
675
676 strbuf_add(out, p + head->colored_start,
677 first->colored_start - head->colored_start);
678 strbuf_add(out, p + first->colored_end,
679 head->colored_end - first->colored_end);
680 } else {
681 const char *p = s->plain.buf;
682
683 strbuf_add(out, p + head->start, first->start - head->start);
684 strbuf_add(out, p + first->end, head->end - first->end);
685 }
686}
687
11f2c0da
JS
688/* Coalesce hunks again that were split */
689static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
bcdd297b 690 size_t *hunk_index, int use_all, struct hunk *merged)
11f2c0da 691{
bcdd297b 692 size_t i = *hunk_index, delta;
11f2c0da
JS
693 struct hunk *hunk = file_diff->hunk + i;
694 /* `header` corresponds to the merged hunk */
695 struct hunk_header *header = &merged->header, *next;
696
bcdd297b 697 if (!use_all && hunk->use != USE_HUNK)
11f2c0da
JS
698 return 0;
699
700 *merged = *hunk;
701 /* We simply skip the colored part (if any) when merging hunks */
702 merged->colored_start = merged->colored_end = 0;
703
704 for (; i + 1 < file_diff->hunk_nr; i++) {
705 hunk++;
706 next = &hunk->header;
707
708 /*
709 * Stop merging hunks when:
710 *
711 * - the hunk is not selected for use, or
712 * - the hunk does not overlap with the already-merged hunk(s)
713 */
bcdd297b
JS
714 if ((!use_all && hunk->use != USE_HUNK) ||
715 header->new_offset >= next->new_offset + merged->delta ||
716 header->new_offset + header->new_count
717 < next->new_offset + merged->delta)
11f2c0da
JS
718 break;
719
bcdd297b
JS
720 /*
721 * If the hunks were not edited, and overlap, we can simply
722 * extend the line range.
723 */
724 if (merged->start < hunk->start && merged->end > hunk->start) {
725 merged->end = hunk->end;
726 merged->colored_end = hunk->colored_end;
727 delta = 0;
728 } else {
729 const char *plain = s->plain.buf;
730 size_t overlapping_line_count = header->new_offset
731 + header->new_count - merged->delta
732 - next->new_offset;
733 size_t overlap_end = hunk->start;
734 size_t overlap_start = overlap_end;
735 size_t overlap_next, len, j;
736
737 /*
738 * One of the hunks was edited: the modified hunk was
739 * appended to the strbuf `s->plain`.
740 *
741 * Let's ensure that at least the last context line of
742 * the first hunk overlaps with the corresponding line
743 * of the second hunk, and then merge.
744 */
745 for (j = 0; j < overlapping_line_count; j++) {
746 overlap_next = find_next_line(&s->plain,
747 overlap_end);
748
749 if (overlap_next > hunk->end)
750 BUG("failed to find %d context lines "
751 "in:\n%.*s",
752 (int)overlapping_line_count,
753 (int)(hunk->end - hunk->start),
754 plain + hunk->start);
755
756 if (plain[overlap_end] != ' ')
757 return error(_("expected context line "
758 "#%d in\n%.*s"),
759 (int)(j + 1),
760 (int)(hunk->end
761 - hunk->start),
762 plain + hunk->start);
763
764 overlap_start = overlap_end;
765 overlap_end = overlap_next;
766 }
767 len = overlap_end - overlap_start;
768
769 if (len > merged->end - merged->start ||
770 memcmp(plain + merged->end - len,
771 plain + overlap_start, len))
772 return error(_("hunks do not overlap:\n%.*s\n"
773 "\tdoes not end with:\n%.*s"),
774 (int)(merged->end - merged->start),
775 plain + merged->start,
776 (int)len, plain + overlap_start);
777
778 /*
779 * Since the start-end ranges are not adjacent, we
780 * cannot simply take the union of the ranges. To
781 * address that, we temporarily append the union of the
782 * lines to the `plain` strbuf.
783 */
784 if (merged->end != s->plain.len) {
785 size_t start = s->plain.len;
786
787 strbuf_add(&s->plain, plain + merged->start,
788 merged->end - merged->start);
789 plain = s->plain.buf;
790 merged->start = start;
791 merged->end = s->plain.len;
792 }
793
794 strbuf_add(&s->plain,
795 plain + overlap_end,
796 hunk->end - overlap_end);
797 merged->end = s->plain.len;
798 merged->splittable_into += hunk->splittable_into;
799 delta = merged->delta;
800 merged->delta += hunk->delta;
801 }
11f2c0da
JS
802
803 header->old_count = next->old_offset + next->old_count
804 - header->old_offset;
bcdd297b
JS
805 header->new_count = next->new_offset + delta
806 + next->new_count - header->new_offset;
11f2c0da
JS
807 }
808
809 if (i == *hunk_index)
810 return 0;
811
812 *hunk_index = i;
813 return 1;
814}
815
80399aec 816static void reassemble_patch(struct add_p_state *s,
bcdd297b
JS
817 struct file_diff *file_diff, int use_all,
818 struct strbuf *out)
f6aa7ecc
JS
819{
820 struct hunk *hunk;
bcdd297b 821 size_t save_len = s->plain.len, i;
25ea47af 822 ssize_t delta = 0;
f6aa7ecc 823
5906d5de 824 render_diff_header(s, file_diff, 0, out);
f6aa7ecc 825
5906d5de 826 for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
11f2c0da
JS
827 struct hunk merged = { 0 };
828
80399aec 829 hunk = file_diff->hunk + i;
bcdd297b 830 if (!use_all && hunk->use != USE_HUNK)
25ea47af
JS
831 delta += hunk->header.old_count
832 - hunk->header.new_count;
11f2c0da
JS
833 else {
834 /* merge overlapping hunks into a temporary hunk */
bcdd297b 835 if (merge_hunks(s, file_diff, &i, use_all, &merged))
11f2c0da
JS
836 hunk = &merged;
837
25ea47af 838 render_hunk(s, hunk, delta, 0, out);
bcdd297b
JS
839
840 /*
841 * In case `merge_hunks()` used `plain` as a scratch
842 * pad (this happens when an edited hunk had to be
843 * coalesced with another hunk).
844 */
845 strbuf_setlen(&s->plain, save_len);
846
847 delta += hunk->delta;
11f2c0da 848 }
f6aa7ecc
JS
849 }
850}
851
510aeca1
JS
852static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
853 size_t hunk_index)
854{
855 int colored = !!s->colored.len, first = 1;
856 struct hunk *hunk = file_diff->hunk + hunk_index;
857 size_t splittable_into;
858 size_t end, colored_end, current, colored_current = 0, context_line_count;
859 struct hunk_header remaining, *header;
860 char marker, ch;
861
862 if (hunk_index >= file_diff->hunk_nr)
863 BUG("invalid hunk index: %d (must be >= 0 and < %d)",
864 (int)hunk_index, (int)file_diff->hunk_nr);
865
866 if (hunk->splittable_into < 2)
867 return 0;
868 splittable_into = hunk->splittable_into;
869
870 end = hunk->end;
871 colored_end = hunk->colored_end;
872
873 remaining = hunk->header;
874
875 file_diff->hunk_nr += splittable_into - 1;
876 ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
877 if (hunk_index + splittable_into < file_diff->hunk_nr)
878 memmove(file_diff->hunk + hunk_index + splittable_into,
879 file_diff->hunk + hunk_index + 1,
880 (file_diff->hunk_nr - hunk_index - splittable_into)
881 * sizeof(*hunk));
882 hunk = file_diff->hunk + hunk_index;
883 hunk->splittable_into = 1;
884 memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
885
886 header = &hunk->header;
887 header->old_count = header->new_count = 0;
888
889 current = hunk->start;
890 if (colored)
891 colored_current = hunk->colored_start;
892 marker = '\0';
893 context_line_count = 0;
894
895 while (splittable_into > 1) {
896 ch = s->plain.buf[current];
897
898 if (!ch)
899 BUG("buffer overrun while splitting hunks");
900
901 /*
902 * Is this the first context line after a chain of +/- lines?
903 * Then record the start of the next split hunk.
904 */
905 if ((marker == '-' || marker == '+') && ch == ' ') {
906 first = 0;
907 hunk[1].start = current;
908 if (colored)
909 hunk[1].colored_start = colored_current;
910 context_line_count = 0;
911 }
912
913 /*
914 * Was the previous line a +/- one? Alternatively, is this the
915 * first line (and not a +/- one)?
916 *
917 * Then just increment the appropriate counter and continue
918 * with the next line.
919 */
920 if (marker != ' ' || (ch != '-' && ch != '+')) {
921next_hunk_line:
922 /* Comment lines are attached to the previous line */
923 if (ch == '\\')
924 ch = marker ? marker : ' ';
925
926 /* current hunk not done yet */
927 if (ch == ' ')
928 context_line_count++;
929 else if (ch == '-')
930 header->old_count++;
931 else if (ch == '+')
932 header->new_count++;
933 else
934 BUG("unhandled diff marker: '%c'", ch);
935 marker = ch;
936 current = find_next_line(&s->plain, current);
937 if (colored)
938 colored_current =
939 find_next_line(&s->colored,
940 colored_current);
941 continue;
942 }
943
944 /*
945 * We got us the start of a new hunk!
946 *
947 * This is a context line, so it is shared with the previous
948 * hunk, if any.
949 */
950
951 if (first) {
952 if (header->old_count || header->new_count)
953 BUG("counts are off: %d/%d",
954 (int)header->old_count,
955 (int)header->new_count);
956
957 header->old_count = context_line_count;
958 header->new_count = context_line_count;
959 context_line_count = 0;
960 first = 0;
961 goto next_hunk_line;
962 }
963
964 remaining.old_offset += header->old_count;
965 remaining.old_count -= header->old_count;
966 remaining.new_offset += header->new_count;
967 remaining.new_count -= header->new_count;
968
969 /* initialize next hunk header's offsets */
970 hunk[1].header.old_offset =
971 header->old_offset + header->old_count;
972 hunk[1].header.new_offset =
973 header->new_offset + header->new_count;
974
975 /* add one split hunk */
976 header->old_count += context_line_count;
977 header->new_count += context_line_count;
978
979 hunk->end = current;
980 if (colored)
981 hunk->colored_end = colored_current;
982
983 hunk++;
984 hunk->splittable_into = 1;
985 hunk->use = hunk[-1].use;
986 header = &hunk->header;
987
988 header->old_count = header->new_count = context_line_count;
989 context_line_count = 0;
990
991 splittable_into--;
992 marker = ch;
993 }
994
995 /* last hunk simply gets the rest */
996 if (header->old_offset != remaining.old_offset)
997 BUG("miscounted old_offset: %lu != %lu",
998 header->old_offset, remaining.old_offset);
999 if (header->new_offset != remaining.new_offset)
1000 BUG("miscounted new_offset: %lu != %lu",
1001 header->new_offset, remaining.new_offset);
1002 header->old_count = remaining.old_count;
1003 header->new_count = remaining.new_count;
1004 hunk->end = end;
1005 if (colored)
1006 hunk->colored_end = colored_end;
1007
1008 return 0;
1009}
1010
bcdd297b
JS
1011static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1012{
1013 const char *plain = s->plain.buf;
1014 size_t current, eol, next;
1015
1016 if (!s->colored.len)
1017 return;
1018
1019 hunk->colored_start = s->colored.len;
1020 for (current = hunk->start; current < hunk->end; ) {
1021 for (eol = current; eol < hunk->end; eol++)
1022 if (plain[eol] == '\n')
1023 break;
1024 next = eol + (eol < hunk->end);
1025 if (eol > current && plain[eol - 1] == '\r')
1026 eol--;
1027
1028 strbuf_addstr(&s->colored,
1029 plain[current] == '-' ?
1030 s->s.file_old_color :
1031 plain[current] == '+' ?
1032 s->s.file_new_color :
1033 s->s.context_color);
1034 strbuf_add(&s->colored, plain + current, eol - current);
1035 strbuf_addstr(&s->colored, GIT_COLOR_RESET);
1036 if (next > eol)
1037 strbuf_add(&s->colored, plain + eol, next - eol);
1038 current = next;
1039 }
1040 hunk->colored_end = s->colored.len;
1041}
1042
1043static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1044{
1045 size_t i;
1046
1047 strbuf_reset(&s->buf);
1048 strbuf_commented_addf(&s->buf, _("Manual hunk edit mode -- see bottom for "
1049 "a quick guide.\n"));
1050 render_hunk(s, hunk, 0, 0, &s->buf);
1051 strbuf_commented_addf(&s->buf,
1052 _("---\n"
1053 "To remove '%c' lines, make them ' ' lines "
1054 "(context).\n"
1055 "To remove '%c' lines, delete them.\n"
1056 "Lines starting with %c will be removed.\n"),
d2a233cb
JS
1057 s->mode->is_reverse ? '+' : '-',
1058 s->mode->is_reverse ? '-' : '+',
1059 comment_line_char);
1060 strbuf_commented_addf(&s->buf, "%s", _(s->mode->edit_hunk_hint));
bcdd297b
JS
1061 /*
1062 * TRANSLATORS: 'it' refers to the patch mentioned in the previous
1063 * messages.
1064 */
1065 strbuf_commented_addf(&s->buf,
1066 _("If it does not apply cleanly, you will be "
1067 "given an opportunity to\n"
1068 "edit again. If all lines of the hunk are "
1069 "removed, then the edit is\n"
1070 "aborted and the hunk is left unchanged.\n"));
1071
1072 if (strbuf_edit_interactively(&s->buf, "addp-hunk-edit.diff", NULL) < 0)
1073 return -1;
1074
1075 /* strip out commented lines */
1076 hunk->start = s->plain.len;
1077 for (i = 0; i < s->buf.len; ) {
1078 size_t next = find_next_line(&s->buf, i);
1079
1080 if (s->buf.buf[i] != comment_line_char)
1081 strbuf_add(&s->plain, s->buf.buf + i, next - i);
1082 i = next;
1083 }
1084
1085 hunk->end = s->plain.len;
1086 if (hunk->end == hunk->start)
1087 /* The user aborted editing by deleting everything */
1088 return 0;
1089
1090 recolor_hunk(s, hunk);
1091
1092 /*
1093 * If the hunk header is intact, parse it, otherwise simply use the
1094 * hunk header prior to editing (which will adjust `hunk->start` to
1095 * skip the hunk header).
1096 */
1097 if (s->plain.buf[hunk->start] == '@' &&
1098 parse_hunk_header(s, hunk) < 0)
1099 return error(_("could not parse hunk header"));
1100
1101 return 1;
1102}
1103
1104static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1105 size_t orig_old_count, size_t orig_new_count)
1106{
1107 struct hunk_header *header = &hunk->header;
1108 size_t i;
1109
1110 header->old_count = header->new_count = 0;
1111 for (i = hunk->start; i < hunk->end; ) {
1112 switch (s->plain.buf[i]) {
1113 case '-':
1114 header->old_count++;
1115 break;
1116 case '+':
1117 header->new_count++;
1118 break;
1119 case ' ': case '\r': case '\n':
1120 header->old_count++;
1121 header->new_count++;
1122 break;
1123 }
1124
1125 i = find_next_line(&s->plain, i);
1126 }
1127
1128 return orig_old_count - orig_new_count
1129 - header->old_count + header->new_count;
1130}
1131
1132static int run_apply_check(struct add_p_state *s,
1133 struct file_diff *file_diff)
1134{
1135 struct child_process cp = CHILD_PROCESS_INIT;
1136
1137 strbuf_reset(&s->buf);
1138 reassemble_patch(s, file_diff, 1, &s->buf);
1139
1140 setup_child_process(s, &cp,
d2a233cb
JS
1141 "apply", "--check", NULL);
1142 argv_array_pushv(&cp.args, s->mode->apply_check_args);
bcdd297b
JS
1143 if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1144 return error(_("'git apply --cached' failed"));
1145
1146 return 0;
1147}
1148
1149static int prompt_yesno(struct add_p_state *s, const char *prompt)
1150{
1151 for (;;) {
1152 color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1153 fflush(stdout);
1154 if (strbuf_getline(&s->answer, stdin) == EOF)
1155 return -1;
1156 strbuf_trim_trailing_newline(&s->answer);
1157 switch (tolower(s->answer.buf[0])) {
1158 case 'n': return 0;
1159 case 'y': return 1;
1160 }
1161 }
1162}
1163
1164static int edit_hunk_loop(struct add_p_state *s,
1165 struct file_diff *file_diff, struct hunk *hunk)
1166{
1167 size_t plain_len = s->plain.len, colored_len = s->colored.len;
1168 struct hunk backup;
1169
1170 backup = *hunk;
1171
1172 for (;;) {
1173 int res = edit_hunk_manually(s, hunk);
1174 if (res == 0) {
1175 /* abandonded */
1176 *hunk = backup;
1177 return -1;
1178 }
1179
1180 if (res > 0) {
1181 hunk->delta +=
1182 recount_edited_hunk(s, hunk,
1183 backup.header.old_count,
1184 backup.header.new_count);
1185 if (!run_apply_check(s, file_diff))
1186 return 0;
1187 }
1188
1189 /* Drop edits (they were appended to s->plain) */
1190 strbuf_setlen(&s->plain, plain_len);
1191 strbuf_setlen(&s->colored, colored_len);
1192 *hunk = backup;
1193
1194 /*
1195 * TRANSLATORS: do not translate [y/n]
1196 * The program will only accept that input at this point.
1197 * Consider translating (saying "no" discards!) as
1198 * (saying "n" for "no" discards!) if the translation
1199 * of the word "no" does not start with n.
1200 */
1201 res = prompt_yesno(s, _("Your edited hunk does not apply. "
1202 "Edit again (saying \"no\" discards!) "
1203 "[y/n]? "));
1204 if (res < 1)
1205 return -1;
1206 }
1207}
1208
52628f94
JS
1209static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1210 int is_reverse)
1211{
1212 const char *reverse = is_reverse ? "-R" : NULL;
1213 struct child_process check_index = CHILD_PROCESS_INIT;
1214 struct child_process check_worktree = CHILD_PROCESS_INIT;
1215 struct child_process apply_index = CHILD_PROCESS_INIT;
1216 struct child_process apply_worktree = CHILD_PROCESS_INIT;
1217 int applies_index, applies_worktree;
1218
1219 setup_child_process(s, &check_index,
1220 "apply", "--cached", "--check", reverse, NULL);
1221 applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1222 NULL, 0, NULL, 0);
1223
1224 setup_child_process(s, &check_worktree,
1225 "apply", "--check", reverse, NULL);
1226 applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1227 NULL, 0, NULL, 0);
1228
1229 if (applies_worktree && applies_index) {
1230 setup_child_process(s, &apply_index,
1231 "apply", "--cached", reverse, NULL);
1232 pipe_command(&apply_index, diff->buf, diff->len,
1233 NULL, 0, NULL, 0);
1234
1235 setup_child_process(s, &apply_worktree,
1236 "apply", reverse, NULL);
1237 pipe_command(&apply_worktree, diff->buf, diff->len,
1238 NULL, 0, NULL, 0);
1239
1240 return 1;
1241 }
1242
1243 if (!applies_index) {
1244 err(s, _("The selected hunks do not apply to the index!"));
1245 if (prompt_yesno(s, _("Apply them to the worktree "
1246 "anyway? ")) > 0) {
1247 setup_child_process(s, &apply_worktree,
1248 "apply", reverse, NULL);
1249 return pipe_command(&apply_worktree, diff->buf,
1250 diff->len, NULL, 0, NULL, 0);
1251 }
1252 err(s, _("Nothing was applied.\n"));
1253 } else
1254 /* As a last resort, show the diff to the user */
1255 fwrite(diff->buf, diff->len, 1, stderr);
1256
1257 return 0;
1258}
1259
9254bdfb
JS
1260#define SUMMARY_HEADER_WIDTH 20
1261#define SUMMARY_LINE_WIDTH 80
1262static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1263 struct strbuf *out)
1264{
1265 struct hunk_header *header = &hunk->header;
1266 struct strbuf *plain = &s->plain;
1267 size_t len = out->len, i;
1268
1269 strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1270 header->old_offset, header->old_count,
1271 header->new_offset, header->new_count);
1272 if (out->len - len < SUMMARY_HEADER_WIDTH)
1273 strbuf_addchars(out, ' ',
1274 SUMMARY_HEADER_WIDTH + len - out->len);
1275 for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1276 if (plain->buf[i] != ' ')
1277 break;
1278 if (i < hunk->end)
1279 strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1280 if (out->len - len > SUMMARY_LINE_WIDTH)
1281 strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1282 strbuf_complete_line(out);
1283}
1284
1285#define DISPLAY_HUNKS_LINES 20
1286static size_t display_hunks(struct add_p_state *s,
1287 struct file_diff *file_diff, size_t start_index)
1288{
1289 size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1290
1291 if (end_index > file_diff->hunk_nr)
1292 end_index = file_diff->hunk_nr;
1293
1294 while (start_index < end_index) {
1295 struct hunk *hunk = file_diff->hunk + start_index++;
1296
1297 strbuf_reset(&s->buf);
1298 strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1299 : hunk->use == SKIP_HUNK ? '-' : ' ',
1300 (int)start_index);
1301 summarize_hunk(s, hunk, &s->buf);
1302 fputs(s->buf.buf, stdout);
1303 }
1304
1305 return end_index;
1306}
1307
54d9d9b2
JS
1308static const char help_patch_remainder[] =
1309N_("j - leave this hunk undecided, see next undecided hunk\n"
f6aa7ecc
JS
1310 "J - leave this hunk undecided, see next hunk\n"
1311 "k - leave this hunk undecided, see previous undecided hunk\n"
1312 "K - leave this hunk undecided, see previous hunk\n"
9254bdfb 1313 "g - select a hunk to go to\n"
d6cf8733 1314 "/ - search for a hunk matching the given regex\n"
510aeca1 1315 "s - split the current hunk into smaller hunks\n"
bcdd297b 1316 "e - manually edit the current hunk\n"
f6aa7ecc
JS
1317 "? - print help\n");
1318
80399aec
JS
1319static int patch_update_file(struct add_p_state *s,
1320 struct file_diff *file_diff)
f6aa7ecc
JS
1321{
1322 size_t hunk_index = 0;
1323 ssize_t i, undecided_previous, undecided_next;
1324 struct hunk *hunk;
1325 char ch;
1326 struct child_process cp = CHILD_PROCESS_INIT;
ade246ef 1327 int colored = !!s->colored.len, quit = 0;
0ecd9d27 1328 enum prompt_mode_type prompt_mode_type;
f6aa7ecc 1329
80399aec 1330 if (!file_diff->hunk_nr)
f6aa7ecc
JS
1331 return 0;
1332
1333 strbuf_reset(&s->buf);
5906d5de 1334 render_diff_header(s, file_diff, colored, &s->buf);
f6aa7ecc
JS
1335 fputs(s->buf.buf, stdout);
1336 for (;;) {
80399aec 1337 if (hunk_index >= file_diff->hunk_nr)
f6aa7ecc 1338 hunk_index = 0;
80399aec 1339 hunk = file_diff->hunk + hunk_index;
f6aa7ecc
JS
1340
1341 undecided_previous = -1;
1342 for (i = hunk_index - 1; i >= 0; i--)
80399aec 1343 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
f6aa7ecc
JS
1344 undecided_previous = i;
1345 break;
1346 }
1347
1348 undecided_next = -1;
80399aec
JS
1349 for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1350 if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
f6aa7ecc
JS
1351 undecided_next = i;
1352 break;
1353 }
1354
1355 /* Everything decided? */
1356 if (undecided_previous < 0 && undecided_next < 0 &&
1357 hunk->use != UNDECIDED_HUNK)
1358 break;
1359
1360 strbuf_reset(&s->buf);
25ea47af 1361 render_hunk(s, hunk, 0, colored, &s->buf);
f6aa7ecc
JS
1362 fputs(s->buf.buf, stdout);
1363
1364 strbuf_reset(&s->buf);
1365 if (undecided_previous >= 0)
1366 strbuf_addstr(&s->buf, ",k");
1367 if (hunk_index)
1368 strbuf_addstr(&s->buf, ",K");
1369 if (undecided_next >= 0)
1370 strbuf_addstr(&s->buf, ",j");
80399aec 1371 if (hunk_index + 1 < file_diff->hunk_nr)
f6aa7ecc 1372 strbuf_addstr(&s->buf, ",J");
9254bdfb 1373 if (file_diff->hunk_nr > 1)
d6cf8733 1374 strbuf_addstr(&s->buf, ",g,/");
510aeca1
JS
1375 if (hunk->splittable_into > 1)
1376 strbuf_addstr(&s->buf, ",s");
bcdd297b
JS
1377 if (hunk_index + 1 > file_diff->mode_change &&
1378 !file_diff->deleted)
1379 strbuf_addstr(&s->buf, ",e");
0ecd9d27
JS
1380
1381 if (file_diff->deleted)
1382 prompt_mode_type = PROMPT_DELETION;
1383 else if (file_diff->mode_change && !hunk_index)
1384 prompt_mode_type = PROMPT_MODE_CHANGE;
1385 else
1386 prompt_mode_type = PROMPT_HUNK;
1387
12c24cf8
JS
1388 color_fprintf(stdout, s->s.prompt_color,
1389 "(%"PRIuMAX"/%"PRIuMAX") ",
80399aec
JS
1390 (uintmax_t)hunk_index + 1,
1391 (uintmax_t)file_diff->hunk_nr);
12c24cf8 1392 color_fprintf(stdout, s->s.prompt_color,
d2a233cb
JS
1393 _(s->mode->prompt_mode[prompt_mode_type]),
1394 s->buf.buf);
f6aa7ecc
JS
1395 fflush(stdout);
1396 if (strbuf_getline(&s->answer, stdin) == EOF)
1397 break;
1398 strbuf_trim_trailing_newline(&s->answer);
1399
1400 if (!s->answer.len)
1401 continue;
1402 ch = tolower(s->answer.buf[0]);
1403 if (ch == 'y') {
1404 hunk->use = USE_HUNK;
1405soft_increment:
1406 hunk_index = undecided_next < 0 ?
80399aec 1407 file_diff->hunk_nr : undecided_next;
f6aa7ecc
JS
1408 } else if (ch == 'n') {
1409 hunk->use = SKIP_HUNK;
1410 goto soft_increment;
1411 } else if (ch == 'a') {
80399aec
JS
1412 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1413 hunk = file_diff->hunk + hunk_index;
f6aa7ecc
JS
1414 if (hunk->use == UNDECIDED_HUNK)
1415 hunk->use = USE_HUNK;
1416 }
ade246ef 1417 } else if (ch == 'd' || ch == 'q') {
80399aec
JS
1418 for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1419 hunk = file_diff->hunk + hunk_index;
f6aa7ecc
JS
1420 if (hunk->use == UNDECIDED_HUNK)
1421 hunk->use = SKIP_HUNK;
1422 }
ade246ef
JS
1423 if (ch == 'q') {
1424 quit = 1;
1425 break;
1426 }
7584dd3c
JS
1427 } else if (s->answer.buf[0] == 'K') {
1428 if (hunk_index)
1429 hunk_index--;
1430 else
1431 err(s, _("No previous hunk"));
1432 } else if (s->answer.buf[0] == 'J') {
80399aec 1433 if (hunk_index + 1 < file_diff->hunk_nr)
7584dd3c
JS
1434 hunk_index++;
1435 else
1436 err(s, _("No next hunk"));
1437 } else if (s->answer.buf[0] == 'k') {
1438 if (undecided_previous >= 0)
1439 hunk_index = undecided_previous;
1440 else
1441 err(s, _("No previous hunk"));
1442 } else if (s->answer.buf[0] == 'j') {
1443 if (undecided_next >= 0)
1444 hunk_index = undecided_next;
1445 else
1446 err(s, _("No next hunk"));
9254bdfb
JS
1447 } else if (s->answer.buf[0] == 'g') {
1448 char *pend;
1449 unsigned long response;
1450
1451 if (file_diff->hunk_nr < 2) {
1452 err(s, _("No other hunks to goto"));
1453 continue;
1454 }
1455 strbuf_remove(&s->answer, 0, 1);
1456 strbuf_trim(&s->answer);
1457 i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1458 if (i < file_diff->mode_change)
1459 i = file_diff->mode_change;
1460 while (s->answer.len == 0) {
1461 i = display_hunks(s, file_diff, i);
1462 printf("%s", i < file_diff->hunk_nr ?
1463 _("go to which hunk (<ret> to see "
1464 "more)? ") : _("go to which hunk? "));
1465 fflush(stdout);
1466 if (strbuf_getline(&s->answer,
1467 stdin) == EOF)
1468 break;
1469 strbuf_trim_trailing_newline(&s->answer);
1470 }
1471
1472 strbuf_trim(&s->answer);
1473 response = strtoul(s->answer.buf, &pend, 10);
1474 if (*pend || pend == s->answer.buf)
1475 err(s, _("Invalid number: '%s'"),
1476 s->answer.buf);
1477 else if (0 < response && response <= file_diff->hunk_nr)
1478 hunk_index = response - 1;
1479 else
1480 err(s, Q_("Sorry, only %d hunk available.",
1481 "Sorry, only %d hunks available.",
1482 file_diff->hunk_nr),
1483 (int)file_diff->hunk_nr);
d6cf8733
JS
1484 } else if (s->answer.buf[0] == '/') {
1485 regex_t regex;
1486 int ret;
1487
1488 if (file_diff->hunk_nr < 2) {
1489 err(s, _("No other hunks to search"));
1490 continue;
1491 }
1492 strbuf_remove(&s->answer, 0, 1);
1493 strbuf_trim_trailing_newline(&s->answer);
1494 if (s->answer.len == 0) {
1495 printf("%s", _("search for regex? "));
1496 fflush(stdout);
1497 if (strbuf_getline(&s->answer,
1498 stdin) == EOF)
1499 break;
1500 strbuf_trim_trailing_newline(&s->answer);
1501 if (s->answer.len == 0)
1502 continue;
1503 }
1504 ret = regcomp(&regex, s->answer.buf,
1505 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1506 if (ret) {
1507 char errbuf[1024];
1508
1509 regerror(ret, &regex, errbuf, sizeof(errbuf));
1510 err(s, _("Malformed search regexp %s: %s"),
1511 s->answer.buf, errbuf);
1512 continue;
1513 }
1514 i = hunk_index;
1515 for (;;) {
1516 /* render the hunk into a scratch buffer */
1517 render_hunk(s, file_diff->hunk + i, 0, 0,
1518 &s->buf);
1519 if (regexec(&regex, s->buf.buf, 0, NULL, 0)
1520 != REG_NOMATCH)
1521 break;
1522 i++;
1523 if (i == file_diff->hunk_nr)
1524 i = 0;
1525 if (i != hunk_index)
1526 continue;
1527 err(s, _("No hunk matches the given pattern"));
1528 break;
1529 }
1530 hunk_index = i;
510aeca1
JS
1531 } else if (s->answer.buf[0] == 's') {
1532 size_t splittable_into = hunk->splittable_into;
1533 if (splittable_into < 2)
1534 err(s, _("Sorry, cannot split this hunk"));
1535 else if (!split_hunk(s, file_diff,
1536 hunk - file_diff->hunk))
1537 color_fprintf_ln(stdout, s->s.header_color,
1538 _("Split into %d hunks."),
1539 (int)splittable_into);
bcdd297b
JS
1540 } else if (s->answer.buf[0] == 'e') {
1541 if (hunk_index + 1 == file_diff->mode_change)
1542 err(s, _("Sorry, cannot edit this hunk"));
1543 else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1544 hunk->use = USE_HUNK;
1545 goto soft_increment;
1546 }
54d9d9b2
JS
1547 } else {
1548 const char *p = _(help_patch_remainder), *eol = p;
1549
1550 color_fprintf(stdout, s->s.help_color, "%s",
d2a233cb 1551 _(s->mode->help_patch_text));
54d9d9b2
JS
1552
1553 /*
1554 * Show only those lines of the remainder that are
1555 * actually applicable with the current hunk.
1556 */
1557 for (; *p; p = eol + (*eol == '\n')) {
1558 eol = strchrnul(p, '\n');
1559
1560 /*
1561 * `s->buf` still contains the part of the
1562 * commands shown in the prompt that are not
1563 * always available.
1564 */
1565 if (*p != '?' && !strchr(s->buf.buf, *p))
1566 continue;
1567
1568 color_fprintf_ln(stdout, s->s.help_color,
1569 "%.*s", (int)(eol - p), p);
1570 }
1571 }
f6aa7ecc
JS
1572 }
1573
1574 /* Any hunk to be used? */
80399aec
JS
1575 for (i = 0; i < file_diff->hunk_nr; i++)
1576 if (file_diff->hunk[i].use == USE_HUNK)
f6aa7ecc
JS
1577 break;
1578
80399aec 1579 if (i < file_diff->hunk_nr) {
f6aa7ecc
JS
1580 /* At least one hunk selected: apply */
1581 strbuf_reset(&s->buf);
bcdd297b 1582 reassemble_patch(s, file_diff, 0, &s->buf);
f6aa7ecc 1583
25ea47af 1584 discard_index(s->s.r->index);
52628f94
JS
1585 if (s->mode->apply_for_checkout)
1586 apply_for_checkout(s, &s->buf,
1587 s->mode->is_reverse);
1588 else {
1589 setup_child_process(s, &cp, "apply", NULL);
1590 argv_array_pushv(&cp.args, s->mode->apply_args);
1591 if (pipe_command(&cp, s->buf.buf, s->buf.len,
1592 NULL, 0, NULL, 0))
1593 error(_("'git apply' failed"));
1594 }
25ea47af
JS
1595 if (!repo_read_index(s->s.r))
1596 repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
f6aa7ecc
JS
1597 1, NULL, NULL, NULL);
1598 }
1599
1600 putchar('\n');
ade246ef 1601 return quit;
f6aa7ecc
JS
1602}
1603
d2a233cb
JS
1604int run_add_p(struct repository *r, enum add_p_mode mode,
1605 const char *revision, const struct pathspec *ps)
f6aa7ecc 1606{
25ea47af
JS
1607 struct add_p_state s = {
1608 { r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1609 };
2e408319 1610 size_t i, binary_count = 0;
25ea47af
JS
1611
1612 init_add_i_state(&s.s, r);
f6aa7ecc 1613
36bae1dc
JS
1614 if (mode == ADD_P_STASH)
1615 s.mode = &patch_mode_stash;
1616 else if (mode == ADD_P_RESET) {
1617 if (!revision || !strcmp(revision, "HEAD"))
1618 s.mode = &patch_mode_reset_head;
1619 else
1620 s.mode = &patch_mode_reset_nothead;
52628f94
JS
1621 } else if (mode == ADD_P_CHECKOUT) {
1622 if (!revision)
1623 s.mode = &patch_mode_checkout_index;
1624 else if (!strcmp(revision, "HEAD"))
1625 s.mode = &patch_mode_checkout_head;
1626 else
1627 s.mode = &patch_mode_checkout_nothead;
cee6cb73
JS
1628 } else if (mode == ADD_P_WORKTREE) {
1629 if (!revision)
1630 s.mode = &patch_mode_checkout_index;
1631 else if (!strcmp(revision, "HEAD"))
1632 s.mode = &patch_mode_worktree_head;
1633 else
1634 s.mode = &patch_mode_worktree_nothead;
36bae1dc
JS
1635 } else
1636 s.mode = &patch_mode_add;
d2a233cb
JS
1637 s.revision = revision;
1638
f6aa7ecc 1639 if (discard_index(r->index) < 0 || repo_read_index(r) < 0 ||
36bae1dc
JS
1640 (!s.mode->index_only &&
1641 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1642 NULL, NULL, NULL) < 0) ||
f6aa7ecc
JS
1643 parse_diff(&s, ps) < 0) {
1644 strbuf_release(&s.plain);
e3bd11b4 1645 strbuf_release(&s.colored);
180f48df 1646 clear_add_i_state(&s.s);
f6aa7ecc
JS
1647 return -1;
1648 }
1649
80399aec 1650 for (i = 0; i < s.file_diff_nr; i++)
2e408319
JS
1651 if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1652 binary_count++;
1653 else if (patch_update_file(&s, s.file_diff + i))
80399aec 1654 break;
f6aa7ecc 1655
2e408319
JS
1656 if (s.file_diff_nr == 0)
1657 fprintf(stderr, _("No changes.\n"));
1658 else if (binary_count == s.file_diff_nr)
1659 fprintf(stderr, _("Only binary files changed.\n"));
1660
f6aa7ecc
JS
1661 strbuf_release(&s.answer);
1662 strbuf_release(&s.buf);
1663 strbuf_release(&s.plain);
e3bd11b4 1664 strbuf_release(&s.colored);
180f48df 1665 clear_add_i_state(&s.s);
f6aa7ecc
JS
1666 return 0;
1667}