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