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