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