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