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