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