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