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