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