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